问:
template with specified mode does not match problem
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

```<code><xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>
</code>```

But the template for this mode does not match:

```<code><xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...
</code>```

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

```<code><xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>
</code>```

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

```<code><?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">
            <body>
                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">
                        <section label="menuetto_A" xml:id="section_A_m1-5">
                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>
                        </section>
                    </score>
                </mdiv>
            </body>
        </music>
    </mei>
</code>```

I am expecting a sequence of @xml:id-values which I derive from my calculations.

答:
When explicitly passing the attributes to the @select they are matched. So,:

```<code><xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion//@accid"/>
</code>```

matches here:

```<code><xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility">
</code>```

@Martin Honnen: $extractMainversion contains a document-node with the value <#documentfragment> which is almost the same as the XML snippet above.
The $checkAccidentalsVisibility was previously containing a string derived from //title/text() Probably I didn't describe it well.

Although I solved the problem, I'd be interested, why you cannot match the @attributes in the way as you would normally do it without modes?

Body:
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

<xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>

But the template for this mode does not match:

<xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

<xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

<?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">

                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">

                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>

                    </score>
                </mdiv>

        </music>
    </mei>

I am expecting a sequence of @xml:id-values which I derive from my calculations.

Body:
When explicitly passing the attributes to the @select they are matched. So,:

<xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion//@accid"/>

matches here:

<xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility">

@Martin Honnen: $extractMainversion contains a document-node with the value <#documentfragment> which is almost the same as the XML snippet above.
The $checkAccidentalsVisibility was previously containing a string derived from //title/text() Probably I didn't describe it well.

Although I solved the problem, I'd be interested, why you cannot match the @attributes in the way as you would normally do it without modes?


来源: stackexchange

问:
How to install Python using Windows Command Prompt
Is it possible to install Python from cmd on Windows? If so, how to do it?</p>

答:
Assuming that you have python-installer.exe file you can run in in /passive mode in administrator window. Without administrator privileges you will be prompted

Do you want to allow this app to make changes to your device?

Powershell example could be:

```<code>$installer = "C:/tmp/python-3.7.6-amd64.exe"
& $installer /passive InstallAllUsers=1 PrependPath=1 Include_test=0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Assuming that you have python-installer.exe file you can run in in /passive mode in administrator window. Without administrator privileges you will be prompted

Do you want to allow this app to make changes to your device?

Powershell example could be:

$installer = "C:/tmp/python-3.7.6-amd64.exe"
& $installer /passive InstallAllUsers=1 PrependPath=1 Include_test=0


问:
Make elements of container fill height of container by wrapping
I have an issue with trying to make the items within a container take up the space the way i want. The main issue seems to be that flex box and css grid are made adjust to changes in width and not height, where as i need the opposite behaviour.This is basically what I want my elements to do

Check the desired effect here.

I have tried using both flex box and css grid.
This is my current code, also containing some residue of my previous attempt. It just makes the images display in their actual size.
The media-container's height is changed via javascript.

.display-img {
  padding:0px;
  margin-top:-4px;
  margin-bottom:-4px;
  flex:0 1 auto;
  height:auto;
}

.media-container{
  width: auto;
  height:800px;
  display:flex;
  //grid-template-rows: repeat(auto-fit,auto);
  //grid-template-columns: repeat(auto-fit,minmax(200px,0.5fr));
  flex-direction: row;
  align-items: flex-start;
  flex-wrap: wrap;
  visibility: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="media-container">
  <img class="display-img" src="assets/projects/feierlichkeiten/23.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/22.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/21.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/20.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/19.png"></img>
</div></code>```

Thanks to everyone who has some idea.

答:
Your question doesn't seem very clear to me.

If you want to have a row of images, all of them with their original size, all you need to do it's apply flex alignment (row & wrap) to the parent and add flex: auto with margin: auto; to the children:

```<code><div class="media-container">
  <img class="display-img" src="https://picsum.photos/160">
  <img class="display-img" src="https://picsum.photos/160/90">
  <img class="display-img" src="https://picsum.photos/150/40">
  <img class="display-img" src="https://picsum.photos/160/100">
  <img class="display-img" src="https://picsum.photos/100/290">
</div>
</code>```

[Added random aspect ratio images to prove they are all aligned regardless of the size of all your images have the same aspect ratio, the result would be the same as in your example image]

```<code>.media-container {
  display: flex;
  flex-flow: row wrap;
}

.display-img {
  margin: auto;
  flex: auto;
}
</code>```

This does the following:

media-container: set flex flow to row and wrap, so when more images are added, they are put into a new line if there is no more free space.

on the images, margin auto will take care of aligning the image inside each cell (both in horizontal and vertical) and flex: auto, which is the equivalent for flex: 1 1 auto (meaning flex grow and flex shrink would be set to one, no grow, no shrink and flex-basis to auto [initial main size of a flex item]).

Check the this codepen.

Body:
I have an issue with trying to make the items within a container take up the space the way i want. The main issue seems to be that flex box and css grid are made adjust to changes in width and not height, where as i need the opposite behaviour.This is basically what I want my elements to do

Check the desired effect here.

I have tried using both flex box and css grid.
This is my current code, also containing some residue of my previous attempt. It just makes the images display in their actual size.
The media-container's height is changed via javascript.

.display-img {
  padding:0px;
  margin-top:-4px;
  margin-bottom:-4px;
  flex:0 1 auto;
  height:auto;
}

.media-container{
  width: auto;
  height:800px;
  display:flex;
  //grid-template-rows: repeat(auto-fit,auto);
  //grid-template-columns: repeat(auto-fit,minmax(200px,0.5fr));
  flex-direction: row;
  align-items: flex-start;
  flex-wrap: wrap;
  visibility: hidden;
}

Thanks to everyone who has some idea.

Body:
Your question doesn't seem very clear to me.

If you want to have a row of images, all of them with their original size, all you need to do it's apply flex alignment (row & wrap) to the parent and add flex: auto with margin: auto; to the children:

<div class="media-container">
  <img class="display-img" src="https://picsum.photos/160">
  <img class="display-img" src="https://picsum.photos/160/90">
  <img class="display-img" src="https://picsum.photos/150/40">
  <img class="display-img" src="https://picsum.photos/160/100">
  <img class="display-img" src="https://picsum.photos/100/290">
</div>

[Added random aspect ratio images to prove they are all aligned regardless of the size of all your images have the same aspect ratio, the result would be the same as in your example image]

.media-container {
  display: flex;
  flex-flow: row wrap;
}

.display-img {
  margin: auto;
  flex: auto;
}

This does the following:

media-container: set flex flow to row and wrap, so when more images are added, they are put into a new line if there is no more free space.

on the images, margin auto will take care of aligning the image inside each cell (both in horizontal and vertical) and flex: auto, which is the equivalent for flex: 1 1 auto (meaning flex grow and flex shrink would be set to one, no grow, no shrink and flex-basis to auto [initial main size of a flex item]).

Check the this codepen.


问:
how to use pg_connect to connect to 2 different postgresql databases on the same computer
I am trying to use 2 instances of postgresql database on the same computer. any idea how should i use pg_connect

I was able to connect to one instance of postgresql  using pg_connect successfully. However I have created a second instance for a new web application. How to specify parameter to connect to both databases on the same php code using pg_connect.

答:
It is literally the first example given on php.net reference page for  pg_connect

```<code>$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password
</code>```

Just change the connection string and declare multiple connection objects and you should be fine

Body:
It is literally the first example given on php.net reference page for  pg_connect

$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

Just change the connection string and declare multiple connection objects and you should be fine


问:
A call to SSPI failed, see inner exception - The Local Security Authority cannot be contacted
I have an WPF app, which uses SSLStream to connect to server and send/receive some messages. My code is largerly based on this example (SslTcpClient): https://msdn.microsoft.com/en-us/library/system.net.security.sslstream(v=vs.110).aspx.

This worked fine for months. However, after getting this windows update (Cumulative Update for Windows 10 version 1511 and Windows Server 2016 Technical Preview 4: June 14, 2016 - https://support.microsoft.com/en-us/kb/3163018). My app started to report this exception:

```<code>System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The Local Security Authority cannot be contacted
   --- End of inner exception stack trace ---
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at MyAPP.Core.Services.Network.Impl.SslTcpClient.ClientSideHandshake()
at MyAPP.Core.Services.Network.Impl.SslTcpClient.Connect()
at MyAPP.Core.Services.Impl.MessageService.SendMessage(String message)
</code>```

What can I do ?

答:
I got this exception when using C# connect to Oracle database using Oracle.ManagedDataAccess.dll,

"Oracle.ManagedDataAccess.Client.OracleException (0x80004005): Oracle Cannot connect to Server or cannot parse connection string ---> OracleInternal.Network.NetworkException (0x80004005): Oracle : Oracle Cannot connect to Server or cannot parse connection string  ---> System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: No credentials are available in the security package\r\n   --- End of inner exception stack trace ---\r\n   at System.Net.Security.NegoState.StartSendAuthResetSignal(LazyAsyncResult lazyResult, Byte[] message, Exception exception)\r\n   at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)\r\n   at  ............

and after a long time finding and try,  finally I find This Answer works, add settings section and set name="SQLNET.AUTHENTICATION_SERVICES" value="" in the app.config:

```<code><oracle.manageddataaccess.client>
  <version number="*">
    <dataSources>
      <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/>
    </dataSources>
    <settings>
      <setting name="SQLNET.AUTHENTICATION_SERVICES" value=""/>
    </settings>
  </version>
</oracle.manageddataaccess.client>
</code>```

In the reference link in answer above, you can try one step further, set:

SQLNET.AUTHENTICATION_SERVICES= ()

in your sqlnet.ora in Oracle Client folder also works.

ContentLicense: CC BY-SA 3.0

Body:
I have an WPF app, which uses SSLStream to connect to server and send/receive some messages. My code is largerly based on this example (SslTcpClient): https://msdn.microsoft.com/en-us/library/system.net.security.sslstream(v=vs.110).aspx.

This worked fine for months. However, after getting this windows update (Cumulative Update for Windows 10 version 1511 and Windows Server 2016 Technical Preview 4: June 14, 2016 - https://support.microsoft.com/en-us/kb/3163018). My app started to report this exception:

System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The Local Security Authority cannot be contacted
   --- End of inner exception stack trace ---
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at MyAPP.Core.Services.Network.Impl.SslTcpClient.ClientSideHandshake()
at MyAPP.Core.Services.Network.Impl.SslTcpClient.Connect()
at MyAPP.Core.Services.Impl.MessageService.SendMessage(String message)

What can I do ?

Body:
I got this exception when using C# connect to Oracle database using Oracle.ManagedDataAccess.dll,

"Oracle.ManagedDataAccess.Client.OracleException (0x80004005): Oracle Cannot connect to Server or cannot parse connection string ---> OracleInternal.Network.NetworkException (0x80004005): Oracle : Oracle Cannot connect to Server or cannot parse connection string  ---> System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: No credentials are available in the security package\r\n   --- End of inner exception stack trace ---\r\n   at System.Net.Security.NegoState.StartSendAuthResetSignal(LazyAsyncResult lazyResult, Byte[] message, Exception exception)\r\n   at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)\r\n   at  ............

and after a long time finding and try,  finally I find This Answer works, add settings section and set name="SQLNET.AUTHENTICATION_SERVICES" value="" in the app.config:

<oracle.manageddataaccess.client>
  <version number="*">
    <dataSources>
      <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/>
    </dataSources>
    <settings>
      <setting name="SQLNET.AUTHENTICATION_SERVICES" value=""/>
    </settings>
  </version>
</oracle.manageddataaccess.client>

In the reference link in answer above, you can try one step further, set:

SQLNET.AUTHENTICATION_SERVICES= ()

in your sqlnet.ora in Oracle Client folder also works.


问:
Error using for loop with Ejs data in Javascript
iI have checked other questions but none have the same issues I am having and so the solutions do not apply.

Here is a sample of the code I am using :

```<code>            <script>
              var dataLength = JSON.parse('<%- JSON.stringify(userData.length) %>');

           for (var i = 0; i < dataLength; i++){
            console.log(i);  //output = 0
         console.log(JSON.stringify('<%- userData[i].latitude %>'));
          var latitude = JSON.parse('<%- userData[i].latitude %>');
          var longitude = JSON.parse('<%- userData[i].longitude %>');

          var co = new google.maps.LatLng(latitude, longitude);
         var marker = new google.maps.Marker({position: co, map: map});
         var image = 'assets/images/location.png';
         marker.setIcon (image);

           }

        }
      </script>
</code>```

This throws an error : "i is not defined".  Can someone please explain what I'm doing wrong

答:
Your for loop with i will execute on client-side, but not on server-side. Hence i is not available while the ejs is executing.

I see you are trying to iterate through userData to get lat, lng. Why don't you try the following?

```<code><script>
  var userData = JSON.parse('<%- JSON.stringify(userData) %>');

  for(var user of userData){
    var latitude = JSON.parse('<%- user.latitude %>');
    var longitude = JSON.parse('<%- user.longitude %>');
    // handle latitude, longitude
  }

</script>
</code>```

Body:
iI have checked other questions but none have the same issues I am having and so the solutions do not apply.

Here is a sample of the code I am using :

This throws an error : "i is not defined".  Can someone please explain what I'm doing wrong

Body:
Your for loop with i will execute on client-side, but not on server-side. Hence i is not available while the ejs is executing.

I see you are trying to iterate through userData to get lat, lng. Why don't you try the following?

<script>
  var userData = JSON.parse('<%- JSON.stringify(userData) %>');

  for(var user of userData){
    var latitude = JSON.parse('<%- user.latitude %>');
    var longitude = JSON.parse('<%- user.longitude %>');
    // handle latitude, longitude
  }

</script>


问:
Pycharm doesnt reslove package dependencies
I installed a pycharm application and did configure interpreter. After i installed spark-nlp package via pip inside pycharm, and tried to run programm, it showed that it missing dependecy in form of pyspark package. When I installed pyspark it complained about bunch of packages that are being missing. Shouldn't venv resolve all requirements automatically?</p>

答:
For this to work "pip" should be associated with the Python interpreter you have specified in Pycharm.

Can you check if the interpreter specified in Pycharm and "pip" on the terminal are pointing to same virtualenv which was created?

I believe "pip" on pycharm-terminal is different and not pointing to virtualenv used by Pyharm.


问:
I'm unable to understand below c# code fragment
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts. </p>

```<code>Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

</code>```

答:
You code reversing a single linked list

It's just another example of reversing a single linked list:
(see this for more details)

```<code>// C# program for reversing the linked list
using System;

class GFG {
    static void Main(string[] args)
    {
        LinkedList list = new LinkedList();
        list.AddNode(new LinkedList.Node(85));
        list.AddNode(new LinkedList.Node(15));
        list.AddNode(new LinkedList.Node(4));
        list.AddNode(new LinkedList.Node(20));

        // List before reversal
        Console.WriteLine("Given linked list:");
        list.PrintList();

        // Reverse the list
        list.ReverseList();

        // List after reversal
        Console.WriteLine("Reversed linked list:");
        list.PrintList();
    }
}

class LinkedList {
    Node head;

    public class Node {
        public int data;
        public Node next;

        public Node(int d)
        {
            data = d;
            next = null;
        }
    }

    // function to add a new node at
    // the end of the list
    public void AddNode(Node node)
    {
        if (head == null)
            head = node;
        else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    // function to reverse the list
    public void ReverseList()
    {
        Node prev = null, current = head, next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
    }

    // function to print the list data
    public void PrintList()
    {
        Node current = head;
        while (current != null) {
            Console.Write(current.data + " ");
            current = current.next;
        }
        Console.WriteLine();
    }
}
</code>```

Body:
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts.

Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

Body:
You code reversing a single linked list

It's just another example of reversing a single linked list:
(see this for more details)

// C# program for reversing the linked list
using System;

class GFG {
    static void Main(string[] args)
    {
        LinkedList list = new LinkedList();
        list.AddNode(new LinkedList.Node(85));
        list.AddNode(new LinkedList.Node(15));
        list.AddNode(new LinkedList.Node(4));
        list.AddNode(new LinkedList.Node(20));

        // List before reversal
        Console.WriteLine("Given linked list:");
        list.PrintList();

        // Reverse the list
        list.ReverseList();

        // List after reversal
        Console.WriteLine("Reversed linked list:");
        list.PrintList();
    }
}

class LinkedList {
    Node head;

    public class Node {
        public int data;
        public Node next;

        public Node(int d)
        {
            data = d;
            next = null;
        }
    }

    // function to add a new node at
    // the end of the list
    public void AddNode(Node node)
    {
        if (head == null)
            head = node;
        else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    // function to reverse the list
    public void ReverseList()
    {
        Node prev = null, current = head, next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
    }

    // function to print the list data
    public void PrintList()
    {
        Node current = head;
        while (current != null) {
            Console.Write(current.data + " ");
            current = current.next;
        }
        Console.WriteLine();
    }
}


问:
Android - Ipay88 got error Access denied finding property "ro.serialno"
hello i tried to implement IPayPayment on Android,

```<code>val checkoutIntent = Ipay.getInstance().checkout(payment,applicationContext, ResultDelegate())
checkoutIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(checkoutIntent)
</code>```

but i got error

```<code>libc: Access denied finding property "ro.serialno"
</code>```

any solution?

答:
The error is thrown later or on Android 9 devices. when we try to access Serial number of device, without application having READ_PHONE_STATE permission.

The error is thrown when serial number is read using reflection.

Apps needing the Build.serial identifier must now request the READ_PHONE_STATE permission and then use the new Build.getSerial() method added in Android 9.

Migrating Apps to Android 9

Body:
hello i tried to implement IPayPayment on Android,

val checkoutIntent = Ipay.getInstance().checkout(payment,applicationContext, ResultDelegate())
checkoutIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(checkoutIntent)

but i got error

libc: Access denied finding property "ro.serialno"

any solution?


问:
is there any method in python to replace nan in dataframe by string without effect blank cell
I have dataframe with values Na, blank and others. I want to replace Na with noted  (string value)
I want to transform from here to here without changing blank cell.

I already tried

```<code>df['A']=df['A'].replace(regex=['NaN'], value='needed')
</code>```

and

```<code>df['A'].replace(regex=['NA'], value='noted
</code>```

答:
You can use the fillna() method -

df['A'].fillna('Noted', inplace=True)

OR

df['A'] = df['A'].fillna('Noted')

To change without changing blanks - you can use a mapping function

```<code>def fillna_not_blanks(value):
    if value.strip() == '':
        return value
    elif value == np.nan:
        return 'Noted'
    else:
        return value

df['A'] = df['A'].map(fillna_not_blanks)
</code>```

Body:
I have dataframe with values Na, blank and others. I want to replace Na with noted  (string value)
I want to transform from here to here without changing blank cell.

I already tried

df['A']=df['A'].replace(regex=['NaN'], value='needed')

and

df['A'].replace(regex=['NA'], value='noted

Body:
You can use the fillna() method -

df['A'].fillna('Noted', inplace=True)

OR

df['A'] = df['A'].fillna('Noted')

To change without changing blanks - you can use a mapping function

def fillna_not_blanks(value):
    if value.strip() == '':
        return value
    elif value == np.nan:
        return 'Noted'
    else:
        return value

df['A'] = df['A'].map(fillna_not_blanks)


问:
Solution to algorithm problem has slightly incorrect output. What's wrong?
The problem was taken from here

Description:
You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent). The number of adjacent 1s forming a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input matrix. Note that these sizes do not need to be in any particular order.

```<code>Sample input:
[
    [1, 0, 0, 1, 0],
    [1, 0, 1, 0, 0],
    [0, 0, 1, 0, 1],
    [1, 0, 1, 0, 1],
    [1, 0, 1, 1, 0],
]
Sample output:
    [1, 2, 2, 2, 5]
</code>```

My solution:

I tried to solve this problem using Depth-First-Search recursively.

```<code>import java.util.*;
class River{
    int size;
    int[][]matrix;
    River(int[][]mat){
        matrix=mat;
    }
    void traverse(int x,int y){
        System.out.println(x+","+y);
        if((y-1)>=matrix.length && matrix[x][y-1]==1){
            size++;
            matrix[x][y-1]=0;
            traverse(x,y-1);
        } if((x+1)<matrix[0].length && matrix[x+1][y]==1){
            size++;
            matrix[x+1][y]=0;
            traverse(x+1,y);
        }if((x-1)>=matrix[0].length && matrix[x-1][y]==1){
                size++;
                matrix[x-1][y]=0;
                traverse(x-1,y);
        }
        if((y+1)<matrix.length && matrix[x][y+1]==1){
            size++;
            matrix[x][y+1]=0;
            traverse(x,y+1);
        }
    }
}
class Program {
  public static List<Integer> riverSizes(int[][] matrix) {
        List<Integer> SList = new ArrayList<>();
        List<River> RList = new ArrayList<>();
        System.out.println("Traversal:");

        for(int i=0;i<matrix[0].length;i++){
            for(int j=0;j<matrix.length;j++){
                if(matrix[i][j]==1){
                    matrix[i][j]=0;
                    River river = new River(matrix);
                    river.size++;
                    river.traverse(i,j);
                    RList.add(river);
                }
            }
        }
        System.out.println("Sizes:");
        for(River r:RList){
            SList.add(r.size);
            System.out.println(r.size);
        }
    return SList;
    }
    public static void main(String[]args){
        int[][]riverM={
        {1,0,0,0,0,0,1},
        {0,1,0,0,0,1,0},
        {0,0,1,0,1,0,0},
        {0,0,1,1,1,0,0},
        {0,0,1,0,1,0,0},
        {0,1,0,0,0,1,0},
        {1,0,0,0,0,0,1},
    };

        System.out.println("("+riverM.length+","+riverM[0].length+")");
        riverSizes(riverM);
    }
}
</code>```

My output passed 7/12 cases. This is one of the case that went wrong.

My Output:

```<code>Sizes:
1,1,1,1,6,1,1,1,1,1,
</code>```

Expected Output:

```<code>Sizes:
1,1,1,1,7,1,1,1,1,1,
</code>```

Can someone tell me what's going wrong?

答:
I think the problem is located into your traverse function:

```<code>if((y-1)>=matrix.length && matrix[x][y-1]==1){...}
</code>```

The left part of the condition (y-1)>=matrix.length is wrong. Here, correct me if I'm wrong, you just want to prevent IndexOutOfBoundsException. To do it, you should test something like (y-1) >= 0.

Same error when you're testing your x index. Test the output with these fixes, didn't check if there's something else wrong.

Body:
The problem was taken from here

Description:
You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent). The number of adjacent 1s forming a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input matrix. Note that these sizes do not need to be in any particular order.

Sample input:
[
    [1, 0, 0, 1, 0],
    [1, 0, 1, 0, 0],
    [0, 0, 1, 0, 1],
    [1, 0, 1, 0, 1],
    [1, 0, 1, 1, 0],
]
Sample output:
    [1, 2, 2, 2, 5]

My solution:

I tried to solve this problem using Depth-First-Search recursively.

import java.util.*;
class River{
    int size;
    int[][]matrix;
    River(int[][]mat){
        matrix=mat;
    }
    void traverse(int x,int y){
        System.out.println(x+","+y);
        if((y-1)>=matrix.length && matrix[x][y-1]==1){
            size++;
            matrix[x][y-1]=0;
            traverse(x,y-1);
        } if((x+1)<matrix[0].length && matrix[x+1][y]==1){
            size++;
            matrix[x+1][y]=0;
            traverse(x+1,y);
        }if((x-1)>=matrix[0].length && matrix[x-1][y]==1){
                size++;
                matrix[x-1][y]=0;
                traverse(x-1,y);
        }
        if((y+1)<matrix.length && matrix[x][y+1]==1){
            size++;
            matrix[x][y+1]=0;
            traverse(x,y+1);
        }
    }
}
class Program {
  public static List<Integer> riverSizes(int[][] matrix) {
        List<Integer> SList = new ArrayList<>();
        List<River> RList = new ArrayList<>();
        System.out.println("Traversal:");

        for(int i=0;i<matrix[0].length;i++){
            for(int j=0;j<matrix.length;j++){
                if(matrix[i][j]==1){
                    matrix[i][j]=0;
                    River river = new River(matrix);
                    river.size++;
                    river.traverse(i,j);
                    RList.add(river);
                }
            }
        }
        System.out.println("Sizes:");
        for(River r:RList){
            SList.add(r.size);
            System.out.println(r.size);
        }
    return SList;
    }
    public static void main(String[]args){
        int[][]riverM={
        {1,0,0,0,0,0,1},
        {0,1,0,0,0,1,0},
        {0,0,1,0,1,0,0},
        {0,0,1,1,1,0,0},
        {0,0,1,0,1,0,0},
        {0,1,0,0,0,1,0},
        {1,0,0,0,0,0,1},
    };

        System.out.println("("+riverM.length+","+riverM[0].length+")");
        riverSizes(riverM);
    }
}

My output passed 7/12 cases. This is one of the case that went wrong.

My Output:

Sizes:
1,1,1,1,6,1,1,1,1,1,

Expected Output:

Sizes:
1,1,1,1,7,1,1,1,1,1,

Can someone tell me what's going wrong?

Body:
I think the problem is located into your traverse function:

if((y-1)>=matrix.length && matrix[x][y-1]==1){...}

The left part of the condition (y-1)>=matrix.length is wrong. Here, correct me if I'm wrong, you just want to prevent IndexOutOfBoundsException. To do it, you should test something like (y-1) >= 0.

Same error when you're testing your x index. Test the output with these fixes, didn't check if there's something else wrong.


问:
kafka connect elasticsearch connector (sink) data move in (almost) real-time
interested in moving data from kafka to elasticsearch. so i have setup kafka connect elasticsearch connector.

although i reviewed all the documentation and the configuration, i have yet found how to configure the connector to move data from kafka to elasticsearch in (near) real-time.

that is, making the connector consume message from the (kafka) topic each second and write them into elasticsearch, mimking streaming of messages from kafka to elasticsearch.

this is the current configuration for the connector:

```<code>{
  "name": "elasticsearch-sink",
  "config": {
    "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
    "tasks.max": "1",
    "topics": "foo",
    "key.ignore": "true",
    "schema.ignore": "true",
    "connection.url": "http://elasticsearch:9200",
    "type.name": "kafka-connect",
    "name": "elasticsearch-sink"
  }
}
</code>```

how does the connector need to be configured so it'll "stream" message from kafka to elasticsearch?

答:
Since Kafka Sink Connector is based on consumer, you can control polling interval via consumer properties (e.g. max.poll.interval.ms, max.poll.records). To configure, just add consumer property with prefix consumer. to your connector config:

consumer.max.poll.records=1

Body:
interested in moving data from kafka to elasticsearch. so i have setup kafka connect elasticsearch connector.

although i reviewed all the documentation and the configuration, i have yet found how to configure the connector to move data from kafka to elasticsearch in (near) real-time.

that is, making the connector consume message from the (kafka) topic each second and write them into elasticsearch, mimking streaming of messages from kafka to elasticsearch.

this is the current configuration for the connector:

{
  "name": "elasticsearch-sink",
  "config": {
    "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
    "tasks.max": "1",
    "topics": "foo",
    "key.ignore": "true",
    "schema.ignore": "true",
    "connection.url": "http://elasticsearch:9200",
    "type.name": "kafka-connect",
    "name": "elasticsearch-sink"
  }
}

how does the connector need to be configured so it'll "stream" message from kafka to elasticsearch?


问:
How to get JSON Array Java
I have code to get JSON Object but now I need to get a JSON Array.</p>

```<code>JSONObject jData = new JSONObject(data);
        JSONObject rates = jData.getJSONObject("page");
        JSONArray namesArray = rates.names();
        for (int i = 0; i < namesArray.length(); i++) {
            String currency = namesArray.getString(i);
            String rate = rates.getString(currency);
            stringBuilder.append(String.format("%s: %s\n", currency, rate));
        }
</code>```

答:
You can do like

```<code> java.lang.Object optionWraper = data.get(key);
            JSONArray jarray = new JSONArray();
            if (optionWraper instanceof JSONArray) {
                jarray = (JSONArray) optionWraper;
             } else if (optionWraper instanceof JSONObject) {
              jarray.put((JSONObject) optionWraper);
             }
</code>```

You can parse the input object in either case JSONObject or JSONArray and don't need to worry about the type in runtime  .

Title: How to get JSON Array Java

Body:
I have code to get JSON Object but now I need to get a JSON Array.

JSONObject jData = new JSONObject(data);
        JSONObject rates = jData.getJSONObject("page");
        JSONArray namesArray = rates.names();
        for (int i = 0; i < namesArray.length(); i++) {
            String currency = namesArray.getString(i);
            String rate = rates.getString(currency);
            stringBuilder.append(String.format("%s: %s\n", currency, rate));
        }

Body:
You can do like

 java.lang.Object optionWraper = data.get(key);
            JSONArray jarray = new JSONArray();
            if (optionWraper instanceof JSONArray) {
                jarray = (JSONArray) optionWraper;
             } else if (optionWraper instanceof JSONObject) {
              jarray.put((JSONObject) optionWraper);
             }

You can parse the input object in either case JSONObject or JSONArray and don't need to worry about the type in runtime  .


问:
Can I use default workflows for this?
I have to create a workflow in Sharepoint online shown in the image. Below is the explanation of the workflow

A Sharepoint list form will be defined with required fields.

Step 1:
Whenever a new project requestor wants to request for resources, they use the link to create a new line item and submit
Step 2:
This item should be assigned to Manager. He will verify the details and assign it to some Lead.
Step 3 :
Lead will work with the requestor offline to gather details about the request and comes up with level of efforts, no. of resources required, etc. and creates a form(some excel template). This form needs to be uploaded to this request and on submit,
Step 4:
Now this item should go back to the manager. Manager will finally review the form created by the lead (and allocate resources - not part of this workflow) and closes the request, and the requests lifecycle is ended.

Is there a way I can achieve this using the inbuild workflow types given in SP online, or Should I create the workflow from scratch - I'm very new to SP, so sorry for the basic question

答:
I don't think the default workflow would meet your requirements. Here are two options for you:

Use microsoft flow to build your workflow.

If you do not have flow license, I would suggest you use SharePoint Designer to build your wokflow.

If you have questions to build your workflow, feel free to ask.

Title: Can I use default workflows for this?


问:
Spring Boot how execute stored procedure multiple times?
I need to execute a procedure multiple times with the requestbody. For now, i am using for loop to do that, but it is not a good way. For example, when the one request is failed, catching that request is a problem. See for the example usage.

Implementation of stored procedure with for-loop;

```<code>**Controller**
public void runSP(
   @RequestBody List<IdNoteModel> idNotes
){
   getService().runSP(idNotes);
}

</code>```

```<code>**Service**
public void runSP(List<IdNoteModel> idNotes){
   for (IdNoteModel idNote : idNotes){
      getRepository().runSP(idNote);
   }
}

</code>```

```<code>**Repository**
@Query(nativeQuery = true, value = "EXECUTE PROCEDURE SP_RUN_ID_NOTE(:id, :note)")
void runSP(Long id, String note);
</code>```

Is there a better way to run stored procedures multiple times? or do you have an idea to catch the failed requests?

答: You can use one stored procedure in which you can use the cursor to execute the procedure (SP_RUN_ID_NOTE) multiple times. In that stored procedure, you can also use rollback for something to fail. In your above case, you can store request body input in the table and then call procedure while taking input row from that table.

Body:
I need to execute a procedure multiple times with the requestbody. For now, i am using for loop to do that, but it is not a good way. For example, when the one request is failed, catching that request is a problem. See for the example usage.

Implementation of stored procedure with for-loop;

**Controller**
public void runSP(
   @RequestBody List<IdNoteModel> idNotes
){
   getService().runSP(idNotes);
}

**Service**
public void runSP(List<IdNoteModel> idNotes){
   for (IdNoteModel idNote : idNotes){
      getRepository().runSP(idNote);
   }
}

**Repository**
@Query(nativeQuery = true, value = "EXECUTE PROCEDURE SP_RUN_ID_NOTE(:id, :note)")
void runSP(Long id, String note);

Is there a better way to run stored procedures multiple times? or do you have an idea to catch the failed requests?


问:
Laravel request helper in URL to get ID / Resource ID
I'm working on a Laravel 5.6 app and have the following two API routes:

```<code>Route::resource('/partners', 'API\Partners\PartnersController');

Route::resource('/partners/{id}/sales-team', 'API\Partners\SalesTeamController');
</code>```

In both of the controllers I am referencing a custom middleware 'VerifyUserOwnsTeam' in the construct method.

To get the resource ID from the request in the middleware I previously had:

```<code>$request->route('partner')
</code>```

This worked a URL such as:

```<code>/api/partners/1
</code>```

However, I am now calling a new end point such as:

```<code>/api/partners/1/sales-team
</code>```

In my middleware the request route param for partner is null. If I change the reference to be:

```<code>$request->route('id')
</code>```

Then it works for the latter endpoint, but fails on the first for a null value.

Any idea how to get this consistent?

答:
For all searchers:
For resources in edit/update/delete actions you can access id of the model inside Request classes using </p>

```<code>$this->get('id')
</code>```

Body:
I'm working on a Laravel 5.6 app and have the following two API routes:

Route::resource('/partners', 'API\Partners\PartnersController');

Route::resource('/partners/{id}/sales-team', 'API\Partners\SalesTeamController');

In both of the controllers I am referencing a custom middleware 'VerifyUserOwnsTeam' in the construct method.

To get the resource ID from the request in the middleware I previously had:

$request->route('partner')

This worked a URL such as:

/api/partners/1

However, I am now calling a new end point such as:

/api/partners/1/sales-team

In my middleware the request route param for partner is null. If I change the reference to be:

$request->route('id')

Then it works for the latter endpoint, but fails on the first for a null value.

Any idea how to get this consistent?

Body:
For all searchers:
For resources in edit/update/delete actions you can access id of the model inside Request classes using

$this->get('id')


问:
Module-scoped css files
TLDR in Angular 9, is it possible to lazy load CSS styles (not component-specific)?

My module structure:

```<code>AppModule
  |--AppFormsModule
  |--AppSharedModule

AdminModule
  |--AppFormsModule
  |--AppSharedModule
</code>```

AdminModule is lazy loaded via a route in my main app module:

```<code>{
  path: appPaths.admin.path,
  canLoad: [ChapterAdminGuardService],
  loadChildren: () => import('../modules/admin/admin.module').then(m => m.AdminModule)
}
</code>```

I have some amount of css that is specific to several components in the admin module. It is currently bundled into the global css file along with the css used by my main module.

Is it possible to lazy-load this css from somewhere else? With the clear benefit that extra resources aren't downloaded by the client until needed.

Ideally I would be able to specify that specific style bundles should be loaded for specific modules.

I am also open to different approaches. For example - is it possible to specify that a module should use a different version of index.html?

答:
You can use the root component of the AdminModule, let's call it AppComponent, and use the ::ng-deep (deprecated) selector in combination with :host. Even though this selector is deprecated, they will not remove it until there is a suitable replacement option:

app.component.scss:

```<code>:host ::ng-deep {
  // This will make any paragraph element which is a child of the app-component element red
  p {
    color: #F00;
  }
}
</code>```

And by adding it as a component specific stylesheet, this will be lazy loaded when the admin module is loaded.

If you want to use ViewEncapsulation.None, you can do something like this:

```<code>@Component({
  selector: 'app-admin-module',
  styleUrls: [ './admin.component.scss' ],
  encapsulation: ViewEncapsulation.None
})
export class AdminComponent {}
</code>```

admin.component.scss:

```<code>app-admin-module {
  // declare all your module styles here
  p {
    color: #F00;
  }
}
</code>```

Title: Module-scoped css files

Body:
TLDR in Angular 9, is it possible to lazy load CSS styles (not component-specific)?

My module structure:

AppModule
  |--AppFormsModule
  |--AppSharedModule

AdminModule
  |--AppFormsModule
  |--AppSharedModule

AdminModule is lazy loaded via a route in my main app module:

{
  path: appPaths.admin.path,
  canLoad: [ChapterAdminGuardService],
  loadChildren: () => import('../modules/admin/admin.module').then(m => m.AdminModule)
}

I have some amount of css that is specific to several components in the admin module. It is currently bundled into the global css file along with the css used by my main module.

Is it possible to lazy-load this css from somewhere else? With the clear benefit that extra resources aren't downloaded by the client until needed.

Ideally I would be able to specify that specific style bundles should be loaded for specific modules.

I am also open to different approaches. For example - is it possible to specify that a module should use a different version of index.html?

Body:
You can use the root component of the AdminModule, let's call it AppComponent, and use the ::ng-deep (deprecated) selector in combination with :host. Even though this selector is deprecated, they will not remove it until there is a suitable replacement option:

app.component.scss:

:host ::ng-deep {
  // This will make any paragraph element which is a child of the app-component element red
  p {
    color: #F00;
  }
}

And by adding it as a component specific stylesheet, this will be lazy loaded when the admin module is loaded.

If you want to use ViewEncapsulation.None, you can do something like this:

@Component({
  selector: 'app-admin-module',
  styleUrls: [ './admin.component.scss' ],
  encapsulation: ViewEncapsulation.None
})
export class AdminComponent {}

admin.component.scss:

app-admin-module {
  // declare all your module styles here
  p {
    color: #F00;
  }
}


问:
How to downgrade to a previous Node version
I want to downgrade my Node version from the latest to v6.10.3.

But nothing has worked so far. Tried NVM and it gives an error as well by saying that the make command is not found. How can I downgrade Node?

答:
Determining your Node version

```<code>node -v  // or node --version
npm -v   // npm version or long npm --version
</code>```

Ensure that you have n installed

```<code>sudo npm install -g n // -g for global installation
</code>```

Upgrading to the latest stable version

```<code>sudo n stable
</code>```

Changing to a specific version

```<code>sudo n 10.16.0
</code>```

Answer inspired by this article.

Body:
Determining your Node version

node -v  // or node --version
npm -v   // npm version or long npm --version

Ensure that you have n installed

sudo npm install -g n // -g for global installation

Upgrading to the latest stable version

sudo n stable

Changing to a specific version

sudo n 10.16.0

Answer inspired by this article.


问:
Programming Riddle: How might you translate an Excel column name to a number?
I was recently asked in a job interview to resolve a programming puzzle that I thought it would be interesting to share. It's about translating Excel column letters to actual numbers, if you recall, Excel names its columns with letters from A to Z, and then the sequence goes AA, AB, AC... AZ, BA, BB, etc.

You have to write a function that accepts a string as a parameter (like "AABCCE") and returns the actual column number.

The solution can be in any language.

答:
In Mathematica:</p>

```<code>FromDigits[ToCharacterCode@# - 64, 26] &
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Mathematica:

FromDigits[ToCharacterCode@# - 64, 26] &


问:
Join back missing date matches
I have the following table:

```<code>| variable | varDate    | match |
|----------|------------|-------|
| var1     | 15/02/2020 | 98    |
| var1     | 16/02/2020 | 99    |
| var1     | 17/02/2020 | 97    |
| var2     | 15/02/2020 | 95    |
</code>```

I would like to populate var2, for the dates 16/02/2020 and 17/02/2020 (those that are missing, and if null, populate with the value 100).

I have a table that contains the last three days in a table, that looks like so:

```<code>| date       |
|------------|
| 15/02/2020 |
| 16/02/2020 |
| 17/02/2020 |
</code>```

My attempt was to use a left join on varDate = date, however this didn't produce the result I expected like below:

```<code>| variable | date       | match |
|----------|------------|-------|
| var1     | 15/02/2020 | 98    |
| var1     | 16/02/2020 | 99    |
| var1     | 17/02/2020 | 97    |
| var2     | 15/02/2020 | 95    |
| var2     | 16/02/2020 | 100   |
| var2     | 17/02/2020 | 100   |
</code>```

答:
Consider:

```<code>select
    v.variable,
    d.date,
    coalesce(t.match, 100) match
from (select distinct variable from mytable) v
cross join mydates d
left join mytable t
    on  t.varDate = d.date
    and t.variable = v.variable
</code>```

This works by first cross joining the distinct values of variable available in the table with the table that references the dates (I called it mydates). This generates all possible combinations of dates and variables.

Then, we bring in the original table (I assumed mytable) with a left join. Finally, we use coalesce() to assign a default value for missing matches.

Ideally, you should have a reference table for the variables as well, which would avoid the need for the distinct subquery:

```<code>select
    v.variable,
    d.date,
    coalesce(t.match, 100) match
from myvariables v
cross join mydates d
left join mytable t
    on  t.varDate = d.date
    and t.variable = v.variable
</code>```

Title: Join back missing date matches

Body:
I have the following table:

| variable | varDate    | match |
|----------|------------|-------|
| var1     | 15/02/2020 | 98    |
| var1     | 16/02/2020 | 99    |
| var1     | 17/02/2020 | 97    |
| var2     | 15/02/2020 | 95    |

I would like to populate var2, for the dates 16/02/2020 and 17/02/2020 (those that are missing, and if null, populate with the value 100).

I have a table that contains the last three days in a table, that looks like so:

| date       |
|------------|
| 15/02/2020 |
| 16/02/2020 |
| 17/02/2020 |

My attempt was to use a left join on varDate = date, however this didn't produce the result I expected like below:

| variable | date       | match |
|----------|------------|-------|
| var1     | 15/02/2020 | 98    |
| var1     | 16/02/2020 | 99    |
| var1     | 17/02/2020 | 97    |
| var2     | 15/02/2020 | 95    |
| var2     | 16/02/2020 | 100   |
| var2     | 17/02/2020 | 100   |

Body:
Consider:

select
    v.variable,
    d.date,
    coalesce(t.match, 100) match
from (select distinct variable from mytable) v
cross join mydates d
left join mytable t
    on  t.varDate = d.date
    and t.variable = v.variable

This works by first cross joining the distinct values of variable available in the table with the table that references the dates (I called it mydates). This generates all possible combinations of dates and variables.

Then, we bring in the original table (I assumed mytable) with a left join. Finally, we use coalesce() to assign a default value for missing matches.

Ideally, you should have a reference table for the variables as well, which would avoid the need for the distinct subquery:

select
    v.variable,
    d.date,
    coalesce(t.match, 100) match
from myvariables v
cross join mydates d
left join mytable t
    on  t.varDate = d.date
    and t.variable = v.variable


问:
AuthorizeAttribute does nothing in ASP.NET Core 3 MVC
I have an ASP.NET Core 3.1 MVC project, with a simple authentication system based on cookies, and a few roles and policies. DI is handled with Autofac (not internal DI system of ASP.NET Core).

I know my user is correctly loaded with proper roles, and calls to internal methods like Context.User.IsInRole("Administrator")) (from views) are working as expected.

However, all my AuthorizeAttribute are not working, depending of the content of my Startup whether they seem to do nothing, or I am always redirected to login page (even if the right requirement is fulfilled).

An annotation like

```<code>[Authorize(Policy = "Administrator,Collaborator")]
</code>```

or a simple

```<code>[Authorize(Roles = "Administrator")]
</code>```

placed on an action method seems to do nothing.

I know that order of calls in startup Configure and ConfigureServices matter a lot, but despite many attempts and a lot of reading of similar questions on SO or somewhere else, I was not able to make it work as expected.

I share below my whole Startup file (sorry for that), in hope somebody will be able to point the correct order (or another kind of fix of course), to make it work for my specific case.

Thanks a lot.

```<code>    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment Environment { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddOptions();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.HttpOnly = true;
                    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                    options.Cookie.SameSite = SameSiteMode.Strict;
                    options.LoginPath = "/Account/Login";
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = new TimeSpan(0, 24, 0, 0);
                    options.AccessDeniedPath = "/Error/RightError";
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(SecurityPolicies.AdministratorOnly, policy =>
                    policy.RequireClaim(ClaimTypes.Role, UserRoles.Administrator));
                options.AddPolicy(SecurityPolicies.AdministratorOrCollaborator, policy =>
                    policy.RequireClaim(ClaimTypes.Role, UserRoles.Administrator, UserRoles.Collaborator));
            });

            services.AddSession(options => options.IdleTimeout = TimeSpan.FromHours(4));
            services.AddMvc(options => options.Filters.Add(new AuthorizeFilter()))
            .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            services.AddKendo();
        }

        // ConfigureContainer is where you can register things directly
        // with Autofac. This runs after ConfigureServices so the things
        // here will override registrations made in ConfigureServices.
        // Don't build the container; that gets done for you by the factory.
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new MyFrontModule());
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseExceptionHandler(ProcessError);
            }
            else
            {
                app.UseExceptionHandler("/Error/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseCookiePolicy();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                    endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

            var ci = new CultureInfo("fr-FR")
            {
                NumberFormat = { NumberDecimalSeparator = ".", CurrencyDecimalSeparator = "." }
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(ci),
                SupportedCultures = new List<CultureInfo> { ci },
                SupportedUICultures = new List<CultureInfo> { ci }
            });
        }

        private void ProcessError(IApplicationBuilder appError)
        {
            appError.Run(async context =>
            {
                // Not relevant for my question
            });
        }
    }
</code>```

I also read that Json Serializer may change something, I am using Newtonsoft with DefaultContractResolver (as above), and I am using Telerik UI components.

Thanks a lot for any useful advice !

答:
As explained in question, I have never been able to have Authorize attribute working as expected, so as my needs in right management were pretty simple, as a workaround I've just implemented a very straightforward FilterAttribute to verify rights based on owned roles.

```<code>public class RoleRequirementAttribute : TypeFilterAttribute
{
    public RoleRequirementAttribute(params string[] claimValues)
        : base(typeof(ClaimRequirementFilter))
    {
        Arguments = new []{ claimValues.Select(cv => new Claim(ClaimTypes.Role, cv)) };
    }
}

public class ClaimRequirementFilter : IAuthorizationFilter
{
    readonly IEnumerable<Claim> _claims;

    public ClaimRequirementFilter(IEnumerable<Claim> claims)
    {
        _claims = claims;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var hasClaim =  context.HttpContext.User.Claims.Any(owned => _claims.Any(required => owned.Type == required.Type && owned.Value == required.Value));

        if (!hasClaim)
        {
            context.Result = new ForbidResult();
        }
    }
}
</code>```

Body:
I have an ASP.NET Core 3.1 MVC project, with a simple authentication system based on cookies, and a few roles and policies. DI is handled with Autofac (not internal DI system of ASP.NET Core).

I know my user is correctly loaded with proper roles, and calls to internal methods like Context.User.IsInRole("Administrator")) (from views) are working as expected.

However, all my AuthorizeAttribute are not working, depending of the content of my Startup whether they seem to do nothing, or I am always redirected to login page (even if the right requirement is fulfilled).

An annotation like

[Authorize(Policy = "Administrator,Collaborator")]

or a simple

[Authorize(Roles = "Administrator")]

placed on an action method seems to do nothing.

I know that order of calls in startup Configure and ConfigureServices matter a lot, but despite many attempts and a lot of reading of similar questions on SO or somewhere else, I was not able to make it work as expected.

I share below my whole Startup file (sorry for that), in hope somebody will be able to point the correct order (or another kind of fix of course), to make it work for my specific case.

Thanks a lot.

    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment Environment { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddOptions();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.HttpOnly = true;
                    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                    options.Cookie.SameSite = SameSiteMode.Strict;
                    options.LoginPath = "/Account/Login";
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = new TimeSpan(0, 24, 0, 0);
                    options.AccessDeniedPath = "/Error/RightError";
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(SecurityPolicies.AdministratorOnly, policy =>
                    policy.RequireClaim(ClaimTypes.Role, UserRoles.Administrator));
                options.AddPolicy(SecurityPolicies.AdministratorOrCollaborator, policy =>
                    policy.RequireClaim(ClaimTypes.Role, UserRoles.Administrator, UserRoles.Collaborator));
            });

            services.AddSession(options => options.IdleTimeout = TimeSpan.FromHours(4));
            services.AddMvc(options => options.Filters.Add(new AuthorizeFilter()))
            .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            services.AddKendo();
        }

        // ConfigureContainer is where you can register things directly
        // with Autofac. This runs after ConfigureServices so the things
        // here will override registrations made in ConfigureServices.
        // Don't build the container; that gets done for you by the factory.
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new MyFrontModule());
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseExceptionHandler(ProcessError);
            }
            else
            {
                app.UseExceptionHandler("/Error/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseCookiePolicy();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                    endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

            var ci = new CultureInfo("fr-FR")
            {
                NumberFormat = { NumberDecimalSeparator = ".", CurrencyDecimalSeparator = "." }
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(ci),
                SupportedCultures = new List<CultureInfo> { ci },
                SupportedUICultures = new List<CultureInfo> { ci }
            });
        }

        private void ProcessError(IApplicationBuilder appError)
        {
            appError.Run(async context =>
            {
                // Not relevant for my question
            });
        }
    }

I also read that Json Serializer may change something, I am using Newtonsoft with DefaultContractResolver (as above), and I am using Telerik UI components.

Thanks a lot for any useful advice !

Body:
As explained in question, I have never been able to have Authorize attribute working as expected, so as my needs in right management were pretty simple, as a workaround I've just implemented a very straightforward FilterAttribute to verify rights based on owned roles.

public class RoleRequirementAttribute : TypeFilterAttribute
{
    public RoleRequirementAttribute(params string[] claimValues)
        : base(typeof(ClaimRequirementFilter))
    {
        Arguments = new []{ claimValues.Select(cv => new Claim(ClaimTypes.Role, cv)) };
    }
}

public class ClaimRequirementFilter : IAuthorizationFilter
{
    readonly IEnumerable<Claim> _claims;

    public ClaimRequirementFilter(IEnumerable<Claim> claims)
    {
        _claims = claims;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var hasClaim =  context.HttpContext.User.Claims.Any(owned => _claims.Any(required => owned.Type == required.Type && owned.Value == required.Value));

        if (!hasClaim)
        {
            context.Result = new ForbidResult();
        }
    }
}


问:
Split an XML to send it to a stored procedure in SQL Server
I have a question about splitting a XML input parameter and sending it to another stored procedure (SQL Server).

I have a master stored procedure which has in input a XML (see below).
I would like this stored procedure to split the XML by RDHistorique.
Then send every RDHistorique to a child stored procedure.

```<code><ArrayOfRDHistorique>
  <RDHistorique>
    <Id>1955</Id>
    <sect_code>08</sect_code>
    <arch_islast>0</arch_islast>
    <ListeEtapes>
        <EtapeWorkflowArchive>
            <Statut>00</Statut>
            <Nom>John DOE</Nom>
            <Date>2009-12-31</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>02</Statut>
            <Nom>John DOE</Nom>
            <Date>2009-12-31</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>03</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire>Silly comment</Commentaire>
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>04</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire>Silly comment</Commentaire>
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>05</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
    </ListeEtapes>
  </RDHistorique>
    <RDHistorique>
    <Id>1999</Id>
    <sect_code>08</sect_code>
    <arch_islast>0</arch_islast>
    <ListeEtapes>
        <EtapeWorkflowArchive>
            <Statut>00</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-12-31</Date>
            <Commentaire />
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>02</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-12-31</Date>
            <Commentaire />
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>03</Statut>
            <Nom>NULL</Nom>
            <Date>2011-06-29</Date>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>06</Statut>
            <Nom>NULL</Nom>
            <Commentaire>Silly comment</Commentaire>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>11</Statut>
            <Nom>NULL</Nom>
            <Commentaire>NULL</Commentaire>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
    </ListeEtapes>
  </RDHistorique>
</ArrayOfRDHistorique>
</code>```

I know I can do what I want using cursors, but I would like to do it using Select.
I can already select the nodes I want like this:

```<code>SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire

FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)
</code>```

My question is then: Can I call a stored procedure for every node in a XML File?

答:
I you really need iterative approach (procedure is already written, you do some NON-SQL jobs), CURSOR is the option:

```<code>CREATE PROCEDURE ProcessStatut(@statut varchar(50), @nom varchar(50),@commentaire varchar(50)) AS
BEGIN
    SELECT @statut Statut, @nom Nom, @commentaire Commentaire, 'Hello world!' Hello
END
</code>```

Then:

```<code>DECLARE @statut varchar(50), @nom varchar(50),@commentaire varchar(50);
DECLARE c CURSOR FOR
SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire
FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)

OPEN c
FETCH NEXT FROM c INTO @statut, @nom, @commentaire
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC ProcessStatut @statut, @nom, @commentaire
    FETCH NEXT FROM c INTO @statut, @nom, @commentaire
END
CLOSE c
DEALLOCATE c
</code>```

Each row will be processed separately.

Edit 1:
If you need to pass table, you can declare TABLE type:

```<code>CREATE TYPE StatutList AS TABLE (
    Statut varchar(50),
    Nom varchar(50),
    Commentaire varchar(50)
)
GO
CREATE PROCEDURE ProcessStatutList(@statutList StatutList READONLY) AS
BEGIN
    SELECT *, 'I was here!' Hello FROM @statutList
END
GO
</code>```

And then, use this to pass all items at once:

```<code>DECLARE @statutList StatutList;
INSERT @statutList
SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire
FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)

EXEC ProcessStatutList @statutList;
</code>```

Body:
I have a question about splitting a XML input parameter and sending it to another stored procedure (SQL Server).

I have a master stored procedure which has in input a XML (see below).
I would like this stored procedure to split the XML by RDHistorique.
Then send every RDHistorique to a child stored procedure.

<ArrayOfRDHistorique>
  <RDHistorique>
    <Id>1955</Id>
    <sect_code>08</sect_code>
    <arch_islast>0</arch_islast>
    <ListeEtapes>
        <EtapeWorkflowArchive>
            <Statut>00</Statut>
            <Nom>John DOE</Nom>
            <Date>2009-12-31</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>02</Statut>
            <Nom>John DOE</Nom>
            <Date>2009-12-31</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>03</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire>Silly comment</Commentaire>
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>04</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire>Silly comment</Commentaire>
            <Id>1955</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>05</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-06-23</Date>
            <Commentaire />
            <Id>1955</Id>
        </EtapeWorkflowArchive>
    </ListeEtapes>
  </RDHistorique>
    <RDHistorique>
    <Id>1999</Id>
    <sect_code>08</sect_code>
    <arch_islast>0</arch_islast>
    <ListeEtapes>
        <EtapeWorkflowArchive>
            <Statut>00</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-12-31</Date>
            <Commentaire />
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>02</Statut>
            <Nom>John DOE</Nom>
            <Date>2010-12-31</Date>
            <Commentaire />
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>03</Statut>
            <Nom>NULL</Nom>
            <Date>2011-06-29</Date>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>06</Statut>
            <Nom>NULL</Nom>
            <Commentaire>Silly comment</Commentaire>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
        <EtapeWorkflowArchive>
            <Statut>11</Statut>
            <Nom>NULL</Nom>
            <Commentaire>NULL</Commentaire>
            <Id>1999</Id>
        </EtapeWorkflowArchive>
    </ListeEtapes>
  </RDHistorique>
</ArrayOfRDHistorique>

I know I can do what I want using cursors, but I would like to do it using Select.
I can already select the nodes I want like this:

SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire

FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)

My question is then: Can I call a stored procedure for every node in a XML File?

Body:
I you really need iterative approach (procedure is already written, you do some NON-SQL jobs), CURSOR is the option:

CREATE PROCEDURE ProcessStatut(@statut varchar(50), @nom varchar(50),@commentaire varchar(50)) AS
BEGIN
    SELECT @statut Statut, @nom Nom, @commentaire Commentaire, 'Hello world!' Hello
END

Then:

DECLARE @statut varchar(50), @nom varchar(50),@commentaire varchar(50);
DECLARE c CURSOR FOR
SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire
FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)

OPEN c
FETCH NEXT FROM c INTO @statut, @nom, @commentaire
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC ProcessStatut @statut, @nom, @commentaire
    FETCH NEXT FROM c INTO @statut, @nom, @commentaire
END
CLOSE c
DEALLOCATE c

Each row will be processed separately.

Edit 1:
If you need to pass table, you can declare TABLE type:

CREATE TYPE StatutList AS TABLE (
    Statut varchar(50),
    Nom varchar(50),
    Commentaire varchar(50)
)
GO
CREATE PROCEDURE ProcessStatutList(@statutList StatutList READONLY) AS
BEGIN
    SELECT *, 'I was here!' Hello FROM @statutList
END
GO

And then, use this to pass all items at once:

DECLARE @statutList StatutList;
INSERT @statutList
SELECT
    b.value('(./Statut/text())[1]','Varchar(50)') as Statut,
    b.value('(./Nom/text())[1]','Varchar(50)') as Nom,
    b.value('(./Commentaire/text())[1]','Varchar(50)') as Commentaire
FROM @xml.nodes('/ArrayOfRDHistorique/RDHistorique/ListeEtapes/*') as a(b)

EXEC ProcessStatutList @statutList;


问:
Can Qt lrelease tool process XLIFF files instead of ts-files?
In the documentation of the Qt lrelease tool I read, that .ts files can be compiled to .qm binaries using following command:

```<code>lrelease.exe main_en.ts languages\main_fr.ts
</code>```

Is it possible to take .xliff files as well as input instead of the .ts files to compile .xliff files to .qm files? How is it done?

答:
From the documentation of lupdate, it is mentioned that you can generate .ts file from XLIFF files. You can then use lrelease to generate the .qm file.

Be aware that only the XLIFF 1.1 format is supported, not the 1.0.

Body:
In the documentation of the Qt lrelease tool I read, that .ts files can be compiled to .qm binaries using following command:

lrelease.exe main_en.ts languages\main_fr.ts

Is it possible to take .xliff files as well as input instead of the .ts files to compile .xliff files to .qm files? How is it done?


问:
Why python script loop is not fetching updated data from DB?
I've two Python script. Both of them uses PYMYSQL to read / write data on a table of MySQL DB.

Script 1: It runs in a infinite while loop and fetches data from outside API in every second and updates the same to the table of MySQL DB via UPDATE SQL Query. It's working completely fine. I can see on DB level that data is getting updated every second.

Script 2: It runs in a infinite while loop and fetches data from above mentioned table of MySQL DB and prints it via SELECT SQL Query. While I run it first time, it fetches correct / updated / latest data from DB, but after that when it iterates on the while loop, it fetches the same data which it fetched at the first time of starting and does not fetch the updated data. But it should fetch the updated data as Script 1 is continuously updating the data on DB every second. But if I stop the script and restarts then it shows the updated data.

I just want to know the reason or fix for same. It seems that when DB connection is getting restarted for Script 2 when I restart the script, it fetches the latest data.

Kindly help on same.

答:
I have found the fix. Any of below can be applied.

Adding autocommit=True into the connect() parameters.

Calling conn.commit() after the cursor.execute() command.

It's repeatable read as mentioned here: https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_consistent_read


问:
Batch renaming files with Bash
How can Bash rename a series of packages to remove their version numbers? I've been toying around with both expr and %%, to no avail.

Examples:

Xft2-2.1.13.pkg becomes Xft2.pkg

jasper-1.900.1.pkg becomes jasper.pkg

xorg-libXrandr-1.2.3.pkg becomes xorg-libXrandr.pkg

答:
I'll do something like this:

```<code>for file in *.pkg ; do
    mv $file $(echo $file | rev | cut -f2- -d- | rev).pkg
done
</code>```

supposed all your file are in the current directory. If not, try to use find as advised above by Javier.

EDIT: Also, this version don't use any bash-specific features, as others above, which leads you to more portability.

OwnerDisplayName: Nerdling

Title: Batch renaming files with Bash

Body:
I'll do something like this:

for file in *.pkg ; do
    mv $file $(echo $file | rev | cut -f2- -d- | rev).pkg
done

supposed all your file are in the current directory. If not, try to use find as advised above by Javier.

EDIT: Also, this version don't use any bash-specific features, as others above, which leads you to more portability.

OwnerDisplayName: Diego Sevilla


问:
How do you set up Caliburn Micro guard methods for items not in the view?
I'm trying to get Caliburn Micro going in my project and I'm having trouble understanding guard methods (Can*) in the context of properties that aren't bound to the view (forgive me if I'm getting my terminology wrong).

I've adapted Tim Corey's example to add this snippet:

```<code>        private bool _connected;

        public bool Connected
        {
            get { return _connected; }
            set { _connected = value; NotifyOfPropertyChange(() => Connected); }
        }

        public bool CanSayHello(bool connected)
        {
            return connected;
        }

        public void SayHello(bool connected)
        {
            Console.WriteLine("Hello!");
        }

        public bool CanClearText(string firstName, string lastName)
        {
            if (String.IsNullOrWhiteSpace(firstName) && string.IsNullOrWhiteSpace(lastName))
            {
                Connected = false;
                return false;
            }
            else
            {
                Connected = true;
                return true;
            }
        }
</code>```

And the associated xaml is:

```<code>        <!-- Row 4 -->
        <Button x:Name="ClearText" Grid.Row="4" Grid.Column="1">Clear Names</Button>
        <Button x:Name="SayHello" Grid.Row="4" Grid.Column="2">Say Hello</Button>
</code>```

The SayHello button is never enabled (even though it seems like it should have the same state as CanClearText). The intent is to use Connected as an intermediary property; in the application I'm putting together, the idea is that Connected is actually set by an external Message (from a model--not connected to a view).

This question gets to it a bit, but I'd like to avoid explicitly calling NotifyOfPropertyChange(() => CanSayHello); and let the Caliburn Micro framework do the work for me. I'm pretty new to this, and I'm sure there's something simple I'm missing--thanks for your help.

答:
Caliburn Micro, in this particular, case might not provide a easy solution. You would have to trigger the NotifyPropertyChanged manually for the dependend properties like CanSayHello each time Connected Property changes. However, you could make use of Fody Extensions which could do the same for you, without explicitly typing the code.

For example,

```<code>[AlsoNotify(nameof(CanSayHello))]
public bool Connected
{
    get { return _connected; }
        set { _connected = value; NotifyOfPropertyChange(() => Connected); }
}
</code>```

This, with the help of Code weaving would do the NotifyPropertyChanged for without having to explicitly do so yourself.

Body:
I'm trying to get Caliburn Micro going in my project and I'm having trouble understanding guard methods (Can*) in the context of properties that aren't bound to the view (forgive me if I'm getting my terminology wrong).

I've adapted Tim Corey's example to add this snippet:

        private bool _connected;

        public bool Connected
        {
            get { return _connected; }
            set { _connected = value; NotifyOfPropertyChange(() => Connected); }
        }

        public bool CanSayHello(bool connected)
        {
            return connected;
        }

        public void SayHello(bool connected)
        {
            Console.WriteLine("Hello!");
        }

        public bool CanClearText(string firstName, string lastName)
        {
            if (String.IsNullOrWhiteSpace(firstName) && string.IsNullOrWhiteSpace(lastName))
            {
                Connected = false;
                return false;
            }
            else
            {
                Connected = true;
                return true;
            }
        }

And the associated xaml is:

        <Button x:Name="ClearText" Grid.Row="4" Grid.Column="1">Clear Names</Button>
        <Button x:Name="SayHello" Grid.Row="4" Grid.Column="2">Say Hello</Button>

The SayHello button is never enabled (even though it seems like it should have the same state as CanClearText). The intent is to use Connected as an intermediary property; in the application I'm putting together, the idea is that Connected is actually set by an external Message (from a model--not connected to a view).

This question gets to it a bit, but I'd like to avoid explicitly calling NotifyOfPropertyChange(() => CanSayHello); and let the Caliburn Micro framework do the work for me. I'm pretty new to this, and I'm sure there's something simple I'm missing--thanks for your help.

Body:
Caliburn Micro, in this particular, case might not provide a easy solution. You would have to trigger the NotifyPropertyChanged manually for the dependend properties like CanSayHello each time Connected Property changes. However, you could make use of Fody Extensions which could do the same for you, without explicitly typing the code.

For example,

[AlsoNotify(nameof(CanSayHello))]
public bool Connected
{
    get { return _connected; }
        set { _connected = value; NotifyOfPropertyChange(() => Connected); }
}

This, with the help of Code weaving would do the NotifyPropertyChanged for without having to explicitly do so yourself.


问:
How can I verify the options present in list of drop down using the Selenium IDE?
How can I verify the options present in list of drop down using the Selenium IDE?

For example A website has a drop down containing the following options:

Regular

Premium

Annual

Monthly

So I want to verify that the drop down contains following options list using Selenium IDE.

答:
Here example of code that shows how I check lists. xpath_to_elements_of_drop_down_list and should be replaced with corresponding xpath.

```<code>execute script | return ['Regular', 'Premium', 'Annual', 'Monthly'] | tabArr
store | 4 | nTabArr
store | 0 | j
store xpath count | xpath=xpath_to_elements_of_drop_down_list | n
assert | ${n} == ${N} | true
echo | Number of elements in the drop down list is correct |
while | ${j} < ${nTabArr} |
execute script | return ${tabArr}[${j}] | tabName
assert element present | xpath=path_to_elements_of_drop_down_list[contains(.,'${tabName}')] |
echo | ${tabName} is present in the drop down list|
execute script | return Number(${j}) + 1 | j
end | |
</code>```

Body:
Here example of code that shows how I check lists. xpath_to_elements_of_drop_down_list and should be replaced with corresponding xpath.

execute script | return ['Regular', 'Premium', 'Annual', 'Monthly'] | tabArr
store | 4 | nTabArr
store | 0 | j
store xpath count | xpath=xpath_to_elements_of_drop_down_list | n
assert | ${n} == ${N} | true
echo | Number of elements in the drop down list is correct |
while | ${j} < ${nTabArr} |
execute script | return ${tabArr}[${j}] | tabName
assert element present | xpath=path_to_elements_of_drop_down_list[contains(.,'${tabName}')] |
echo | ${tabName} is present in the drop down list|
execute script | return Number(${j}) + 1 | j
end | |


问:
'Where' method is not working inside the 'onChange' method
I'm trying to filter data inside a list based on search field input value. I'm running the where method on the list. Since a list has different items on different indexes, therefore I'm running this code in for loop.

Below is an example of the first item in the list;

print(pageData[0].person);

// ###### OUTPUT ######

Person(id: 2, name: james, nickname: , role: guest, phone: , email: , physical_address: s, created: 2020-02-18 09:12:56.000, updated: 2020-02-18 09:12:56.000)
```

<p>Below I'm trying to find matches using the <code>where</code> Method but I'm getting non. </p>

<pre class="lang-dart prettyprint-override"><code>Widget _buildSearchField() {
    return new TextField(
      controller: new TextEditingController(),
      autofocus: true,
      decoration: const InputDecoration(
        hintText: 'Search...',
        border: InputBorder.none,
        hintStyle: const TextStyle(color: Colors.white30),
      ),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (val) {
        var i;
        var results = [];

        for (i = 0; i < pageData.length; i++) {
          print('in pageData for loop');
          var matches = pageData[i].where((data) =>
              (data.person.name.toLowerCase().contains('james') ||
                  data.person.nickname.toLowerCase().contains('james')));

/// Code below is not executing

          if (matches != null) {
            print('matches found');
            results.add(matches);
          }
          if (i == pageData.length) {
            setState(() {
              searchResults = results;
            });
          }
        }
      },
    );
  }
</code>```

How do I fix this? What I'm I doing wrong?

Thank you, posted with Love.

答:
The for loop looks pretty weird to me. Why are you iterating the array like that, and then calling where inside the loop? I had implemented a very similar functionality to what you are trying to achieve in the past, and what I did was something like this:

        final filtered = testUsers
        .where((user) =>
            user.name.toLowerCase().contains(nameOrNick.toLowerCase()) ||
            user.nick.toLowerCase().contains(nameOrNick.toLowerCase()))
        .toList();
```

I have a testUsers List<User> that contains a list of User objects. I use where directly on the list to check if any of the objects have a name or a nick containing the string I am looking for. Then, I create a list from that filtered search, and assign it to a filtered variable.

Should work, I don't see any other issue there other than your loop.

Body:
I'm trying to filter data inside a list based on search field input value. I'm running the where method on the list. Since a list has different items on different indexes, therefore I'm running this code in for loop.

Below is an example of the first item in the list;

print(pageData[0].person);

// ###### OUTPUT ######

Person(id: 2, name: james, nickname: , role: guest, phone: , email: , physical_address: s, created: 2020-02-18 09:12:56.000, updated: 2020-02-18 09:12:56.000)

Below I'm trying to find matches using the where Method but I'm getting non.

Widget _buildSearchField() {
    return new TextField(
      controller: new TextEditingController(),
      autofocus: true,
      decoration: const InputDecoration(
        hintText: 'Search...',
        border: InputBorder.none,
        hintStyle: const TextStyle(color: Colors.white30),
      ),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (val) {
        var i;
        var results = [];

        for (i = 0; i < pageData.length; i++) {
          print('in pageData for loop');
          var matches = pageData[i].where((data) =>
              (data.person.name.toLowerCase().contains('james') ||
                  data.person.nickname.toLowerCase().contains('james')));

/// Code below is not executing

          if (matches != null) {
            print('matches found');
            results.add(matches);
          }
          if (i == pageData.length) {
            setState(() {
              searchResults = results;
            });
          }
        }
      },
    );
  }

How do I fix this? What I'm I doing wrong?

Thank you, posted with Love.

Body:
The for loop looks pretty weird to me. Why are you iterating the array like that, and then calling where inside the loop? I had implemented a very similar functionality to what you are trying to achieve in the past, and what I did was something like this:

        final filtered = testUsers
        .where((user) =>
            user.name.toLowerCase().contains(nameOrNick.toLowerCase()) ||
            user.nick.toLowerCase().contains(nameOrNick.toLowerCase()))
        .toList();

I have a testUsers List<User> that contains a list of User objects. I use where directly on the list to check if any of the objects have a name or a nick containing the string I am looking for. Then, I create a list from that filtered search, and assign it to a filtered variable.

Should work, I don't see any other issue there other than your loop.