问:
Accessing XML data from C#
I'm struggling with accessing to the data stored in the XML file from C#. I read a lot of posts - the closest one was here - but still can't get it working.

The xml node looks like below:

```<code><Prop Name='StartTime' Type='Number' Flags='0x0'>
<Value>171.8032865</Value>
</Prop>
</code>```

I need to know what is the value of the property named 'StartTime'

EDIT: The node above is a one of the many in the xml document. And it is nested amongst other nodes. I need to find ALL values of the property with the name 'StartTime'.

I use XAML.

EDIT2: I think it'll better if I display bigger chunk of the xml I have to get the data from. It looks like Kaz's solution is the closest the demanded solution, but it fails if I load whole xml.

XML file:

```<code><Prop Type='TEResult' Flags='0x0'>
<Prop Name='TS' Type='Obj' Flags='0x0'>
    <Prop Name='SequenceCall' Type='Obj' Flags='0x0'>
        <Prop Name='ResultList' Type='Array' LBound='[0]' HBound='[3]' ElementType='Obj' Flags='0x0'>
            <ArrayElementPrototype Type='TEResult' Flags='0x0'>
            </ArrayElementPrototype>
            <Value ID='[0]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8032865</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0005158</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 1</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:TbZA+59stkivP1pqe//sUB</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>5</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[1]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8135159</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0000802</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>1</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 2</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:7RheSM0MDEGTAnRrrfGNcB</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>6</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[2]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8240739</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.000081</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>2</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 3</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:pWFWDejvo0GThcOYVssHBA</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>7</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[3]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8270851</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0001041</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>3</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 4</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:w+ziJ/u2bkWz+F3kWa4mpC</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>8</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
        </Prop>
        <Prop Name='SequenceFile' Type='String' Flags='0x0'>
            <Value>C:\Users\Public\Documents\National Instruments\TestStand 2010 SP1\Sequence File 16.seq</Value>
        </Prop>
        <Prop Name='Sequence' Type='String' Flags='0x0'>
            <Value>MainSequence</Value>
        </Prop>
        <Prop Name='Status' Type='String' Flags='0x0'>
            <Value>Failed</Value>
        </Prop>
    </Prop>
    <Prop Name='StartTime' Type='Number' Flags='0x0'>
        <Value>171.6948629</Value>
    </Prop>
    <Prop Name='TotalTime' Type='Number' Flags='0x0'>
        <Value>0.1359434</Value>
    </Prop>
    <Prop Name='ModuleTime' Type='Number' Flags='0x0'>
        <Value>0.1357157</Value>
    </Prop>
    <Prop Name='Index' Type='Number' Flags='0x0'>
        <Value>31</Value>
    </Prop>
    <Prop Name='StepName' Type='String' Flags='0x0'>
        <Value>MainSequence Callback</Value>
    </Prop>
    <Prop Name='StepGroup' Type='String' Flags='0x0'>
        <Value>Main</Value>
    </Prop>
    <Prop Name='StepId' Type='String' Flags='0x0'>
        <Value>ID#:xnW0PT0ORE2el7wF7uaxyB</Value>
    </Prop>
    <Prop Name='Id' Type='Number' Flags='0x0'>
        <Value>4</Value>
    </Prop>
    <Prop Name='StepType' Type='String' Flags='0x0'>
        <Value>SequenceCall</Value>
    </Prop>
    <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
        <Value>0</Value>
    </Prop>
    <Prop Name='SequenceFilePostResultListEntry' Type='Obj' Flags='0x0'>
        <Prop Name='ResultList' Type='Array' LBound='[0]' HBound='[]' ElementType='Obj' Flags='0x0'>
            <ArrayElementPrototype Type='TEResult' Flags='0x0'>
            </ArrayElementPrototype>
        </Prop>
        <Prop Name='SequenceFile' Type='String' Flags='0x0'>
            <Value>C:\Program Files\National Instruments\TestStand 2010 SP1\Components\Models\TestStandModels\SequentialModel.seq</Value>
        </Prop>
        <Prop Name='Sequence' Type='String' Flags='0x0'>
            <Value>SequenceFilePostResultListEntry</Value>
        </Prop>
        <Prop Name='Status' Type='String' Flags='0x0'>
            <Value>Passed</Value>
        </Prop>
    </Prop>
</Prop>
</code>```

答:
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLdata
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("c:\\somexmlfile.xml");
             XmlDocument doc1 = new XmlDocument();
                doc1.LoadXml (doc.ToString());
                XmlElement element = doc1.DocumentElement;
                XmlNode node= element.ChildNodes[0];

            double value = double.Parse(node.InnerText);
        }
    }
}
</code>```

You can try this

Title: Accessing XML data from C#

Body:
I'm struggling with accessing to the data stored in the XML file from C#. I read a lot of posts - the closest one was here - but still can't get it working.

The xml node looks like below:

<Prop Name='StartTime' Type='Number' Flags='0x0'>
<Value>171.8032865</Value>
</Prop>

I need to know what is the value of the property named 'StartTime'

EDIT: The node above is a one of the many in the xml document. And it is nested amongst other nodes. I need to find ALL values of the property with the name 'StartTime'.

I use XAML.

EDIT2: I think it'll better if I display bigger chunk of the xml I have to get the data from. It looks like Kaz's solution is the closest the demanded solution, but it fails if I load whole xml.

XML file:

<Prop Type='TEResult' Flags='0x0'>
<Prop Name='TS' Type='Obj' Flags='0x0'>
    <Prop Name='SequenceCall' Type='Obj' Flags='0x0'>
        <Prop Name='ResultList' Type='Array' LBound='[0]' HBound='[3]' ElementType='Obj' Flags='0x0'>
            <ArrayElementPrototype Type='TEResult' Flags='0x0'>
            </ArrayElementPrototype>
            <Value ID='[0]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8032865</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0005158</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 1</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:TbZA+59stkivP1pqe//sUB</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>5</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[1]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8135159</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0000802</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>1</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 2</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:7RheSM0MDEGTAnRrrfGNcB</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>6</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[2]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8240739</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.000081</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>2</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 3</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:pWFWDejvo0GThcOYVssHBA</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>7</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
            <Value ID='[3]'>
                <Prop Type='TEResult' Flags='0x0'>
                    <Prop Name='Error' Type='Obj' TypeName='Error' Flags='0x400000'>
                        <Prop Name='Code' Type='Number' Flags='0x400000'>
                            <Value>0</Value>
                        </Prop>
                        <Prop Name='Msg' Type='String' Flags='0x400000'>
                            <Value></Value>
                        </Prop>
                        <Prop Name='Occurred' Type='Boolean' Flags='0x400000'>
                            <Value>False</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Status' Type='String' Flags='0x400000'>
                        <Value>Failed</Value>
                    </Prop>
                    <Prop Name='Numeric' Type='Number' Flags='0x2400'>
                        <Value>0</Value>
                    </Prop>
                    <Prop Name='ReportText' Type='String' Flags='0x400000'>
                        <Value></Value>
                    </Prop>
                    <Prop Name='Common' Type='Obj' TypeName='CommonResults' Flags='0x0'>
                        <Prop Name='IncludeInReport' Type='Boolean' Flags='0x0'>
                            <Value>True</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='TS' Type='Obj' Flags='0x0'>
                        <Prop Name='StartTime' Type='Number' Flags='0x0'>
                            <Value>171.8270851</Value>
                        </Prop>
                        <Prop Name='TotalTime' Type='Number' Flags='0x0'>
                            <Value>0.0001041</Value>
                        </Prop>
                        <Prop Name='Index' Type='Number' Flags='0x0'>
                            <Value>3</Value>
                        </Prop>
                        <Prop Name='StepName' Type='String' Flags='0x0'>
                            <Value>Test 4</Value>
                        </Prop>
                        <Prop Name='StepGroup' Type='String' Flags='0x0'>
                            <Value>Main</Value>
                        </Prop>
                        <Prop Name='StepId' Type='String' Flags='0x0'>
                            <Value>ID#:w+ziJ/u2bkWz+F3kWa4mpC</Value>
                        </Prop>
                        <Prop Name='Id' Type='Number' Flags='0x0'>
                            <Value>8</Value>
                        </Prop>
                        <Prop Name='StepType' Type='String' Flags='0x0'>
                            <Value>NumericLimitTest</Value>
                        </Prop>
                        <Prop Name='StepCausedSequenceFailure' Type='Boolean' Flags='0x0'>
                            <Value>False</Value>
                        </Prop>
                        <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
                            <Value>0</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Limits' Type='Obj' Flags='0x3000'>
                        <Prop Name='Low' Type='Number' Flags='0x0'>
                            <Value>9</Value>
                        </Prop>
                        <Prop Name='High' Type='Number' Flags='0x0'>
                            <Value>11</Value>
                        </Prop>
                    </Prop>
                    <Prop Name='Comp' Type='String' Flags='0x3000'>
                        <Value>GELE</Value>
                    </Prop>
                </Prop>
            </Value>
        </Prop>
        <Prop Name='SequenceFile' Type='String' Flags='0x0'>
            <Value>C:\Users\Public\Documents\National Instruments\TestStand 2010 SP1\Sequence File 16.seq</Value>
        </Prop>
        <Prop Name='Sequence' Type='String' Flags='0x0'>
            <Value>MainSequence</Value>
        </Prop>
        <Prop Name='Status' Type='String' Flags='0x0'>
            <Value>Failed</Value>
        </Prop>
    </Prop>
    <Prop Name='StartTime' Type='Number' Flags='0x0'>
        <Value>171.6948629</Value>
    </Prop>
    <Prop Name='TotalTime' Type='Number' Flags='0x0'>
        <Value>0.1359434</Value>
    </Prop>
    <Prop Name='ModuleTime' Type='Number' Flags='0x0'>
        <Value>0.1357157</Value>
    </Prop>
    <Prop Name='Index' Type='Number' Flags='0x0'>
        <Value>31</Value>
    </Prop>
    <Prop Name='StepName' Type='String' Flags='0x0'>
        <Value>MainSequence Callback</Value>
    </Prop>
    <Prop Name='StepGroup' Type='String' Flags='0x0'>
        <Value>Main</Value>
    </Prop>
    <Prop Name='StepId' Type='String' Flags='0x0'>
        <Value>ID#:xnW0PT0ORE2el7wF7uaxyB</Value>
    </Prop>
    <Prop Name='Id' Type='Number' Flags='0x0'>
        <Value>4</Value>
    </Prop>
    <Prop Name='StepType' Type='String' Flags='0x0'>
        <Value>SequenceCall</Value>
    </Prop>
    <Prop Name='BlockLevel' Type='Number' Flags='0x0'>
        <Value>0</Value>
    </Prop>
    <Prop Name='SequenceFilePostResultListEntry' Type='Obj' Flags='0x0'>
        <Prop Name='ResultList' Type='Array' LBound='[0]' HBound='[]' ElementType='Obj' Flags='0x0'>
            <ArrayElementPrototype Type='TEResult' Flags='0x0'>
            </ArrayElementPrototype>
        </Prop>
        <Prop Name='SequenceFile' Type='String' Flags='0x0'>
            <Value>C:\Program Files\National Instruments\TestStand 2010 SP1\Components\Models\TestStandModels\SequentialModel.seq</Value>
        </Prop>
        <Prop Name='Sequence' Type='String' Flags='0x0'>
            <Value>SequenceFilePostResultListEntry</Value>
        </Prop>
        <Prop Name='Status' Type='String' Flags='0x0'>
            <Value>Passed</Value>
        </Prop>
    </Prop>
</Prop>

Body:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLdata
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("c:\\somexmlfile.xml");
             XmlDocument doc1 = new XmlDocument();
                doc1.LoadXml (doc.ToString());
                XmlElement element = doc1.DocumentElement;
                XmlNode node= element.ChildNodes[0];

            double value = double.Parse(node.InnerText);
        }
    }
}

You can try this


来源: stackexchange

问:
C# statement inside using block returns null
I'm new to C# and curious about next example:

Imagine we have such code:

```<code>private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}
</code>```

And:

```<code>private static byte[] Compress(byte[] data)
{
    using (var output = new MemoryStream())
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
        return output.ToArray();
    }
}
</code>```

The first example works as expected, while the latter just returns null.
How does using work internally?
I expect it to work like simple try/finally, but it seems it closes MemoryStream before invoking toArray.

On the other hand following code works as expected too, which brings even more mysteriousness:

```<code>private static byte[] Decompress(byte[] payload)
{
   using(var inputStream = new MemoryStream(payload))
   using(var outputStream = new MemoryStream())
   using (var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress))
   {
       deflateStream.CopyTo(outputStream);
       return outputStream.ToArray();
   }
}
</code>```

答:
You are understanding incorrectly the usage of the using statement, in the first example works as intended because you never disposed the MemoryStream. While in the second statement you are disposing the MemoryStream as soon as you are ending the DeflateStream

First of all, you should always dispose your streams as soon as they re done, i had messy results when not disposing them correctly.

Now, I ll try to explain where you are wrong and how to correct each of those 2 examples which would be the same for the third one (its like the second)

First example (solution):

```<code>private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    var ret = output.ToArray();
    output.Dispose();
    return ret;
}
</code>```

Second example (solution) equivalent to the above code:

```<code>private static byte[] Compress(byte[] data)
{
    byte[] ret;
    using (var output = new MemoryStream())
    {
      using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
      {
         deflateStream.Write(data, 0, data.Length);
         ret = output.ToArray();
      }
    }
    return ret;
}
</code>```

in the second example i added the brackets so you understand what you are really doing with the using, its the same as if you are writting a one line action for a true or false in an if statement.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to C# and curious about next example:

Imagine we have such code:

private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}

And:

private static byte[] Compress(byte[] data)
{
    using (var output = new MemoryStream())
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
        return output.ToArray();
    }
}

The first example works as expected, while the latter just returns null.
How does using work internally?
I expect it to work like simple try/finally, but it seems it closes MemoryStream before invoking toArray.

On the other hand following code works as expected too, which brings even more mysteriousness:

private static byte[] Decompress(byte[] payload)
{
   using(var inputStream = new MemoryStream(payload))
   using(var outputStream = new MemoryStream())
   using (var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress))
   {
       deflateStream.CopyTo(outputStream);
       return outputStream.ToArray();
   }
}

Body:
You are understanding incorrectly the usage of the using statement, in the first example works as intended because you never disposed the MemoryStream. While in the second statement you are disposing the MemoryStream as soon as you are ending the DeflateStream

First of all, you should always dispose your streams as soon as they re done, i had messy results when not disposing them correctly.

Now, I ll try to explain where you are wrong and how to correct each of those 2 examples which would be the same for the third one (its like the second)

First example (solution):

private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    var ret = output.ToArray();
    output.Dispose();
    return ret;
}

Second example (solution) equivalent to the above code:

private static byte[] Compress(byte[] data)
{
    byte[] ret;
    using (var output = new MemoryStream())
    {
      using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
      {
         deflateStream.Write(data, 0, data.Length);
         ret = output.ToArray();
      }
    }
    return ret;
}

in the second example i added the brackets so you understand what you are really doing with the using, its the same as if you are writting a one line action for a true or false in an if statement.


问:
Difference between binary tree and binary search tree
Can anyone please explain the difference between binary tree and binary search tree with an example?

答:
A tree can be called as a binary tree if and only if the maximum number of children of any of the nodes is two.

A tree can be called as a binary search tree if and only if the maximum number of children of any of the nodes is two and the left child is always smaller than the right child.

ContentLicense: CC BY-SA 3.0


问:
Is sed auto in-place substitution?
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

```<code> echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"
</code>```

The result is

```<code>dd dd
</code>```

and wish it would be

```<code>qq dd
</code>```

Also via "looping" we get the same result.

```<code>echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"
</code>```

its petty, very disappointing bug !!

Any suggestion why it's happening?

答:
Maybe it is the behaviour of the y/// command you are looking for:

▶ echo "ss qq" | sed 'y/sq/qd/'
qq dd
```

This will transform all s into q and all q into d character by character.

Title: Is sed auto in-place substitution?

Body:
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

 echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"

The result is

dd dd

and wish it would be

qq dd

Also via "looping" we get the same result.

echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"

its petty, very disappointing bug !!

Any suggestion why it's happening?

Body:
Maybe it is the behaviour of the y/// command you are looking for:

▶ echo "ss qq" | sed 'y/sq/qd/'
qq dd

This will transform all s into q and all q into d character by character.


答:
You're modifying the numbers ahead, and then you check the next one. So you actually create an interim result and the final outcome therefore, in a way, is correct:

```<code>[ 2, 2, 4, 8] -> [ 0, 4, 4, 8 ] -> [ 0, 0, 8, 8 ] -> [ 0, 0, 0, 16 ]
  ^  ^                ^  ^                 ^  ^                  ^
</code>```

If you want to ignore changes made in the same run, you can increase j by 1 once you find a change:

Example that does all combinations per row, without taking current modifications into account

function solution(x) {
  for (let i = 0; i < x.length; i++) {
    for (let j = 0; j < x.length; j++) {
      if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
        x[i][j + 1] = x[i][j] * 2;
        x[i][j] = 0;
        j += 1;
      }
    }
  }
  return JSON.stringify(x)
}

console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))```
</div>
</div>
</p>

<p>If you just want 1 change per row, you can use <code>break</code></p>

<h3>Example with <code>break</code>, only does <em>1</em> update per row</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function solution(x) {
  for (let i = 0; i < x.length; i++) {
    for (let j = 0; j < x.length; j++) {
      if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
        x[i][j + 1] = x[i][j] * 2;
        x[i][j] = 0;
        // If you only want one move, you can break here
        break;
      }
    }
  }
  return JSON.stringify(x)
}

console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))</code>```

Title: Do only one move to right in 2048 game

Body:
I have 4x4 matrix like in game 2048, and I need to print result of one move to right. For example we have matrix:

0 0 2 2
4 4 8 4
64 64 8 4
16 8 64 8

Result is:

0 0 0 4
0 8 8 4
0 128 8 4
16 8 64 8

My code:

function solution(x){
  for (let i = 0; i < x.length; i++){
   for (let j = 0; j < x.length; j++){
     if (x[i][j] == x[i][j+1]){
        x[i][j+1] = x[i][j+1] * 2;
        x[i][j] = 0;
      }
   }
  }
  return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))

In the second version I get wrong result on the first row [0,0,0,16], the correct result is [0, 4, 4, 8]

Body:
You're modifying the numbers ahead, and then you check the next one. So you actually create an interim result and the final outcome therefore, in a way, is correct:

[ 2, 2, 4, 8] -> [ 0, 4, 4, 8 ] -> [ 0, 0, 8, 8 ] -> [ 0, 0, 0, 16 ]
  ^  ^                ^  ^                 ^  ^                  ^

If you want to ignore changes made in the same run, you can increase j by 1 once you find a change:

Example that does all combinations per row, without taking current modifications into account

function solution(x) {
  for (let i = 0; i < x.length; i++) {
    for (let j = 0; j < x.length; j++) {
      if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
        x[i][j + 1] = x[i][j] * 2;
        x[i][j] = 0;
        j += 1;
      }
    }
  }
  return JSON.stringify(x)
}

console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))

If you just want 1 change per row, you can use break

Example with break, only does 1 update per row

function solution(x) {
  for (let i = 0; i < x.length; i++) {
    for (let j = 0; j < x.length; j++) {
      if (x[i][j] == x[i][j + 1] && x[i][j] !== 0) {
        x[i][j + 1] = x[i][j] * 2;
        x[i][j] = 0;
        // If you only want one move, you can break here
        break;
      }
    }
  }
  return JSON.stringify(x)
}

console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))


问:
Ubuntu 19.04, Make custom shortcut like SUPER + NUM (favorite app create | show) shortcut in same desktop
Create show or hide any window that I want in same desktop instead of default SUPER + NUM functionality.

I want to remove the default (old) one too.

答:
Removing default shortcuts:

Via Terminal Command

gsettings set org.gnome.shell.extensions.dash-to-dock hot-keys false
gsettings set org.gnome.shell.keybindings switch-to-application-1 []
gsettings set org.gnome.shell.keybindings switch-to-application-2 []
gsettings set org.gnome.shell.keybindings switch-to-application-3 []
gsettings set org.gnome.shell.keybindings switch-to-application-4 []
gsettings set org.gnome.shell.keybindings switch-to-application-5 []
gsettings set org.gnome.shell.keybindings switch-to-application-6 []
gsettings set org.gnome.shell.keybindings switch-to-application-7 []
gsettings set org.gnome.shell.keybindings switch-to-application-8 []
gsettings set org.gnome.shell.keybindings switch-to-application-9 []
```

<h3>Via GUI of Dconf-Editor</h3>

<ul>
<li>Install dconf-editor <code>sudo apt get install dconf-editor</code></li>
<li>Start editor <code>dconf-editor</code></li>
<li>Move <code>org.gnome.shell.keybindings</code> then click and set '[]' (del maybe)</li>
</ul>

<h2>Making Custom Shortcuts</h2>

<ul>
<li>First, install dependencies <code>sudo apt install xdotool</code></li>
<li>Copy all text in <strong>my script</strong> that is in bellow</li>
<li>Open terminal and type <code>gedit ~/Tools/ywm.sh</code> and paste your clipboard content</li>
<li>Give executable permission <code>sudo chmod u+x '~/Tools/ywm.sh'</code></li>
<li>Press <kbd>SUPER</kbd> key and type <code>Shortcut</code></li>
<li>Scroll to the bottom of window click <code>+</code> button</li>
<li>Type these command (<em>just example</em>) and set your favorite shortcut

<ul>
<li>For terminal, <code>bash -c "bash ~/Tools/ywm.sh gnome-terminal"</code></li>
<li>For google chrome, <code>bash -c "bash ~/Tools/ywm.sh google-chrome"</code></li>
<li>For Vscode, <code>bash -c "bash ~/Tools/ywm.sh code"</code></li>
<li>For file explorer, <code>bash -c "bash ~/Tools/ywm.sh nautilus"</code></li>
<li>For text editör, <code>bash -c "bash ~/Tools/ywm.sh gedit"</code></li>
</ul></li>
</ul>

<h3>My Script</h3>

<pre class="lang-sh prettyprint-override"><code># !/bin/bash

# Window manager script
# Show, hide or create window in the current workspace with It's WM_CLASS
# $1, WM_CLASS
# $2, Optional command
# Copyright © ~ Yunus Emre Ak

# Suppose that these script written in '~/Tools/ywm.sh'

# # Need permission to work as shurtcut
# chmod u+x '~/Tools/ywm.sh'

# Getting windows id if exist
if [ ${#1} -gt 0 ]; then
    # Work only in the current workspace
    WID=$(xdotool search --desktop $(xdotool get_desktop) --classname $1)
    if [ ${#WID} -gt 0 ]; then
        # If opened more, find focused one and hide
        if [[ "$WID" =~ "$(xdotool getwindowfocus)" ]]; then
            xdotool windowminimize $(xdotool getwindowfocus)
        else
            # Open first windows if not, then try second
            let "WID1 = $(echo $WID | awk '{print $1}')"
            let "WID2 = $(echo $WID | awk '{print $2}')"
            xdotool windowactivate $WID1 || xdotool windowactivate $WID2
        fi
    else
        # If optional exec not exist, execute WM_CLASS
        if [ ${#2} -gt 0 ]; then
            $2
        else
            $1
        fi
    fi
else
    echo "Need to get parameter which are 'WM_CLASS' and optional Exec"
    echo "Ex: 'bash ywm.sh chrome google-chrome'"
fi

# Shortcuts for favorite app
# bash -c "bash ~/Tools/ywm.sh gnome-terminal" # SUPER + 1
# bash -c "bash ~/Tools/ywm.sh google-chrome" # SUPER + 2
# bash -c "bash ~/Tools/ywm.sh code" # SUPER + 3
# bash -c "bash ~/Tools/ywm.sh nautilus" # SUPER + 4
# bash -c "bash ~/Tools/ywm.sh gedit" # SUPER + 4
</code>```

Body:
Removing default shortcuts:

Via Terminal Command

gsettings set org.gnome.shell.extensions.dash-to-dock hot-keys false
gsettings set org.gnome.shell.keybindings switch-to-application-1 []
gsettings set org.gnome.shell.keybindings switch-to-application-2 []
gsettings set org.gnome.shell.keybindings switch-to-application-3 []
gsettings set org.gnome.shell.keybindings switch-to-application-4 []
gsettings set org.gnome.shell.keybindings switch-to-application-5 []
gsettings set org.gnome.shell.keybindings switch-to-application-6 []
gsettings set org.gnome.shell.keybindings switch-to-application-7 []
gsettings set org.gnome.shell.keybindings switch-to-application-8 []
gsettings set org.gnome.shell.keybindings switch-to-application-9 []

Via GUI of Dconf-Editor

Install dconf-editor sudo apt get install dconf-editor

Start editor dconf-editor

Move org.gnome.shell.keybindings then click and set '[]' (del maybe)

Making Custom Shortcuts

First, install dependencies sudo apt install xdotool

Copy all text in my script that is in bellow

Open terminal and type gedit ~/Tools/ywm.sh and paste your clipboard content

Give executable permission sudo chmod u+x '~/Tools/ywm.sh'

Press SUPER key and type Shortcut

Scroll to the bottom of window click + button

Type these command (just example) and set your favorite shortcut

For terminal, bash -c "bash ~/Tools/ywm.sh gnome-terminal"

For google chrome, bash -c "bash ~/Tools/ywm.sh google-chrome"

For Vscode, bash -c "bash ~/Tools/ywm.sh code"

For file explorer, bash -c "bash ~/Tools/ywm.sh nautilus"

For text editör, bash -c "bash ~/Tools/ywm.sh gedit"

My Script

# !/bin/bash

# Window manager script
# Show, hide or create window in the current workspace with It's WM_CLASS
# $1, WM_CLASS
# $2, Optional command
# Copyright © ~ Yunus Emre Ak

# Suppose that these script written in '~/Tools/ywm.sh'

# # Need permission to work as shurtcut
# chmod u+x '~/Tools/ywm.sh'

# Getting windows id if exist
if [ ${#1} -gt 0 ]; then
    # Work only in the current workspace
    WID=$(xdotool search --desktop $(xdotool get_desktop) --classname $1)
    if [ ${#WID} -gt 0 ]; then
        # If opened more, find focused one and hide
        if [[ "$WID" =~ "$(xdotool getwindowfocus)" ]]; then
            xdotool windowminimize $(xdotool getwindowfocus)
        else
            # Open first windows if not, then try second
            let "WID1 = $(echo $WID | awk '{print $1}')"
            let "WID2 = $(echo $WID | awk '{print $2}')"
            xdotool windowactivate $WID1 || xdotool windowactivate $WID2
        fi
    else
        # If optional exec not exist, execute WM_CLASS
        if [ ${#2} -gt 0 ]; then
            $2
        else
            $1
        fi
    fi
else
    echo "Need to get parameter which are 'WM_CLASS' and optional Exec"
    echo "Ex: 'bash ywm.sh chrome google-chrome'"
fi

# Shortcuts for favorite app
# bash -c "bash ~/Tools/ywm.sh gnome-terminal" # SUPER + 1
# bash -c "bash ~/Tools/ywm.sh google-chrome" # SUPER + 2
# bash -c "bash ~/Tools/ywm.sh code" # SUPER + 3
# bash -c "bash ~/Tools/ywm.sh nautilus" # SUPER + 4
# bash -c "bash ~/Tools/ywm.sh gedit" # SUPER + 4


问:
World map not dispalyed in crystal reports
I'm generating a pdf report using crystal report, I would like to use  Data Map Tool

In c# code I've a dataset containing geographicals fields and some values to display in the map.

```<code>    public class CrystalReportViewerPlugIn : ICrystalReportViewer
    {
      private ReportDocument _reportDocument;
      private CrystalReportViewer _crystalReportViewer;

      public void Init(string fileName, DataSet dataSet)
      {
        _reportDocument = new ReportDocument();
        _reportDocument.Load(fileName);
        _reportDocument.SetDataSource(dataSet);
        _crystalReportViewer = new CrystalReportViewer();
        _crystalReportViewer.DisplayToolbar = false;
        _crystalReportViewer.DisplayGroupTree = false;
        _crystalReportViewer.PageToTreeRatio = 4;
        _crystalReportViewer.RefreshReport();
        _crystalReportViewer.ReportSource = _reportDocument;
      }
    }
</code>```

Then I export the result into a strem:

```<code>public MemoryStream GetCrystalReportResults(string rptFileName, DataSet ds)
{
  var crystalReportViewer = new CrystalReportViewerPlugIn();
  crystalReportViewer.PlugIn.Init(rptFileName, ds);
  crystalReportViewer.PlugIn.Control.Visible = true;
  var oStream = crystalReportViewer.PlugIn.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
  var byteArray = new byte[oStream.Length];
  oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
  return new MemoryStream(byteArray);
}
</code>```

The stream is exported as pdf:

```<code>protected virtual IHttpActionResult FinalizeExport(MemoryStream data, string name)
{
  string contentType = "application/octet-stream";
  name = name.GetCleanFileName();

  var response = Request.CreateResponse(HttpStatusCode.OK);
  response.Content = new StreamContent(data);
  response.Content.Headers.Remove("content-type");
  response.Content.Headers.Add("content-type", contentType);
  response.Content.Headers.Remove("x-filename");
  response.Content.Headers.Add("x-filename", name);
  response.Content.Headers.Add("Content-Disposition", "inline; filename=\"" + name + "\"");
  response.Content.Headers.Add("Content-Length", data.Length.ToString());

  return ResponseMessage(response);
}
</code>```

The world map is not displayed, do you have anny idea about this issue ?

答: Crystal report's map works only in 32 bits environment.</p>

Body:
I'm generating a pdf report using crystal report, I would like to use  Data Map Tool

In c# code I've a dataset containing geographicals fields and some values to display in the map.

    public class CrystalReportViewerPlugIn : ICrystalReportViewer
    {
      private ReportDocument _reportDocument;
      private CrystalReportViewer _crystalReportViewer;

      public void Init(string fileName, DataSet dataSet)
      {
        _reportDocument = new ReportDocument();
        _reportDocument.Load(fileName);
        _reportDocument.SetDataSource(dataSet);
        _crystalReportViewer = new CrystalReportViewer();
        _crystalReportViewer.DisplayToolbar = false;
        _crystalReportViewer.DisplayGroupTree = false;
        _crystalReportViewer.PageToTreeRatio = 4;
        _crystalReportViewer.RefreshReport();
        _crystalReportViewer.ReportSource = _reportDocument;
      }
    }

Then I export the result into a strem:

public MemoryStream GetCrystalReportResults(string rptFileName, DataSet ds)
{
  var crystalReportViewer = new CrystalReportViewerPlugIn();
  crystalReportViewer.PlugIn.Init(rptFileName, ds);
  crystalReportViewer.PlugIn.Control.Visible = true;
  var oStream = crystalReportViewer.PlugIn.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
  var byteArray = new byte[oStream.Length];
  oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
  return new MemoryStream(byteArray);
}

The stream is exported as pdf:

protected virtual IHttpActionResult FinalizeExport(MemoryStream data, string name)
{
  string contentType = "application/octet-stream";
  name = name.GetCleanFileName();

  var response = Request.CreateResponse(HttpStatusCode.OK);
  response.Content = new StreamContent(data);
  response.Content.Headers.Remove("content-type");
  response.Content.Headers.Add("content-type", contentType);
  response.Content.Headers.Remove("x-filename");
  response.Content.Headers.Add("x-filename", name);
  response.Content.Headers.Add("Content-Disposition", "inline; filename=\"" + name + "\"");
  response.Content.Headers.Add("Content-Length", data.Length.ToString());

  return ResponseMessage(response);
}

The world map is not displayed, do you have anny idea about this issue ?


问:
iOS: RSA Encrypt using public key (with modulus and exponent)
I'm trying to RSA encrypt an NSData using a public key. The public key is in this format:

```<code><RSAKeyValue>
  <Modulus>yOTe0L1/NcbXdZYwliS82MiTE8VD5WD23S4RDsdbJOFzCLbsyb4d+K1M5fC+xDfCkji1zQjPiiiToZ7JSj/2ww==</Modulus>
  <Exponent>AWAB</Exponent>
</RSAKeyValue>
</code>```

After extracting the modulus and exponent from the XML string, how do I get a SecKeyRef out of those to be used as publicKey in the method below?

```<code>+ (NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = malloc(cipherBufferSize);
    uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
    SecKeyEncrypt(publicKey,
        kSecPaddingOAEP,
        nonce,
        strlen( (char*)nonce ),
        &cipherBuffer[0],
        &cipherBufferSize);
    NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
    return [encryptedData base64EncodedString];
}
</code>```

I can't seem to find a definite answer anywhere.

答:
I have used the below method for encryption using public key without using any third party libs, guess it may help who is looking for the same after they implemented it just as I did :D</p>

```<code>+(NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = malloc(cipherBufferSize);
    uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
    SecKeyEncrypt(publicKey,
                  kSecPaddingPKCS1,
                  nonce,
                  strlen( (char*)nonce ),
                  &cipherBuffer[0],
                  &cipherBufferSize);
    NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
    return [encryptedData base64EncodedStringWithOptions:0];
}
</code>```

Body:
I'm trying to RSA encrypt an NSData using a public key. The public key is in this format:

<RSAKeyValue>
  <Modulus>yOTe0L1/NcbXdZYwliS82MiTE8VD5WD23S4RDsdbJOFzCLbsyb4d+K1M5fC+xDfCkji1zQjPiiiToZ7JSj/2ww==</Modulus>
  <Exponent>AWAB</Exponent>
</RSAKeyValue>

After extracting the modulus and exponent from the XML string, how do I get a SecKeyRef out of those to be used as publicKey in the method below?

+ (NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = malloc(cipherBufferSize);
    uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
    SecKeyEncrypt(publicKey,
        kSecPaddingOAEP,
        nonce,
        strlen( (char*)nonce ),
        &cipherBuffer[0],
        &cipherBufferSize);
    NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
    return [encryptedData base64EncodedString];
}

I can't seem to find a definite answer anywhere.

Body:
I have used the below method for encryption using public key without using any third party libs, guess it may help who is looking for the same after they implemented it just as I did :D

+(NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = malloc(cipherBufferSize);
    uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
    SecKeyEncrypt(publicKey,
                  kSecPaddingPKCS1,
                  nonce,
                  strlen( (char*)nonce ),
                  &cipherBuffer[0],
                  &cipherBufferSize);
    NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
    return [encryptedData base64EncodedStringWithOptions:0];
}


问:
How to extract storage account name and blob name from storage uri
I have below  url for azure
https://restoreprojectdb.blob.core.windows.net/bacpacfiles/TestDB.bacpac

I want to extract "restoreprojectdb" and  "bacpacfiles" from the url using regex.

what is the best regex for this?

答: Not sure if it's the best regex, but if the format is always more or less the same I would just do https:\/\/(.*)?.blob.core.windows.net\/(.*)?\/


问:
Querying XML nodes in MS SQL
I have the following XML record.

```<code><row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>
</code>```

C2 are lables for C1 in two languages differentiated by the S attribute so the count of S2 is always double C1.

I would like to select a query with the following output.

```<code>NAME              LABEL
--------------------------------------
BUSINESS.HOME     Our Business
PAYMENTS.HOME     Payment Services
DEPARTMENT.PAGE   Department Operations
SECTION.HOME      Section Operations
ABOUT.HOME        ABOUT
</code>```

Every value from C1 and the corresponding first value from C2.

I tried cross apply like this:

```<code>select t.p.query('.').value('data(./c2)[1]', 'varchar(max)') c2
from table_name
cross apply XMLRECORD.nodes('(/row/c2)') t(p)
where ID  = 'HOME.PAGE'
</code>```

But do not know how to proceed further in order to exclude the foreign language and include the C1 tag.

答:
This is a bit "ugly", due to having to match NULL on NULL, however, this is how I would achieve what you're after:

```<code>DECLARE @XML xml = '
<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>';

SELECT c1.value('(./text())[1]','varchar(15)') AS [NAME],
       c2.value('(./text())[1]','varchar(15)') AS LABEL
FROM @XML.nodes('row/c1') c1(c1)
     JOIN @XML.nodes('row/c2') c2(c2) ON (c1.value('@m','int') = c2.value('@m','int') AND c2.value('@s','int') IS NULL)
                                      OR (c1.value('@m','int') IS NULL AND c2.value('@m','int') IS NULL);
</code>```

Title: Querying XML nodes in MS SQL

Body:
I have the following XML record.

<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>

C2 are lables for C1 in two languages differentiated by the S attribute so the count of S2 is always double C1.

I would like to select a query with the following output.

NAME              LABEL
--------------------------------------
BUSINESS.HOME     Our Business
PAYMENTS.HOME     Payment Services
DEPARTMENT.PAGE   Department Operations
SECTION.HOME      Section Operations
ABOUT.HOME        ABOUT

Every value from C1 and the corresponding first value from C2.

I tried cross apply like this:

select t.p.query('.').value('data(./c2)[1]', 'varchar(max)') c2
from table_name
cross apply XMLRECORD.nodes('(/row/c2)') t(p)
where ID  = 'HOME.PAGE'

But do not know how to proceed further in order to exclude the foreign language and include the C1 tag.

Body:
This is a bit "ugly", due to having to match NULL on NULL, however, this is how I would achieve what you're after:

DECLARE @XML xml = '
<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>';

SELECT c1.value('(./text())[1]','varchar(15)') AS [NAME],
       c2.value('(./text())[1]','varchar(15)') AS LABEL
FROM @XML.nodes('row/c1') c1(c1)
     JOIN @XML.nodes('row/c2') c2(c2) ON (c1.value('@m','int') = c2.value('@m','int') AND c2.value('@s','int') IS NULL)
                                      OR (c1.value('@m','int') IS NULL AND c2.value('@m','int') IS NULL);


问:
Build matrix from smaller matrices/vectors
My final matrix A should be of size m x m, where I have two vectors v, k which are of size (m-1) and should be the first column and row respectively in A, excluding the element at (0, 0) which is 1. The remaining elements of A correspond to some matrix M of size (m-1) x (m-1).

Example for 3 x 3 matrix

For the following components

```<code> v = 2 2
 k = 3 3

 M = 4 4
     4 4
</code>```

I would like to get

```<code>A = 1 2 2
    3 4 4
    3 4 4
</code>```

Note: Elements of v, k and M can be arbitrary in reality.

Code

My code looks the following for an example matrix of size 3 x 3.

```<code>#include <iostream>
#include <Eigen/Dense>

int main(){

  Eigen::MatrixXd m;
  m.resize(3,3);

  Eigen::VectorXd v;
  v.resize(3);
  v[0] = 1 ;
  v[1] = 2;
  v[2] = 2;

  Eigen::VectorXd k;
  k.resize(3);
  k[0] = 1;
  k[1] = 3;
  k[2] = 3;

  Eigen::Matrix2d a = Eigen::Matrix2d::Constant(4);

  m.col(0) = k;
  m.row(0) = v;
  m.block<2,2>(1,1) = a;

  std::cout << m << std::endl;
  return 0;
}
</code>```

Output looks like the following:

```<code>1 2 2
3 4 4
3 4 4
</code>```

In the actual program the final matrix will be up to order 10^4 - 10^6. As I am fairly new to C++ I was wondering if this is the most efficient and elegant to do this and if I might run into trouble when it comes to larger matrices?

答:
Assuming v and k are n x 1 vectors and M is a n x n matrix, you can write:

```<code>Eigen::MatrixXd A(M.rows()+1, M.cols()+1);
A << 1, v.transpose(),
     k, M;
</code>```

This does almost the same as your code using row, col and block, but is probably more readable. And unless this happens inside a critical loop, I would not worry too much about performance here.

If this happens inside a critical loop, consider storing only A and access M, v and k by some block-expression.

Body:
My final matrix A should be of size m x m, where I have two vectors v, k which are of size (m-1) and should be the first column and row respectively in A, excluding the element at (0, 0) which is 1. The remaining elements of A correspond to some matrix M of size (m-1) x (m-1).

Example for 3 x 3 matrix

For the following components

 v = 2 2
 k = 3 3

 M = 4 4
     4 4

I would like to get

A = 1 2 2
    3 4 4
    3 4 4

Note: Elements of v, k and M can be arbitrary in reality.

Code

My code looks the following for an example matrix of size 3 x 3.

#include <iostream>
#include <Eigen/Dense>

int main(){

  Eigen::MatrixXd m;
  m.resize(3,3);

  Eigen::VectorXd v;
  v.resize(3);
  v[0] = 1 ;
  v[1] = 2;
  v[2] = 2;

  Eigen::VectorXd k;
  k.resize(3);
  k[0] = 1;
  k[1] = 3;
  k[2] = 3;

  Eigen::Matrix2d a = Eigen::Matrix2d::Constant(4);

  m.col(0) = k;
  m.row(0) = v;
  m.block<2,2>(1,1) = a;

  std::cout << m << std::endl;
  return 0;
}

Output looks like the following:

1 2 2
3 4 4
3 4 4

In the actual program the final matrix will be up to order 10^4 - 10^6. As I am fairly new to C++ I was wondering if this is the most efficient and elegant to do this and if I might run into trouble when it comes to larger matrices?

Body:
Assuming v and k are n x 1 vectors and M is a n x n matrix, you can write:

Eigen::MatrixXd A(M.rows()+1, M.cols()+1);
A << 1, v.transpose(),
     k, M;

This does almost the same as your code using row, col and block, but is probably more readable. And unless this happens inside a critical loop, I would not worry too much about performance here.

If this happens inside a critical loop, consider storing only A and access M, v and k by some block-expression.


问:
How do I convert web application into desktop executable?
I've HTML application build with AngularJS/jQuery/Bootstrap with AJAX REST API.

Is it possible to create executable/installer for Windows operating system?

Without any 3rd-party software, it should look like native application, but HTML.

For example, Slack messenger has web/mac/windows versions and they look same.

Any ideas?

// UPD

I probably need a wrapper (webview), but I need all features for EcmaScript5/CSS3.

答:
(Full disclosure, I'm the founder of ToDesktop, I'll try to be objective and unbiased here.)

As usual in Computer Science, the answer is "it depends"!

The first question that you should ask yourself is: Who is the desktop app being used by? Just you? Or, are you distributing the app to customers? Because these two segments have very different needs.

Just you

There are a lot of options here (in no particular order):

Nativefier — The obvious option. Lots of configuration options, lots of contributors, open source and regularly updated. This should probably be the default option if you want to whip up an app just for yourself.

WebDGap — This is a lovely project but it is a little old and "as of April 13th, 2018 WebDGap is no longer an active project.". It should also be noted that this is built on an old version of node-webkit and not Electron.

Web2Desk — Great option if you don't want to mess around with the command-line. It uses Nativefier under-the-hood. It is free with a splash screen or $19 with the splash screen removed.

Do-it-yourself with Electron — The basics were covered quite well in this earlier answer. I like this option because it gives you complete flexibility to take the project wherever you like and you'll learn a bit of Electron too.

Fluid App — This is Mac only but otherwise it's a lovely solution and super easy. It's free for the standard version, there is also a $5 version which includes features like fullscreen.

Flotato — Mac only again but this is a really interesting approach. Simply clone the app and give it a name like docs.google.com, it will then turn into Google Docs. At the time of writing this, it's in pre-release (not released yet) but I'll be watching this closely, it's very cool.

ToDesktop — ToDesktop will work but it's probably a bit overkill if you're creating a personal app. Also, it's probably a bit too expensive for this use-case. ToDesktop is targeted at creating a desktop app for distribution to customers (more about that below).

Distributing to customers

There are a few extra considerations which become more important when creating a desktop app for distribution to your customers:

Installer — Mac users expect a "drag to applications" DMG file. Windows users expect an installer and they also expect to be able to uninstall it from the control panel.

Code Signing — If your app isn't code signed then by default Windows Authenticode and Apple Gatekeeper will prevent your desktop app from being opened.

Auto-update — There is still a web browser running "underneath" your desktop app, it's important to keep this updated for two reasons. 1. Security issues + vulnerabilities should be patched over time. 2. You don't want to be stuck supporting an old web browser in 5 years time because your desktop app's browser hasn't been updated

The tools mentioned above don't offer these features, so they're not really suitable for the use-case of distributing your app to customers. These are the features that we wanted to add when building ToDesktop, so I think it fits this use-case quite nicely. We're adding features all the time, last week we added support for App Protocols and Deeplinks.


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答:
Hey there, use the FROM_UNIXTIME() function for this.

Like this:

```<code>INSERT INTO table_name
(id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES
(1,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1'),
(2,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1')
</code>```

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')

Body:
Hey there, use the FROM_UNIXTIME() function for this.

Like this:

INSERT INTO table_name
(id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES
(1,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1'),
(2,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1')


问:
How can I force a child to have square dimensions in Xamarin?
Let's say I have a button in a stack layout that fills the parent horizontally. How do I make it so that it's vertical height is the same as the horizontal length? Preferably entirely in xaml, but in c# if it must.</p>

答:
I think the easiest way to do this is by binding the height of the object to it's width</p>

```<code>  Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}">
</code>```

Body:
I think the easiest way to do this is by binding the height of the object to it's width

  Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}">


问:
Add 2 parameters to Email Template Body
I have a email template and i have bind 1 parameter to it(this.OrderCode) and it's working .So now i need to bind another one.

Email Template Like Below,

```<code>string OrderTemplate="<p><%=this.OrderCode%></p><p><%=this.ReferredTo%></p>";

tempValues comes like below,
[0]this.OrderCode
[1]ODR5000
[2]this.ReferredTo
[3]Janez Smithson
</code>```

Using below code i need to show both of above values.In here only shows 1st value only(ODR5000)

```<code>public string EmailTemplate(string OrderTemplate, params string[] tempValues)
        {
            string templatebody = string.Empty;
            try
            {
                templatebody = OrderTemplate;
                for (var i = 0; i < tempValues.Length; i++)
                {
                    templatebody= templatebody.Replace("<%={0}%>".FormatWith(tempValues[i]), tempValues++);
                }
            }
            catch (Exception ex)
            {
                throw ex;
                Log4NetLogger.Log(ex);
            }
            return templatebody;
        }
</code>```

答:
I have pretty similar function for that. </p>

```<code>for (int i = 0; i < tempValues.Length; i++)
{
    var pattern = string.Format(@"(\[{0}\])", i);
    templatebody = Regex.Replace(templatebody, pattern, tempValues[i].ToString());
}
</code>```

Title: Add 2 parameters to Email Template Body

Body:
I have a email template and i have bind 1 parameter to it(this.OrderCode) and it's working .So now i need to bind another one.

Email Template Like Below,

string OrderTemplate="
<%=this.OrderCode%>

<%=this.ReferredTo%>
";

tempValues comes like below,
[0]this.OrderCode
[1]ODR5000
[2]this.ReferredTo
[3]Janez Smithson

Using below code i need to show both of above values.In here only shows 1st value only(ODR5000)

public string EmailTemplate(string OrderTemplate, params string[] tempValues)
        {
            string templatebody = string.Empty;
            try
            {
                templatebody = OrderTemplate;
                for (var i = 0; i < tempValues.Length; i++)
                {
                    templatebody= templatebody.Replace("<%={0}%>".FormatWith(tempValues[i]), tempValues++);
                }
            }
            catch (Exception ex)
            {
                throw ex;
                Log4NetLogger.Log(ex);
            }
            return templatebody;
        }

Body:
I have pretty similar function for that.

for (int i = 0; i < tempValues.Length; i++)
{
    var pattern = string.Format(@"(\[{0}\])", i);
    templatebody = Regex.Replace(templatebody, pattern, tempValues[i].ToString());
}


问:
What means this Exception?
I try to test a code and got the Exception below:

The component(s) below failed to render. Possible reasons could be that: 1) you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered), 2) if your components were added in a parent container then make sure the markup for the child container includes them in .

I don't know what to do now.

答:
This error means that you have added a component in your Java code, e.g.:

```<code>add(new Label("someId", "Some text"));
</code>```

but you forgot to add wicket:id="someId" to the corresponding HTML template.

So, Wicket says: I have a component in the Java component tree that I have no idea where and how to render.

Title: What means this Exception?

Body:
This error means that you have added a component in your Java code, e.g.:

add(new Label("someId", "Some text"));

but you forgot to add wicket:id="someId" to the corresponding HTML template.

So, Wicket says: I have a component in the Java component tree that I have no idea where and how to render.


问:
Why is the openquery returning 0 rows on SQL server but has 900k rows in the target Server?
Need help to figure ut why the remote query I execute on the server return 0 rows , but the same query returns over 900k rows in the target DB.

the string is less 8000 characters long so I won't post it here.  but this is the sctructure basically:

```<code>declare @SQL varchar(MAX);
declare @D varchar(15);
declare @Per varchar(15);
declare @NextPer varchar(15);
declare @NextYPer varchar(15);
set @D = N'01-JUN-2019'
set @Per = N'2020004';
set @NextYPer = N'2021004'
set @NextPer = N'2020005'
set @SQL = N' SELECT  ...... '
set @SQL = N'select * from openquery ([LK1], "'+@SQL+'")';
execute( @SQL);
print @SQL;
</code>```

Note: the linked server works and is used on other openqueries with shorter strings successfully. I tried using EXECUTE (@SQL) AT  and I still get 0 rows.  When i exexute the print output directly on the Oracle DB , the query runs for about 15 min and gives results.

答:
Thanks all for the input.

The root cause is simply the format of the Date parameter, which didn't run correctly on the linked server.
All I had to do is change my query to use this:

SO_BOOK_DATE <  to_date(''@D''  , ''DD-MON-YYYY'')

instead of

SO_BOOK_DATE < ''@D''  .

Body:
Need help to figure ut why the remote query I execute on the server return 0 rows , but the same query returns over 900k rows in the target DB.

the string is less 8000 characters long so I won't post it here.  but this is the sctructure basically:

declare @SQL varchar(MAX);
declare @D varchar(15);
declare @Per varchar(15);
declare @NextPer varchar(15);
declare @NextYPer varchar(15);
set @D = N'01-JUN-2019'
set @Per = N'2020004';
set @NextYPer = N'2021004'
set @NextPer = N'2020005'
set @SQL = N' SELECT  ...... '
set @SQL = N'select * from openquery ([LK1], "'+@SQL+'")';
execute( @SQL);
print @SQL;

Note: the linked server works and is used on other openqueries with shorter strings successfully. I tried using EXECUTE (@SQL) AT  and I still get 0 rows.  When i exexute the print output directly on the Oracle DB , the query runs for about 15 min and gives results.


问:
Count columns and sum
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

```<code>+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+
</code>```

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

答:
MySQL treats boolean expressions as numbers, so this is easy to express:

```<code>select id,
       ( (risk1 = 'h') + (risk2 = 'h') + (risk3 = 'h') ) as num_hs
from t;
</code>```

Note:  This assumes that none of the values are NULL which appears to be the case with your data.

Title: Count columns and sum

Body:
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

Body:
MySQL treats boolean expressions as numbers, so this is easy to express:

select id,
       ( (risk1 = 'h') + (risk2 = 'h') + (risk3 = 'h') ) as num_hs
from t;

Note:  This assumes that none of the values are NULL which appears to be the case with your data.


答:
One way:

```<code>SELECT
    id,
    IF(COALESCE(risk1, '') = 'h', 1, 0) +
    IF(COALESCE(risk2, '') = 'h', 1, 0) +
    IF(COALESCE(risk3, '') = 'h', 1, 0) AS h_sum
FROM yourTable
ORDER BY id;
</code>```

Just for fun, here is more exotic way of doing this, using string manipulation:

```<code>SELECT
    id,
    3 - LENGTH(REPLACE(CONCAT(risk1, risk2, risk3), 'h', '')) AS h_sum
FROM yourTable
ORDER BY id;
</code>```

Demo

To make the second approach also be NULL safe, just use COALESCE(risk1, '') in place of risk1 (and the same for the other columns).

Title: Count columns and sum

Body:
One way:

SELECT
    id,
    IF(COALESCE(risk1, '') = 'h', 1, 0) +
    IF(COALESCE(risk2, '') = 'h', 1, 0) +
    IF(COALESCE(risk3, '') = 'h', 1, 0) AS h_sum
FROM yourTable
ORDER BY id;

Just for fun, here is more exotic way of doing this, using string manipulation:

SELECT
    id,
    3 - LENGTH(REPLACE(CONCAT(risk1, risk2, risk3), 'h', '')) AS h_sum
FROM yourTable
ORDER BY id;

Demo

To make the second approach also be NULL safe, just use COALESCE(risk1, '') in place of risk1 (and the same for the other columns).


问:
Nested Grid IN EXTJS
HI

How to design Nested grids in ExtJS
Please provide some samples(How to use RowExpander in ExtJS GridPanel)

答:
How to use RowExpander in grid? Here's an example: http://dev.sencha.com/deploy/dev/examples/grid/grid-plugins.html

More examples can be found from http://dev.sencha.com/deploy/dev/examples/

Title: Nested Grid IN EXTJS


问:
Convert list of tuple-1 of float to set of int
After querying a database, I get a result r of the following format:

```<code>r = [(123.0,), (456.0,), (789.0,)]
</code>```

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

```<code>s = {123, 456, 789}
</code>```

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?

答:
You can do:

```<code>result = {int(x[0]) for x in r}
</code>```

If you want to go full map ninja:

```<code>In [1]: import operator
In [2]: set(map(int, map(operator.itemgetter(0), r)))
Out[2]: {123, 456, 789}
</code>```

Body:
After querying a database, I get a result r of the following format:

r = [(123.0,), (456.0,), (789.0,)]

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

s = {123, 456, 789}

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?

Body:
You can do:

result = {int(x[0]) for x in r}

If you want to go full map ninja:

In [1]: import operator
In [2]: set(map(int, map(operator.itemgetter(0), r)))
Out[2]: {123, 456, 789}


问:
Unreadable content in Excel file generated with EPPlus
I'm having a little problem when I generate an Excel file from a template, using the EPPlus library. The file has a first spreadsheet that contains data that is used for populating pivot tables in the following sheets.

When I open the generated file, I get the following error message :
"Excel found unreadable content in 'sampleFromTemplate.xlsx'. Do you want to recover the contents of this workbook ? I you trust the source of this workbook, click Yes."

I obviously click yes, then get a summary of repairs done to the file, and a link to an xml formatted log file containing this :

```<code><?xml version="1.0" encoding="UTF-8" standalone="true"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <logFileName>error095080_01.xml</logFileName>
    <summary>Errors were detected in file  'C:\TEMP\sampleFromTemplate.xlsx'</summary>
    <repairedRecords summary="Following is a list of repairs:">
        <repairedRecord>Repaired Records: Table from /xl/tables/table1.xml part (Table)</repairedRecord>
    </repairedRecords>
</recoveryLog>
</code>```

This is apparently caused by a named range ("Table1") that I define in my code to indicate the data to be used for the pivot tables. There already is a "Table Name" in the template called "Table1", but I can't seem to access it through the ExcelPackage.Worksheet.Names collection. Being new to EPPlus and not very experimented with Excel, I don't understand where I'm doing wrong. Here's the bit of code where I generate the file :

```<code>private string GenerateFromTemplate(string fileName, string templateName, DataTable tab)
{
    FileInfo newFile = new FileInfo(string.Format("C:\\MyPath\\{0}.xlsx", fileName));
    FileInfo templateFile = new FileInfo(string.Format("C:\\MyPath\\{0}.xlsx", templateName));

    try
    {
        using (ExcelPackage pkg = new ExcelPackage(newFile, templateFile))
        {
            ExcelWorksheet sheet = pkg.Workbook.Worksheets["MyDataSheet"];
            ExcelRange range = sheet.Cells[string.Format("A1:U{0}", dt.Rows.Count)];
            pkg.Workbook.Names.Add("Table1", range as ExcelRangeBase);

            int sheetRowIndex = 2;

            foreach (DataRow row in this.dt.Rows)
            {
                sheet.Cells[sheetRowIndex, 1].Value = row["Row1"];
                sheet.Cells[sheetRowIndex, 2].Value = row["Row2"];
                [...]
                sheet.Cells[sheetRowIndex, 21].Value = row["Row21"];

                sheetRowIndex++;
            }

            pkg.Save();
            return newFile.FullName;
        }
    }
    catch (IOException ex) { return ex.Message; }
}
</code>```

Note that the pivot tables are populated correctly anyway, so why is this happening ?

Thanks :-)

答:
Different setup (returning a stream), but same problem (corrupted table record). In my case the problem was the explicit call to ExcelPackage.Save():</p>

```<code>using (var excelPackage = new ExcelPackage())
{
    /* ... removed code for clarity */

    // caused the stream to contain the file 2 times,
    // save is already called by GetAsByteArray()
    //excelPackage.Save();

    return new MemoryStream(excelPackage.GetAsByteArray());
}
</code>```

Body:
I'm having a little problem when I generate an Excel file from a template, using the EPPlus library. The file has a first spreadsheet that contains data that is used for populating pivot tables in the following sheets.

When I open the generated file, I get the following error message :
"Excel found unreadable content in 'sampleFromTemplate.xlsx'. Do you want to recover the contents of this workbook ? I you trust the source of this workbook, click Yes."

I obviously click yes, then get a summary of repairs done to the file, and a link to an xml formatted log file containing this :

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <logFileName>error095080_01.xml</logFileName>
    Errors were detected in file  'C:\TEMP\sampleFromTemplate.xlsx'
    <repairedRecords summary="Following is a list of repairs:">
        <repairedRecord>Repaired Records: Table from /xl/tables/table1.xml part (Table)</repairedRecord>
    </repairedRecords>
</recoveryLog>

This is apparently caused by a named range ("Table1") that I define in my code to indicate the data to be used for the pivot tables. There already is a "Table Name" in the template called "Table1", but I can't seem to access it through the ExcelPackage.Worksheet.Names collection. Being new to EPPlus and not very experimented with Excel, I don't understand where I'm doing wrong. Here's the bit of code where I generate the file :

private string GenerateFromTemplate(string fileName, string templateName, DataTable tab)
{
    FileInfo newFile = new FileInfo(string.Format("C:\\MyPath\\{0}.xlsx", fileName));
    FileInfo templateFile = new FileInfo(string.Format("C:\\MyPath\\{0}.xlsx", templateName));

    try
    {
        using (ExcelPackage pkg = new ExcelPackage(newFile, templateFile))
        {
            ExcelWorksheet sheet = pkg.Workbook.Worksheets["MyDataSheet"];
            ExcelRange range = sheet.Cells[string.Format("A1:U{0}", dt.Rows.Count)];
            pkg.Workbook.Names.Add("Table1", range as ExcelRangeBase);

            int sheetRowIndex = 2;

            foreach (DataRow row in this.dt.Rows)
            {
                sheet.Cells[sheetRowIndex, 1].Value = row["Row1"];
                sheet.Cells[sheetRowIndex, 2].Value = row["Row2"];
                [...]
                sheet.Cells[sheetRowIndex, 21].Value = row["Row21"];

                sheetRowIndex++;
            }

            pkg.Save();
            return newFile.FullName;
        }
    }
    catch (IOException ex) { return ex.Message; }
}

Note that the pivot tables are populated correctly anyway, so why is this happening ?

Thanks :-)

Body:
Different setup (returning a stream), but same problem (corrupted table record). In my case the problem was the explicit call to ExcelPackage.Save():

using (var excelPackage = new ExcelPackage())
{
    /* ... removed code for clarity */

    // caused the stream to contain the file 2 times,
    // save is already called by GetAsByteArray()
    //excelPackage.Save();

    return new MemoryStream(excelPackage.GetAsByteArray());
}


问:
How to extract lower and upper bound in numeric format from a confidence interval string?
Suppose a vector including some confidence intervals as below

```<code>confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")
</code>```

I want to have two new vectors one including the lower Limits in numeric format as

```<code>lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)
</code>```

and othe including the upper Limits in numeric format like

```<code>upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)
</code>```

答:
A tidyverse solution:

```<code>library(dplyr)
library(tidyr)

df = data.frame(confint)
df = df %>%
  mutate(confint = gsub("(\\[|\\])","",confint)) %>%
    separate(confint,c("lower","upper"),";",convert=T)
</code>```

Body:
Suppose a vector including some confidence intervals as below

confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")

I want to have two new vectors one including the lower Limits in numeric format as

lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)

and othe including the upper Limits in numeric format like

upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)

Body:
A tidyverse solution:

library(dplyr)
library(tidyr)

df = data.frame(confint)
df = df %>%
  mutate(confint = gsub("(\\[|\\])","",confint)) %>%
    separate(confint,c("lower","upper"),";",convert=T)