问:
Automatically resize image with column width
I would like to automatically resize an image so that it's width is that of a certain column range, say column A to J in Excel.

The image is a banner image that spans the width of the page on a quotation.
I would like it's width to change as the column widths change so the width of the image always coincides with the width of column A to J

答:
Unfortunately, there is no Worksheet_CellSizeChange or any other comparable event avaiable in Excel. However, you could use the Worksheet_SelectionChange event to autofit your picture whenever you select another cell. Just paste the code in the regarding worksheet in Visual Basic Editor:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim myRange As Range
    Set myRange = Me.Columns("A:J")

    Application.EnableEvents = False
    If Not Intersect(Target, myRange) Is Nothing Then
        If Not Me.Pictures(1).Width = myRange.Columns.Width Then
            Me.Pictures(1).Width = myRange.Columns.Width
        End If
    End If
    Application.EnableEvents = True
End Sub
</code>```

Body:
Unfortunately, there is no Worksheet_CellSizeChange or any other comparable event avaiable in Excel. However, you could use the Worksheet_SelectionChange event to autofit your picture whenever you select another cell. Just paste the code in the regarding worksheet in Visual Basic Editor:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim myRange As Range
    Set myRange = Me.Columns("A:J")

    Application.EnableEvents = False
    If Not Intersect(Target, myRange) Is Nothing Then
        If Not Me.Pictures(1).Width = myRange.Columns.Width Then
            Me.Pictures(1).Width = myRange.Columns.Width
        End If
    End If
    Application.EnableEvents = True
End Sub


来源: stackexchange

问:
Include a JS variable inside "<%: %>"
I want to include the variable "count" inside the '<%:Givenome[count]%>' code.

HTML code

```<code><table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
</table>
<br>

<button type="button" onclick="myFunction()">Try it</button>
<script>
    function myFunction() {
        var count;
        for (count = 0; count < <%=Givenome.Count()%>; count++)
        {
            var table = document.getElementById("myTable");
            var row = table.insertRow(0);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = "<%:Givenome[count]%>";
            cell2.innerHTML = "NEW CELL2";
        }
    }
</script>
</code>```

This is my C# Code, where I create my string array.

```<code>public string[] Givenome { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    string[] answers = new string[10] { "Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y" };

    Givenome = answers;
}
</code>```

答:
I think what you want is something like this:</p>

```<code>var table = document.getElementById('myTable');
<%
for (var i = 0; i < Givenome.Length; i++)
{
    Response.Write("{");
    Response.Write("var row = table.insertRow(0);");
    Response.Write("var cell1 = row.insertCell(0);");
    Response.Write("var cell2 = row.insertCell(1);");
    Response.Write("cell1.innerHTML = '" + Givenome[i] + "';");
    Response.Write("cell2.innerHTML = 'NEW CELL2';");
    Response.Write("}");
}
%>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Include a JS variable inside "<%: %>"

Body:
I want to include the variable "count" inside the '<%:Givenome[count]%>' code.

HTML code

    Row1 cell1
    Row1 cell2

<button type="button" onclick="myFunction()">Try it</button>

This is my C# Code, where I create my string array.

public string[] Givenome { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    string[] answers = new string[10] { "Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y" };

    Givenome = answers;
}

Body:
I think what you want is something like this:

var table = document.getElementById('myTable');
<%
for (var i = 0; i < Givenome.Length; i++)
{
    Response.Write("{");
    Response.Write("var row = table.insertRow(0);");
    Response.Write("var cell1 = row.insertCell(0);");
    Response.Write("var cell2 = row.insertCell(1);");
    Response.Write("cell1.innerHTML = '" + Givenome[i] + "';");
    Response.Write("cell2.innerHTML = 'NEW CELL2';");
    Response.Write("}");
}
%>


问:
Regex - Find first word without a specific string
I want to analyse line of string. There are some bytes as hex code. To this i want to get the first word after these without the characters "0x".
The word after can contain a "x" but not as 0x.
e.g.: TimeStamp[ID] -> 0x12 0x34 0x56 0x7 0x88 0x98 0x76 0x5 Word_I_Searched_without

I have proofed:

Regex excluding specific characters

Regex: Match word not containing

Regular expression to match a word without a character

答:
At least i changed my code. The result is that i used following regex with your input:

(?<=-> )(.*?)(\b(?!0x)(?!\s+)+.*)

Thanks for your help.


问:
Find which element of list is a key in a dictionary and what is it's value
I have a dictionary:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
</code>```

and a list:

```<code>labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']
</code>```

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

```<code>class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])
</code>```

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

答:
If labels_list is a set instead, you might be able to squeeze out some performance. Use intersection of set and dictionary keys:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
labels_list= set(['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk'])

[classes_dictionary[k] for k in labels_list & classes_dictionary.keys()]
</code>```

Body:
I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

Body:
If labels_list is a set instead, you might be able to squeeze out some performance. Use intersection of set and dictionary keys:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
labels_list= set(['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk'])

[classes_dictionary[k] for k in labels_list & classes_dictionary.keys()]


问:
Minimum android tablet size information needed
I want to develop application with single binary for Android device and for Android tablets with target android 2.1 version.

My orientation also depends upon whether app is running on device or on tablet.

So i just want to know, is there any specification like tablet should be minimum of "X" inches.

答: There is heaps of information on screen sizes and each device can be different so you should use the Android standards talked about here to figure out exactly what screen you are dealing with and react accordingly. There are no hard and fast "atleast X inches" rules; just different screen sizes of different resolutions. You can use the Android manifest to restrict the screen sizes to just the ones that you want to support.</p>

ContentLicense: CC BY-SA 3.0


问:
Unable to run Jersey 2 Restful web service on Tomcat 9
I am writing a Jersey 2 Restful web service.
Here is the service class:

package com.Test.PS;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;

import com.Test.Exchange.*; // Here class UserInfo is defined

@Path("/ps")
public class TestService {
    private UserInfo ui;
    public TestService () throws IOException {
        ui = new UserInfo();
    }
    public TestService (String uid) throws IOException {
        UserInfo ui = ObjectFileStore.serializeDataIn(uid);
    }

    public TestService (UserInfo ui) throws IOException {
        this.ui = ui;
        ObjectFileStore.serializeDataOut(ui);
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHelloHTML(@QueryParam("uid") String uid) {
        String resource="
 Hi '" + uid + "'.
";
        return resource;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public UserInfo postNK(@QueryParam("asid") String asid, UserInfo u) {
        return ui;
    }
}
```

<p>Here is the maven dependencies:</p>

<pre class="lang-xml prettyprint-override"><code><dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-server</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.inject</groupId>
  <artifactId>jersey-hk2</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>
</code>```

Finaly, this is my web.xml file:

  <display-name>Test-PS</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Test-PS</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.Test.PS</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test-PS</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>
```

<p>I am getting the following error when running this service on Tomcat 9 using url (http://localhost:8081/Test-PS/rest/ps?uid=90):</p>

```HTTP Status 404 – Not Found
Type Status Report
Message /Test-PS/rest/ps
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
```

<p>On the console screen, I see:</p>

```INFO: Reloading Context with name [/Test-PS] has started
org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/Test-PS] is completed
```

I tried adding several other dependencies as suggested by other posts here, however, still having the same issue. Surprisengly, sometimes it works for unknown reason!!!

I have also deleted all of the maven repositories, nothing has been changed!!!

答:
Use jersey-container-servlet-core instead of jersey-container-servlet

Refer:

Jersey dependecies - https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/modules-and-dependencies.html

Tomcat versions compare - http://tomcat.apache.org/whichversion.html

Body:
I am writing a Jersey 2 Restful web service.
Here is the service class:

package com.Test.PS;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;

import com.Test.Exchange.*; // Here class UserInfo is defined

@Path("/ps")
public class TestService {
    private UserInfo ui;
    public TestService () throws IOException {
        ui = new UserInfo();
    }
    public TestService (String uid) throws IOException {
        UserInfo ui = ObjectFileStore.serializeDataIn(uid);
    }

    public TestService (UserInfo ui) throws IOException {
        this.ui = ui;
        ObjectFileStore.serializeDataOut(ui);
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHelloHTML(@QueryParam("uid") String uid) {
        String resource="
 Hi '" + uid + "'.
";
        return resource;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public UserInfo postNK(@QueryParam("asid") String asid, UserInfo u) {
        return ui;
    }
}

Here is the maven dependencies:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-server</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.inject</groupId>
  <artifactId>jersey-hk2</artifactId>
  <version>2.27</version>
  <scope>provided</scope>
</dependency>

Finaly, this is my web.xml file:

  <display-name>Test-PS</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Test-PS</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.Test.PS</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test-PS</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

I am getting the following error when running this service on Tomcat 9 using url (http://localhost:8081/Test-PS/rest/ps?uid=90):

HTTP Status 404 – Not Found
Type Status Report
Message /Test-PS/rest/ps
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

On the console screen, I see:

INFO: Reloading Context with name [/Test-PS] has started
org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/Test-PS] is completed

I tried adding several other dependencies as suggested by other posts here, however, still having the same issue. Surprisengly, sometimes it works for unknown reason!!!

I have also deleted all of the maven repositories, nothing has been changed!!!


问:
replace all odd values in vector with coresponing value from new vector
Given following vectors:

```<code>std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
</code>```

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

```<code>// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
</code>```

答:
std::replace_if only supports replacing elements with the constant value specified as last argument. However, if you feel that it makes any sense for you, you can write your own replace_if function based on the reference implementation and make it accept some kind of generator as a last parameter. For example:

```<code>template<class ForwardIt, class UnaryPredicate, class Generator>
void my_replace_if(ForwardIt first, ForwardIt last,
                UnaryPredicate p, Generator g)
{
    for (; first != last; ++first) {
        if(p(*first)) {
            *first = g();
        }
    }
}

bool IsOdd (int i) { return ((i%2)==1); }

int main(int argc, const char * argv[]) {
    std::vector<int> foo{1,2,3,4,5,6,7};
    std::vector<int> bar{10,20,30,40,50,60,70};
    int i = 0;
    my_replace_if (foo.begin(), foo.end(), IsOdd, [&bar, &i]()
        {
            return bar[i++];
        });
    for (auto el : foo)
    {
        std::cout << el << std::endl;
    }
    return 0;
}
</code>```

===== EDIT =====

As pointed out by anastaciu, index for generator should be incremented with each step, not only when  generator is invoked.

e.g.:

```<code>    my_replace_if (foo.begin(), foo.end(),
        [&i](int v) { i++; return ((v%2)==1); },
        [&bar, &i]() { return bar[i-1]; });
</code>```

But to be honest, it really is overkill in this case and it doesn't even look nice.

Body:
Given following vectors:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70

Body:
std::replace_if only supports replacing elements with the constant value specified as last argument. However, if you feel that it makes any sense for you, you can write your own replace_if function based on the reference implementation and make it accept some kind of generator as a last parameter. For example:

template<class ForwardIt, class UnaryPredicate, class Generator>
void my_replace_if(ForwardIt first, ForwardIt last,
                UnaryPredicate p, Generator g)
{
    for (; first != last; ++first) {
        if(p(*first)) {
            *first = g();
        }
    }
}

bool IsOdd (int i) { return ((i%2)==1); }

int main(int argc, const char * argv[]) {
    std::vector<int> foo{1,2,3,4,5,6,7};
    std::vector<int> bar{10,20,30,40,50,60,70};
    int i = 0;
    my_replace_if (foo.begin(), foo.end(), IsOdd, [&bar, &i]()
        {
            return bar[i++];
        });
    for (auto el : foo)
    {
        std::cout << el << std::endl;
    }
    return 0;
}

===== EDIT =====

As pointed out by anastaciu, index for generator should be incremented with each step, not only when  generator is invoked.

e.g.:

    my_replace_if (foo.begin(), foo.end(),
        [&i](int v) { i++; return ((v%2)==1); },
        [&bar, &i]() { return bar[i-1]; });

But to be honest, it really is overkill in this case and it doesn't even look nice.


问:
Check if student is in right class and only show students that goes in the class that is pressed
I have an assignnment where there is laid out a html script that shows radio buttons, saying the name of each class, and a json file that lists all the students names and which class they go too.

I wondered is there a way to use addEventListener to do this? Because that's what I have heard is the right solution, and I have to do what the professor says.

I am not allowed to change the HTML code.

```<code>fetch("studenter.json")
  .then((response) => {
    return response.json();
})
  .then(function appendData(data) {
  var unordered = document.querySelector(".studenter");
  for (var i = 0; i < data.length; i++) {
    var li = document.createElement("li");
    li.innerHTML = 'Name: ' + data[i].fornavn + ' ' + data[i].etternavn;
    unordered.appendChild(li);
  }
});

</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Studenter i IIKG1002 og IDG1011</title>

  <link rel="stylesheet" href="css/studenterIKlasse.css" />

Studenter i IIKG1002 og IDG1011

Velg klasse

      <input type="radio" name="programvelger" id="BIGEOMAT" />
      Bachelor in Engineering, Geomatics

      <input type="radio" name="programvelger" id="BWU" />
      Bachelor in Web Development

      <input type="radio" name="programvelger" id="ÅRWEB" />
      Web Design - One-year programme

      <input type="radio" name="programvelger" id="BIXD" />
      Interaction Design - Bachelor's Programme

      <input type="radio" name="programvelger" id="all" />
      Show all

```

<p>Here's an example of the json I want to display:</p>

```  {
    "fornavn": "Marcus Gimse",
    "etternavn": "Blikstad",
    "studieprogram": "Bachelor in Engineering, Geomatics",
    "forkortelse": "BIGEOMAT"
  },
```

答:
Sure

You were almost there

NOTE: I renamed data to students

// fetch here and keep the data - uncomment the next 4 lines when ready
// let students = [];
// fetch("studenter.json")
//  .then(response => response.json())
//  .then(data => students = data);

// example data. Remove when doing fetch
const students = [{ "fornavn": "Marcus Gimse", "etternavn": "Blikstad", "studieprogram": "Bachelor in Engineering, Geomatics", "forkortelse": "BIGEOMAT"}];

// using delegation - i.e. a click on anything in klasseVelger will give the target in event.target
document.querySelector(".klasseVelger").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.type && tgt.type === "radio") {
    const id = tgt.id;
    console.log(id); // can be removed
    var unordered = document.querySelector(".studenter");
    unordered.innerHTML = ""; // reset
    for (var i = 0; i < students.length; i++) {
      if (id === "all" || id === students[i].forkortelse) {
        var li = document.createElement("li");
        li.innerHTML = 'Name: ' + students[i].fornavn + ' ' + students[i].etternavn;
        unordered.appendChild(li);
      }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Studenter i IIKG1002 og IDG1011</h1>
<p>Velg klasse</p>
<div class="klasseVelger">
  <div>
    <input type="radio" name="programvelger" id="BIGEOMAT" />
    <label for="BIGEOMAT">Bachelor in Engineering, Geomatics</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="BWU" />
    <label for="BWU">Bachelor in Web Development</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="ÅRWEB" />
    <label for="ÅRWEB">Web Design - One-year programme</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="BIXD" />
    <label for="BIXD">Interaction Design - Bachelor's Programme</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="all" />
    <label for="all">Show all</label>
  </div>
</div>
<p>
  <ul class="studenter"></ul>
</p></code>```

Body:
I have an assignnment where there is laid out a html script that shows radio buttons, saying the name of each class, and a json file that lists all the students names and which class they go too.

I wondered is there a way to use addEventListener to do this? Because that's what I have heard is the right solution, and I have to do what the professor says.

I am not allowed to change the HTML code.

fetch("studenter.json")
  .then((response) => {
    return response.json();
})
  .then(function appendData(data) {
  var unordered = document.querySelector(".studenter");
  for (var i = 0; i < data.length; i++) {
    var li = document.createElement("li");
    li.innerHTML = 'Name: ' + data[i].fornavn + ' ' + data[i].etternavn;
    unordered.appendChild(li);
  }
});

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Studenter i IIKG1002 og IDG1011</title>

  <link rel="stylesheet" href="css/studenterIKlasse.css" />

Studenter i IIKG1002 og IDG1011

Velg klasse

      <input type="radio" name="programvelger" id="BIGEOMAT" />
      Bachelor in Engineering, Geomatics

      <input type="radio" name="programvelger" id="BWU" />
      Bachelor in Web Development

      <input type="radio" name="programvelger" id="ÅRWEB" />
      Web Design - One-year programme

      <input type="radio" name="programvelger" id="BIXD" />
      Interaction Design - Bachelor's Programme

      <input type="radio" name="programvelger" id="all" />
      Show all

Here's an example of the json I want to display:

  {
    "fornavn": "Marcus Gimse",
    "etternavn": "Blikstad",
    "studieprogram": "Bachelor in Engineering, Geomatics",
    "forkortelse": "BIGEOMAT"
  },

Body:
Sure

You were almost there

NOTE: I renamed data to students

// fetch here and keep the data - uncomment the next 4 lines when ready
// let students = [];
// fetch("studenter.json")
//  .then(response => response.json())
//  .then(data => students = data);

// example data. Remove when doing fetch
const students = [{ "fornavn": "Marcus Gimse", "etternavn": "Blikstad", "studieprogram": "Bachelor in Engineering, Geomatics", "forkortelse": "BIGEOMAT"}];

// using delegation - i.e. a click on anything in klasseVelger will give the target in event.target
document.querySelector(".klasseVelger").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.type && tgt.type === "radio") {
    const id = tgt.id;
    console.log(id); // can be removed
    var unordered = document.querySelector(".studenter");
    unordered.innerHTML = ""; // reset
    for (var i = 0; i < students.length; i++) {
      if (id === "all" || id === students[i].forkortelse) {
        var li = document.createElement("li");
        li.innerHTML = 'Name: ' + students[i].fornavn + ' ' + students[i].etternavn;
        unordered.appendChild(li);
      }
    }
  }
})

<h1>Studenter i IIKG1002 og IDG1011</h1>
<p>Velg klasse</p>
<div class="klasseVelger">
  <div>
    <input type="radio" name="programvelger" id="BIGEOMAT" />
    <label for="BIGEOMAT">Bachelor in Engineering, Geomatics</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="BWU" />
    <label for="BWU">Bachelor in Web Development</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="ÅRWEB" />
    <label for="ÅRWEB">Web Design - One-year programme</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="BIXD" />
    <label for="BIXD">Interaction Design - Bachelor's Programme</label>
  </div>
  <div>
    <input type="radio" name="programvelger" id="all" />
    <label for="all">Show all</label>
  </div>
</div>
<p>
  <ul class="studenter"></ul>
</p>


问:
Development/runtime Licensing mechanism for a C# class library?
I'm developing a .Net class library (a data provider) and I'm starting to think about how I would handle licensing the library to prospective purchasers.  By licensing, I mean the mechanics of trying to prevent my library from being used by those who haven't purchased it, not the software license (i.e., Apache, Gnu, etc).

I've never dealt with licensing, and in the past, I've always developed apps, not libraries.  I don't want to make things difficult for my customers; know it is not possible to make it ironclad.  Just some mechanism that gives me decent protection without making the customer jump through hoops or gnash their teeth.

I think the mechanism would check for a valid license when the class is being used in development mode, and not in runtime mode (when the customer's software is released to their customers).  I think libraries are typically sold per developer, but I'm not sure how that could be accomplished without making the mechanism odious for my customers; maybe that gets left to the honor system.

I Googled this and found many approaches.  Ideally, I'd like to do something that is generally accepted and common, the "right" way class libraries are licensed, if that exists, rather than making my customers deal with yet another license mechanism. A firm push in the right direction will be greatly appreciated!

答: When your client instantiates your class library, you would in your constructor code check for licensing. If the vendor does not have a valid/missing license, then you can throw a licensing exception. This would prevent someone from using your class/library. You should only do this once such that if the licensing is valid in one class, all your other classes would skip the licensing check.</p>

ContentLicense: CC BY-SA 2.5


问:
Fetch data from Json array in rows and columns
I have this query to append the arrary in JSON:

```<code>DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

SELECT TheJSON FROM @TheTable
</code>```

It gives me the output in 1 single Row:

```<code>[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]
</code>```

Till this part it is correct.

Now I want to fetch the data from this table in rows and columns wise like a regular table:

```<code>ID  Name
1   One
2   Two
3   Three
</code>```

How to fetch the data from Json in rows and columns wise?

Any help would be appreciated

答:
```<code>DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

Declare @temp nvarchar(max)

select @temp= TheJSON   FROM @TheTable

select id,name   FROM OPENJSON(@temp)
 WITH (
 id  NVARCHAR(100)  ,
 name   NVARCHAR(100)

 )
</code>```

Hi you can try this. This is giving what you want . Thank you.

Body:
I have this query to append the arrary in JSON:

DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

SELECT TheJSON FROM @TheTable

It gives me the output in 1 single Row:

[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]

Till this part it is correct.

Now I want to fetch the data from this table in rows and columns wise like a regular table:

ID  Name
1   One
2   Two
3   Three

How to fetch the data from Json in rows and columns wise?

Any help would be appreciated

Body:
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

Declare @temp nvarchar(max)

select @temp= TheJSON   FROM @TheTable

select id,name   FROM OPENJSON(@temp)
 WITH (
 id  NVARCHAR(100)  ,
 name   NVARCHAR(100)

 )

Hi you can try this. This is giving what you want . Thank you.


问:
How can I use Jsoup for multithreading
I am trying to Download information from URl as text using Jsoup and then count the frequency of each unique word I want to implement using multi threading.I am using text file which has a url on each
newline.I am getting output if I give only one url but when I give more urls I get error.

```<code>
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.*;

import org.jsoup.*;
public class JavaGetUrl {
public void downloadweb(String url) throws IOException  {
    //System.out.println(url);
    Document doc=Jsoup.connect(url).get();
    //System.out.println(doc.text());
    wordCounter(doc.text());

    }
public static void wordCounter(String s)
{

        String a[] = s.split(" ");
        Map<String, Integer> words = new HashMap<>();
        for (String str : a) {
            if (words.containsKey(str)) {
                words.put(str, 1 + words.get(str));
            } else {
                words.put(str, 1);
            }
        }
        System.out.println(words);
    }

   public static void main (String[] args) throws IOException {
       Mythread mt=new Mythread();
        Thread t=new Thread(mt);
        t.start();
}
}
class Mythread extends JavaGetUrl  implements Runnable
{

    public void run()
    {
        try
        {

        File file=new File("Demo.txt");    //creates a new file instance
        FileReader fr=new FileReader(file);   //reads the file
        BufferedReader br=new BufferedReader(fr);  //creates a buffering character input stream
            //constructs a string buffer with no characters
        String line;
        StringBuffer sb=new StringBuffer();

        while((line=br.readLine())!=null)
        {
        sb.append(line);      //appends line to string buffer
        sb.append("\n");     //line feed
        }
        fr.close();    //closes the stream and release the resources
        System.out.println("Contents of File: ");
        System.out.println(sb.toString());
        JavaGetUrl jg=new JavaGetUrl();
        jg.downloadweb(sb.toString());

        //System.out.println(sb.toString());

        }
        catch(IOException e)
        {
        e.printStackTrace();
        }
    }
}
</code>```

I am getting these errors
Is there some way to implement multithreading using Jsoup

答:
Your links contain \n symbol, so they are incorrect.

I think you could use just list of Strings, like this:

```<code>List<String> urls = new ArrayList<>();
while((line=br.readLine())!=null)
    {
        urls.add(line);      // adds line to the List of Strings
    }
</code>```

And please, pay attention to code formatting.

Title: How can I use Jsoup for multithreading

Body:
I am trying to Download information from URl as text using Jsoup and then count the frequency of each unique word I want to implement using multi threading.I am using text file which has a url on each
newline.I am getting output if I give only one url but when I give more urls I get error.

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.*;

import org.jsoup.*;
public class JavaGetUrl {
public void downloadweb(String url) throws IOException  {
    //System.out.println(url);
    Document doc=Jsoup.connect(url).get();
    //System.out.println(doc.text());
    wordCounter(doc.text());

    }
public static void wordCounter(String s)
{

        String a[] = s.split(" ");
        Map<String, Integer> words = new HashMap<>();
        for (String str : a) {
            if (words.containsKey(str)) {
                words.put(str, 1 + words.get(str));
            } else {
                words.put(str, 1);
            }
        }
        System.out.println(words);
    }

   public static void main (String[] args) throws IOException {
       Mythread mt=new Mythread();
        Thread t=new Thread(mt);
        t.start();
}
}
class Mythread extends JavaGetUrl  implements Runnable
{

    public void run()
    {
        try
        {

        File file=new File("Demo.txt");    //creates a new file instance
        FileReader fr=new FileReader(file);   //reads the file
        BufferedReader br=new BufferedReader(fr);  //creates a buffering character input stream
            //constructs a string buffer with no characters
        String line;
        StringBuffer sb=new StringBuffer();

        while((line=br.readLine())!=null)
        {
        sb.append(line);      //appends line to string buffer
        sb.append("\n");     //line feed
        }
        fr.close();    //closes the stream and release the resources
        System.out.println("Contents of File: ");
        System.out.println(sb.toString());
        JavaGetUrl jg=new JavaGetUrl();
        jg.downloadweb(sb.toString());

        //System.out.println(sb.toString());

        }
        catch(IOException e)
        {
        e.printStackTrace();
        }
    }
}

I am getting these errors
Is there some way to implement multithreading using Jsoup

Body:
Your links contain \n symbol, so they are incorrect.

I think you could use just list of Strings, like this:

List<String> urls = new ArrayList<>();
while((line=br.readLine())!=null)
    {
        urls.add(line);      // adds line to the List of Strings
    }

And please, pay attention to code formatting.


答:
You can use get() and check if the returned value is not None instead of looking if the key exists in the dict (although it's O(1) operation). If you know it's only one value add break

```<code>class_str = []
for k in labels_list:
    value = classes_dictionary.get(k)
    if value:
        class_str.append(value)
</code>```

If you are using Python 3.8 you can use Assignment Expressions, which will evaluate classes_dictionary.get(x) only once

```<code>class_str = [y for x in labels_list if (y := classes_dictionary.get(x)) is not None]
</code>```

Title: Find which element of list is a key in a dictionary and what is it's value

Body:
You can use get() and check if the returned value is not None instead of looking if the key exists in the dict (although it's O(1) operation). If you know it's only one value add break

class_str = []
for k in labels_list:
    value = classes_dictionary.get(k)
    if value:
        class_str.append(value)

If you are using Python 3.8 you can use Assignment Expressions, which will evaluate classes_dictionary.get(x) only once

class_str = [y for x in labels_list if (y := classes_dictionary.get(x)) is not None]


问:
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter when using DiffUtil
Below is an adapter class for loading all book items in recycler view. Used DiffUtils so that the whole list doesn't get notified.

```<code>
class BooksAdapter(var mContext: Context) : RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() {

    var books: List<BookTable> = ArrayList()
        set(value) {
            val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))
            field = value
            result.dispatchUpdatesTo(this)
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BooksViewHolder {
        val binding = DataBindingUtil.inflate<ItemBookBinding>(LayoutInflater.from(mContext), R.layout.item_book, parent, false)
        return BooksViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return books.size
    }

    override fun onBindViewHolder(holder: BooksViewHolder, position: Int) {
        holder.setData(books[position])
    }

    inner class BooksViewHolder(var binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) {
        fun setData(bookTable: BookTable) {
            binding.book = bookTable
        }
    }
}

</code>```

My DiffUtil class is as below. I have extended DiffUtil class and checked if items are same or not , if not then DiffUtil will handle updatin

```<code>class BookListDiffCallBacks(var oldBooks: ArrayList<BookTable>, var newBooks: ArrayList<BookTable>) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition].bookId == newBooks[newItemPosition].bookId
    }

    override fun getOldListSize(): Int {
        return oldBooks.size
    }

    override fun getNewListSize(): Int {
        return newBooks.size
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition] == newBooks[newItemPosition]// == means structural equality checks in kotlin
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}
</code>```

Model class

```<code>

@Entity(
    tableName = "book_table"//,
//    foreignKeys = [ForeignKey(entity = CategoryTable::class, parentColumns = arrayOf("categoryId"), childColumns = arrayOf("categoryId"), onDelete = ForeignKey.CASCADE)]
)
class BookTable : BaseObservable() {

    @Bindable
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "bookId")
    var bookId: Int = 0
        set(value) {
            field = value
            notifyPropertyChanged(BR.bookId)
        }

    @Bindable
    var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }

    @Bindable
    var categoryId: Int? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.categoryId)
        }

    override fun equals(other: Any?): Boolean {

        if (other === this) return true // means same reference
        if (other !is BookTable) return false// is not of same class

        // other is now Booktable instance as above condition false if you remove that condition then it will show error in below condition
        // as it has passed above condition means it is of type BookTable
        return (bookId == other.bookId
                && categoryId == other.categoryId
                && name == other.name)

    }

    override fun hashCode(): Int {
        var result = bookId
        result = 31 * result + (name?.hashCode() ?: 0)
        result = 31 * result + (categoryId ?: 0)
        return result
    }

}

</code>```

My app gets crash and I am getting this error:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionBooksViewHolder

I have implemented DiffUtil class so that whole recycleview view items don't get notified.

Reference: https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil

答:
Sometimes that error can still persist if so I have found a workaround. Thanks, @Ryan for valuable effort. Actually your solution solved my problem, below given is the prevention.</p>

```<code>class WrapContentLinearLayoutManager : LinearLayoutManager {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {}

    override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State) {
        try {
            super.onLayoutChildren(recycler, state)
        } catch (e: IndexOutOfBoundsException) {
            Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens")
        }
    }
}
</code>```

Body:
Below is an adapter class for loading all book items in recycler view. Used DiffUtils so that the whole list doesn't get notified.

class BooksAdapter(var mContext: Context) : RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() {

    var books: List<BookTable> = ArrayList()
        set(value) {
            val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))
            field = value
            result.dispatchUpdatesTo(this)
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BooksViewHolder {
        val binding = DataBindingUtil.inflate<ItemBookBinding>(LayoutInflater.from(mContext), R.layout.item_book, parent, false)
        return BooksViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return books.size
    }

    override fun onBindViewHolder(holder: BooksViewHolder, position: Int) {
        holder.setData(books[position])
    }

    inner class BooksViewHolder(var binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) {
        fun setData(bookTable: BookTable) {
            binding.book = bookTable
        }
    }
}

My DiffUtil class is as below. I have extended DiffUtil class and checked if items are same or not , if not then DiffUtil will handle updatin

class BookListDiffCallBacks(var oldBooks: ArrayList<BookTable>, var newBooks: ArrayList<BookTable>) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition].bookId == newBooks[newItemPosition].bookId
    }

    override fun getOldListSize(): Int {
        return oldBooks.size
    }

    override fun getNewListSize(): Int {
        return newBooks.size
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition] == newBooks[newItemPosition]// == means structural equality checks in kotlin
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}

Model class

@Entity(
    tableName = "book_table"//,
//    foreignKeys = [ForeignKey(entity = CategoryTable::class, parentColumns = arrayOf("categoryId"), childColumns = arrayOf("categoryId"), onDelete = ForeignKey.CASCADE)]
)
class BookTable : BaseObservable() {

    @Bindable
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "bookId")
    var bookId: Int = 0
        set(value) {
            field = value
            notifyPropertyChanged(BR.bookId)
        }

    @Bindable
    var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }

    @Bindable
    var categoryId: Int? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.categoryId)
        }

    override fun equals(other: Any?): Boolean {

        if (other === this) return true // means same reference
        if (other !is BookTable) return false// is not of same class

        // other is now Booktable instance as above condition false if you remove that condition then it will show error in below condition
        // as it has passed above condition means it is of type BookTable
        return (bookId == other.bookId
                && categoryId == other.categoryId
                && name == other.name)

    }

    override fun hashCode(): Int {
        var result = bookId
        result = 31 * result + (name?.hashCode() ?: 0)
        result = 31 * result + (categoryId ?: 0)
        return result
    }

}

My app gets crash and I am getting this error:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionBooksViewHolder

I have implemented DiffUtil class so that whole recycleview view items don't get notified.

Reference: https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil

Body:
Sometimes that error can still persist if so I have found a workaround. Thanks, @Ryan for valuable effort. Actually your solution solved my problem, below given is the prevention.

class WrapContentLinearLayoutManager : LinearLayoutManager {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {}

    override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State) {
        try {
            super.onLayoutChildren(recycler, state)
        } catch (e: IndexOutOfBoundsException) {
            Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens")
        }
    }
}


问:
How to make Gradle run tasks in certain order?
Let's say that I have created separate tasks for running integration and acceptance tests in my gradle build script. When I run the build task I want to run testing tasks before in this order: unit tests(test task), integration tests (intergationTest task) and acceptance tests (acceptanceTest task). Is this possible and how?</p>

答:
The first answer in the list turned out to be great for me. I used

X.shouldRunAfter Y


答:
Use rank() or row_number():

```<code>select x.*
from (select x.*,
             row_number() over (partition by category_id order by rating desc) as seqnum
      from tableX x
     ) x
where seqnum = 1;
</code>```

For ties, use rank() (that is all rows with the highest  rating).

That above works in MySQL 8+.  In earlier versions, you can use a correlated subquery.  Something like:

```<code>select x.*
from tableX x
where x.rating = (select max(x2.rating)
                  from tableX x2
                  where x2.category_id = x.category_id
                 );
</code>```

If you want only one row using the second form, then:

```<code>select x.*
from tableX x
where x.id = (select x2.id
              from tableX x2
              where x2.category_id = x.category_id
              order by x2.rating desc
              limit 1
             );
</code>```

Title: SQL: foreach query result - run query

Body:
I have a tableX with items and each item has a category_id and rating.
I want to take the item with the highest rating form each category.

I imagine i have to do something like

SELECT DISTINCT category_id from tableX;

Then run a foreach those results with another query like

SELECT * from tableX where category_id = ${1} ORDER BY rating, LIMIT 1;

OR something like

call foreach('SELECT distinct category_id FROM tableX', 'SELECT * from tableX WHERE category_id = ${1} ORDER BY rating DESC LIMIT 1')

Edit:

I added some rows examples

CREATE TABLE `tableX` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `rating` double(6,1) DEFAULT '0.0',
  `category_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Dumping data for table tableX

INSERT INTO `tableX` (`id`, `rating`, `category_id`) VALUES
(1463, 8.0, 1),
(1464, 8.0, 1),
(1465, 8.0, 1),
(1466, 9.0, 1),
(1467, 9.0, 1),
(1468, 3.0, 1),
(1469, 8.0, 1),
(1470, 2.0, 1),
(1471, 4.0, 1),
(1472, 9.0, 1),
(1473, 5.0, 1),
(1474, 9.0, 1),
(1475, 10.0, 1),
(1476, 7.0, 1),
(1477, 7.0, 1),
(1478, 6.0, 1),
(1479, 10.0, 1),
(1480, 3.0, 1),
(1481, 7.0, 1),
(1482, 4.0, 1),
(1483, 7.0, 1),
(1484, 4.0, 1),
(1485, 2.0, 1),
(1486, 4.0, 1),
(1487, 5.0, 1),
(1488, 9.0, 1),
(1489, 8.0, 1),
(1490, 7.0, 1),
(1491, 10.0, 1),
(1492, 9.0, 1),
(1493, 9.0, 1),
(1494, 9.0, 2),
(1495, 3.0, 2),
(1496, 9.0, 2),
(1497, 9.0, 2),
(1498, 2.0, 2),
(1499, 4.0, 2),
(1500, 5.0, 2),
(1501, 7.0, 2),
(1502, 5.0, 2),
(1503, 7.0, 2),
(1504, 10.0, 2),
(1505, 6.0, 2),
(1506, 6.0, 4),
(1507, 1.0, 4),
(1508, 5.0, 4),
(1509, 7.0, 5),
(1510, 4.0, 5);

Indexes for dumped tables

ALTER TABLE `tableX`
  ADD PRIMARY KEY (`id`),
  ADD KEY `category_id` (`category_id`);

Body:
Use rank() or row_number():

select x.*
from (select x.*,
             row_number() over (partition by category_id order by rating desc) as seqnum
      from tableX x
     ) x
where seqnum = 1;

For ties, use rank() (that is all rows with the highest  rating).

That above works in MySQL 8+.  In earlier versions, you can use a correlated subquery.  Something like:

select x.*
from tableX x
where x.rating = (select max(x2.rating)
                  from tableX x2
                  where x2.category_id = x.category_id
                 );

If you want only one row using the second form, then:

select x.*
from tableX x
where x.id = (select x2.id
              from tableX x2
              where x2.category_id = x.category_id
              order by x2.rating desc
              limit 1
             );


问:
Place the three columns with the same height
Using the bootstrap I created three columns. Within each column I have several rows.

My problem is that the columns are not the same height, the left column is bigger than the rest, they were supposed to all be the same height.

In the cards I did not define any height, that is, if any of the columns increased the height, the rest would follow this growth automatically in order to have all the same height.

Is there a way to place all the columns at the same height without using measurements in pixels (px)?

Thanks

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

```

答:
Done with js, just copied from the duplicate linked post. Shows weird on a small screen though.

// Get cards
var cards = $('.card');
var maxHeight = 0;

// Loop all cards and check height, if bigger than max then save it
for (var i = 0; i < cards.length; i++) {
  if (maxHeight < $(cards[i]).outerHeight()) {
    maxHeight = $(cards[i]).outerHeight();
  }
}
// Set ALL card bodies to this height
for (var i = 0; i < cards.length; i++) {
  $(cards[i]).height(maxHeight);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mycontainer {
    width: 96%;
    margin-top: 148px;
    margin-right: auto;
    margin-left: auto;
}

.card{
    width:100%;
    margin-top:15px;
    background: #FFFFFF 0% 0% no-repeat padding-box;
    box-shadow: 0px 3px 20px #BCBCCB47;
    border-radius: 8px;
    border: none;
}</code>```

```

Body:
Done with js, just copied from the duplicate linked post. Shows weird on a small screen though.

// Get cards
var cards = $('.card');
var maxHeight = 0;

// Loop all cards and check height, if bigger than max then save it
for (var i = 0; i < cards.length; i++) {
  if (maxHeight < $(cards[i]).outerHeight()) {
    maxHeight = $(cards[i]).outerHeight();
  }
}
// Set ALL card bodies to this height
for (var i = 0; i < cards.length; i++) {
  $(cards[i]).height(maxHeight);
}

.mycontainer {
    width: 96%;
    margin-top: 148px;
    margin-right: auto;
    margin-left: auto;
}

.card{
    width:100%;
    margin-top:15px;
    background: #FFFFFF 0% 0% no-repeat padding-box;
    box-shadow: 0px 3px 20px #BCBCCB47;
    border-radius: 8px;
    border: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 100%;height: 100%; overflow-y: auto; overflow-x: hidden;">
    <div class="row mycontainer">
      <div class="col">
        <div class="row">
          <div class="card">
            <div class="card-body" style="padding: 8px;">

            </div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="row">
              <div class="card">
                <div class="card-body">

                </div>
              </div>
            </div>
            <div class="row">
              <div class="card">
                <div class="card-body">

                </div>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row h-100">
              <div class="card" style="margin-left:15px">
                <div class="card-body">

                </div>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row h-100">
              <div class="card" style="margin-left:15px">
                <div class="card-body">

                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="row">
          <div class="col">
            <div class="row h-100">
              <div class="card">
                <div class="card-body">

                </div>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row h-100">
              <div class="card" style="margin-left:15px">
                <div class="card-body">

                </div>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row">
              <div class="col" style="padding-right:0">
                <div class="card cardm">
                  <div class="card-body">

                  </div>
                </div>
              </div>
              <div class="col" style="padding-right:0">
                <div class="card cardm">
                  <div class="card-body">

                  </div>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col" style="padding-right:0">
                <div class="card cardm">
                  <div class="card-body">

                  </div>
                </div>
              </div>
              <div class="col" style="padding-right:0">
                <div class="card cardm">
                  <div class="card-body">

                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="row">
          <div class="col">
            <div class="row h-100">
              <div class="card">
                <div class="card-body" style="padding: 16px;">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-3">
        <div class="row">
          <div class="col" style="padding-right:0">
            <div class="card cardm">
              <div class="card-body" style="overflow-y: auto;">
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col" style="padding-right:0">
            <div class="card cardm">
              <div class="card-body">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col">
        <div class="row">
          <div class="col">
            <div class="card cardm">
              <div class="card-body">

              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="card cardm">
              <div class="card-body">

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>


问:
Report Server aggregation over groups by line
Maybe this is a newbie question, but

Imagine I have a report that shows the sales-order list pr sales-rep, itemized
to sku level, and want to show how many percent of the total sale of 1 sku, the sales-rep has sold.

I.e.

Sales-person

List of orders

```<code>    - List of items              no sold:  5  out of this months total 942
</code>```

Example:

John Doe

```<code>- Order #12312

      - SKU SP1231     Sold 5 . Month total 445

      - SKU SP4141     Sold 63 .  Month total 300
</code>```

Emma Doe

```<code>- Order #123324

      - SKU SP1231     Sold 65 . Month total 445

      - SKU SP4141     Sold 2 .  Month total 300
</code>```

etc

The Month total figure is the number of items sold of that particular sku in the total reporting period.

How do I go about adding this number? If I use Fields!TotalAmount.Value it gives the total as the group'ed total. i.e. how many of sku Y was sold on order X by sales-rep Z.

I need the global total of sales of that particular SKU.

If i say SUM(Fields!Amount,Nothing) to set global scope, it gives the sum of ALL sku's, not just the sku in question.

How do I do this?

EDIT

The Report Server is SSRS, the report uses a shared Datasource that is a Report Model already hosted on the reporting server, which points to a SQL Server database with
the contents.

答:
What would I do is select Sku total sum in your report dataset using comma separated lists:

```<code>-- testing data
DECLARE @Order TABLE (ID INT, SalesRepID INT, Date DATETIME)
INSERT INTO @Order
SELECT 1, 1, GETDATE() UNION
SELECT 2, 2, GETDATE() UNION
SELECT 3, 1, GETDATE() UNION
SELECT 4, 1, GETDATE() UNION
SELECT 5, 2, GETDATE()

DECLARE @OrderDetail TABLE (ID INT, OrderID INT, SkuID INT, SkuCount INT)
INSERT INTO @OrderDetail
SELECT 1, 1, 1, 10 UNION
SELECT 2, 1, 2, 5 UNION
SELECT 3, 1, 3, 20 UNION
SELECT 4, 1, 4, 10 UNION
SELECT 5, 2, 1, 15 UNION
SELECT 6, 2, 2, 25 UNION
SELECT 7, 2, 3, 15 UNION
SELECT 8, 3, 1, 15 UNION
SELECT 9, 3, 1, 10 UNION
SELECT 10, 3, 3, 10 UNION
SELECT 11, 3, 4, 15 UNION
SELECT 12, 4, 1, 5

DECLARE @Sku TABLE (ID INT, SkuCode VARCHAR(10))
INSERT INTO @Sku
SELECT 1, 'SP1233' UNION
SELECT 2, 'SP2262' UNION
SELECT 3, 'SP1531' UNION
SELECT 4, 'SP4235'

DECLARE @SalesRep TABLE (ID INT, SalesRepName VARCHAR(20))
INSERT INTO @SalesRep
SELECT 1, 'John Doe' UNION
SELECT 2, 'Emma Doe'

    -- filters for testing
DECLARE @StartDate DATETIME, @EndDate DATETIME
SELECT  @StartDate = GETDATE(), @EndDate = GETDATE()

DECLARE @SkuIDList VARCHAR(8000), @SkuSumList VARCHAR(8000)
SELECT @SkuIDList = '', @SkuSumList = ''
--gether all sku IDs and Sum in two comma separated list
SELECT @SkuIDList = @SkuIDList + CONVERT(VARCHAR, OD.SkuID) + ',',
@SkuSumList = @SkuSumList + CONVERT(VARCHAR, SUM(OD.SkuCount)) + ','
FROM @Order O
INNER JOIN @OrderDetail OD ON O.ID = OD.OrderID
WHERE O.Date BETWEEN @StartDate AND @EndDate
GROUP BY OD.SkuID
-- remove last ','
SELECT @SkuIDList = SUBSTRING(@SkuIDList, 0, LEN(@SkuIDList)),
 @SkuSumList = SUBSTRING(@SkuSumList, 0, LEN(@SkuSumList))

-- include thouse lists in the main select for your report dataset
SELECT O.ID, OD.SkuID, O.SalesRepID, SR.SalesRepName, S.SkuCode,
    OD.SkuCount, @SkuIDList AS SkuIDs, @SkuSumList AS SkuSums
FROM @Order O
INNER JOIN @OrderDetail OD ON O.ID = OD.OrderID
INNER JOIN @Sku S ON OD.SkuID = S.ID
INNER JOIN @SalesRep SR ON O.SalesRepID = SR.ID
WHERE O.Date BETWEEN @StartDate AND @EndDate
</code>```

Then you can use some custome code to retrieve sum value by sku ID (I have to write in C# currently, you easely convert it to VB):

```<code>public int GetSkuSum(string skuSumCSV, string skuIDCSV, int searchSkuID)
{
    string[] strSkuSum = skuSumCSV.Split(',');
    string[] strSkuID = skuIDCSV.Split(',');

    for (int i = 0; i < strSkuID.Length; i++)
    {
        if (Convert.ToInt32(strSkuID[i].Trim()) == searchSkuID)
        {
            return Convert.ToInt32(strSkuSum[i]);
        }
    }
    return 0;
}
</code>```

Then use it in your textbox Value expression:

```<code>=Code.GetSkuSum(Fields!SkuIDs.Value,Fields!SkuSums.Value,Fields!SkuID.Value)
</code>```

OwnerDisplayName: Soraz

Body:
Maybe this is a newbie question, but

Imagine I have a report that shows the sales-order list pr sales-rep, itemized
to sku level, and want to show how many percent of the total sale of 1 sku, the sales-rep has sold.

I.e.

Sales-person

List of orders

    - List of items              no sold:  5  out of this months total 942

Example:

John Doe

- Order #12312

      - SKU SP1231     Sold 5 . Month total 445

      - SKU SP4141     Sold 63 .  Month total 300

Emma Doe

- Order #123324

      - SKU SP1231     Sold 65 . Month total 445

      - SKU SP4141     Sold 2 .  Month total 300

etc

The Month total figure is the number of items sold of that particular sku in the total reporting period.

How do I go about adding this number? If I use Fields!TotalAmount.Value it gives the total as the group'ed total. i.e. how many of sku Y was sold on order X by sales-rep Z.

I need the global total of sales of that particular SKU.

If i say SUM(Fields!Amount,Nothing) to set global scope, it gives the sum of ALL sku's, not just the sku in question.

How do I do this?

EDIT

The Report Server is SSRS, the report uses a shared Datasource that is a Report Model already hosted on the reporting server, which points to a SQL Server database with
the contents.

LastEditorDisplayName: Soraz

Body:
What would I do is select Sku total sum in your report dataset using comma separated lists:

-- testing data
DECLARE @Order TABLE (ID INT, SalesRepID INT, Date DATETIME)
INSERT INTO @Order
SELECT 1, 1, GETDATE() UNION
SELECT 2, 2, GETDATE() UNION
SELECT 3, 1, GETDATE() UNION
SELECT 4, 1, GETDATE() UNION
SELECT 5, 2, GETDATE()

DECLARE @OrderDetail TABLE (ID INT, OrderID INT, SkuID INT, SkuCount INT)
INSERT INTO @OrderDetail
SELECT 1, 1, 1, 10 UNION
SELECT 2, 1, 2, 5 UNION
SELECT 3, 1, 3, 20 UNION
SELECT 4, 1, 4, 10 UNION
SELECT 5, 2, 1, 15 UNION
SELECT 6, 2, 2, 25 UNION
SELECT 7, 2, 3, 15 UNION
SELECT 8, 3, 1, 15 UNION
SELECT 9, 3, 1, 10 UNION
SELECT 10, 3, 3, 10 UNION
SELECT 11, 3, 4, 15 UNION
SELECT 12, 4, 1, 5

DECLARE @Sku TABLE (ID INT, SkuCode VARCHAR(10))
INSERT INTO @Sku
SELECT 1, 'SP1233' UNION
SELECT 2, 'SP2262' UNION
SELECT 3, 'SP1531' UNION
SELECT 4, 'SP4235'

DECLARE @SalesRep TABLE (ID INT, SalesRepName VARCHAR(20))
INSERT INTO @SalesRep
SELECT 1, 'John Doe' UNION
SELECT 2, 'Emma Doe'

    -- filters for testing
DECLARE @StartDate DATETIME, @EndDate DATETIME
SELECT  @StartDate = GETDATE(), @EndDate = GETDATE()

DECLARE @SkuIDList VARCHAR(8000), @SkuSumList VARCHAR(8000)
SELECT @SkuIDList = '', @SkuSumList = ''
--gether all sku IDs and Sum in two comma separated list
SELECT @SkuIDList = @SkuIDList + CONVERT(VARCHAR, OD.SkuID) + ',',
@SkuSumList = @SkuSumList + CONVERT(VARCHAR, SUM(OD.SkuCount)) + ','
FROM @Order O
INNER JOIN @OrderDetail OD ON O.ID = OD.OrderID
WHERE O.Date BETWEEN @StartDate AND @EndDate
GROUP BY OD.SkuID
-- remove last ','
SELECT @SkuIDList = SUBSTRING(@SkuIDList, 0, LEN(@SkuIDList)),
 @SkuSumList = SUBSTRING(@SkuSumList, 0, LEN(@SkuSumList))

-- include thouse lists in the main select for your report dataset
SELECT O.ID, OD.SkuID, O.SalesRepID, SR.SalesRepName, S.SkuCode,
    OD.SkuCount, @SkuIDList AS SkuIDs, @SkuSumList AS SkuSums
FROM @Order O
INNER JOIN @OrderDetail OD ON O.ID = OD.OrderID
INNER JOIN @Sku S ON OD.SkuID = S.ID
INNER JOIN @SalesRep SR ON O.SalesRepID = SR.ID
WHERE O.Date BETWEEN @StartDate AND @EndDate

Then you can use some custome code to retrieve sum value by sku ID (I have to write in C# currently, you easely convert it to VB):

public int GetSkuSum(string skuSumCSV, string skuIDCSV, int searchSkuID)
{
    string[] strSkuSum = skuSumCSV.Split(',');
    string[] strSkuID = skuIDCSV.Split(',');

    for (int i = 0; i < strSkuID.Length; i++)
    {
        if (Convert.ToInt32(strSkuID[i].Trim()) == searchSkuID)
        {
            return Convert.ToInt32(strSkuSum[i]);
        }
    }
    return 0;
}

Then use it in your textbox Value expression:

=Code.GetSkuSum(Fields!SkuIDs.Value,Fields!SkuSums.Value,Fields!SkuID.Value)

OwnerDisplayName: coldice


问:
problem with ColdFusion cfqueryparam and a complicated query
I have a query where I am inserting ~300 records using one insert query.  For each record, I have to do replaces and operations on the data.  I just found out I have to use cfqueryparam now because one of the records is a CLOB and is reaching a large size.  I was using a string to form the query and placing the string in the cfquery tag. Now I can't do that because you have to use PreserveSingleQuotes to put a string var in a cfquery tag and you can't use PreserveSingleQuotes with cfqueryparam.  So is my best option to do all the operations and looping inside the cfquery tag?  Will it be able to handle that?  Or will I have to do 1000 separate insert statements?  Is there a better idea?  thanks.</p>

答:
```<code><cfqueryparam value="#PreserveSingleQuotes(whatever)#" CFSQLType="CF_SQL_CLOB" />
</code>```

Should work in CFQUERY.

Body:
<cfqueryparam value="#PreserveSingleQuotes(whatever)#" CFSQLType="CF_SQL_CLOB" />

Should work in CFQUERY.


问:
Pytest - Test directory specific conftest.py to override pytest_terminal_summary
Searching over the net and pytest documentation, I am bit confused.
Is it or is it not recommended to have test directory specific hooks in their own respective conftest.py ??

While the doc says

Note that pytest does not find conftest.py files in deeper nested sub directories at tool startup. It is usually a good idea to keep your conftest.py file in the top level test or project root directory.

The very next paragraph describes having per-directory conftest.py

The issue I am having is that the existing pytest framework we have has few globals defined in the root conftest.py And then some scripts have import contest

I wish to override the pytest_terminal_summary for few of my testcases where I need to parse a file and display results

But the presence of local contest.py in the test directory, raises error about the globals

```<code>contest.py    # Root conftest.py
global logfile

tests/mytests/
              conftest.py
              my_own_test.py

# pytest my_own_test.py
E    module 'conftest' has no attribute 'logfile'
</code>```

Any workarounds for this ? I am not sure if I can get of the existing import contest

答:
I was able to workaround this by having my pytest_terminal_summary hook in py file. Then including that as pytest_plugins=[...] in the test module.

Note: I had to invoke the tests with python3 -m pytest to let it find the locally available module, but that is ok

Body:
Searching over the net and pytest documentation, I am bit confused.
Is it or is it not recommended to have test directory specific hooks in their own respective conftest.py ??

While the doc says

Note that pytest does not find conftest.py files in deeper nested sub directories at tool startup. It is usually a good idea to keep your conftest.py file in the top level test or project root directory.

The very next paragraph describes having per-directory conftest.py

The issue I am having is that the existing pytest framework we have has few globals defined in the root conftest.py And then some scripts have import contest

I wish to override the pytest_terminal_summary for few of my testcases where I need to parse a file and display results

But the presence of local contest.py in the test directory, raises error about the globals

contest.py    # Root conftest.py
global logfile

tests/mytests/
              conftest.py
              my_own_test.py

# pytest my_own_test.py
E    module 'conftest' has no attribute 'logfile'

Any workarounds for this ? I am not sure if I can get of the existing import contest


问:
How can i make flat button size as it's child size
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

```<code>        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),
</code>```

and this is the photo
photo

答:
Try this for button function:</p>

```<code>Expanded(
//Modify below factor as your requirement
  flex: 1,
  child: InkWell(
      onTap: () {},
      child: Container(
      alignment: Alignment.center,
//Modify width,height as your requirement
      height: double.infinity,
      width:double.infinity,
      decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(30),
      color: Colors.blueAccent.withAlpha(30),
        ),
     child: Text('SHOP',
           style: TextStyle(
           color: Colors.blue,
           fontWeight: FontWeight.bold,
           fontSize: 20)),
          ),
        )),
</code>```

Body:
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),

and this is the photo
photo

Body:
Try this for button function:

Expanded(
//Modify below factor as your requirement
  flex: 1,
  child: InkWell(
      onTap: () {},
      child: Container(
      alignment: Alignment.center,
//Modify width,height as your requirement
      height: double.infinity,
      width:double.infinity,
      decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(30),
      color: Colors.blueAccent.withAlpha(30),
        ),
     child: Text('SHOP',
           style: TextStyle(
           color: Colors.blue,
           fontWeight: FontWeight.bold,
           fontSize: 20)),
          ),
        )),


答:
You can make a use of std::transform:

std::vector<int> result;

std::transform(
    foo.begin(), foo.end(), bar.begin(),
    std::back_inserter(result),
    [](const auto& a, const auto& b) {
        if (a % 2 == 0) {
            return a;
        }
        return b;
    }
);
```

Demo

Title: replace all odd values in vector with coresponing value from new vector

Body:
Given following vectors:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70

Body:
You can make a use of std::transform:

std::vector<int> result;

std::transform(
    foo.begin(), foo.end(), bar.begin(),
    std::back_inserter(result),
    [](const auto& a, const auto& b) {
        if (a % 2 == 0) {
            return a;
        }
        return b;
    }
);

<a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxEAGZXpAA6oFhdbT1DE0FvXzU6Kxt7IycXd0VlTFV/BgJmYgJA41NOBJVw2lT0gki7R2c3DwU0jKzg3Ori0ujYyoBKRVQDYmQOAHIpV2tkQywAanFXHXVq4kxmI0nsMZWVgHo1ser0EBQugnEABgBBQeHRzAmptmASQgRF12XVja2CHZA5z2FegH00TwAT1%2BeCoR1OkiGtBGBnGkx0ADckkRiEtVujXttdkjVCRweDrAQxkZmNYxhA2hMAOyyE7orEgHEo%2BGEtE0VDiGm5SSkDy8ACspAAbKQqZyACKTWnHenvbHIvFTVlPMYOdKc6ScQ6kSTa1za7ja/naoXaqmHCVS8Gyj5MxXTehouYKAysA6uaXW1YMgjEEQKGjEIwQL3olbsgB0TmA1gppDGkfMcdV6SjmBjtDjobDDLVyAA1iDaEoMs4IM7XQQOtn0eJ%2BbJ%2BeKIGhi0TmAYiFIhWNmPGW9Uex2OZJuw42jXVhqJ2GxqDycwJpJ%2BWNJFdJa5xWNDpSp3SZ/uVnMCN1aD2rXuDytLRfL0eT6rzzL99enytxx6vdmGWgO1cdPDF0kdkxhbNJrAUEApEkR90UDech1nEAE1QVBxxpN4Ph/Il4QAsA%2BjGPC/wAvApWpSUb2/fYiKmAiBn5HRaDwx8vzlPZfxwmioLVYgQLoMDi0gyRoI/G84IgdsiEQlNiDQ6QMN2LDqJ0WiVI45SSI9MiWMwqi1NousGKYkTTgo1jFL0qCKzdXj6FJASoJg1YxIk1ApKsqsNXktjsKmXD8MIvSNLkl8bQU3TfJopj6MYgZjOzO9iFPC04qpcU%2Bg6VgQD6fk%2BlIUw%2BkOXLUCy/8ZDkLYuh6S5Bk4XKCCywq2g6fMQH5SQIyFVxzSpfkqU4AAOQ5OH5IVRqELLuFy/LCtIYq%2BlyiDtXqgr0tIOBYBgRA9iMTw8HYMgKGbVAdr2ipgAATh5Kg9oIZwIIgBwGtyhxrHSQEstq0g0CMIwtAIAB5WhWHelbSCwElRHYJ6wbwOZkiRCDQcwAAPJIO36GbCWUaHWDwBw/WIQE9CwD66uIPAjFJjoaHoJg2A4Hh%2BEEYRRBQOQ5CEPGIMgDpUE8ApEYAWm2SZxQkMqZEkZgFsSZINAgcw6hyUhzGacoXFyUI/DoJWQh8bXaDVmIKgaWWCiKWp9GyQQlHyFIahKawymNjXFAd3WGgdo3Wk4DoFEq3ouAyrKcry6G5uR/qhUFoVuDGYBkGQMZzojVcIFwQgSEXVxcjGPQTv27Pfbz9mZDqp6mtIFquojQVMr6SbSEp40w9BuaFpAJaK7WzaICQfZPA7chKG%2B3b9rMfAUUEGnGBYKHGYAdz9TwqfG7KpvDrKarGBf7jGSPo9j%2BPE%2BT1Py5WyuEHmLAXDjevG%2Bb7VpqKrKO67i/mpAbgqQjVwhUkS63BJD9U4Odfq3B3C8Hrq4DebdX6kGWo1YOfRJCwJmu3BBFcOhImIL4DQ3AgA%3D%3D" rel="nofollow noreferrer">Demo


问:
Always return Account/Login page if not logged
I have a problem when return login page if user is not logged.
My ConfigureServices:

```<code>services.AddAuthentication(CookieScheme) // Sets the default scheme to cookies
            .AddCookie(CookieScheme, options =>
            {
                options.AccessDeniedPath = "/admin/account/accessdenied";
                options.LoginPath = "/admin/account/login";
            });
</code>```

What I want it returns /admin/account/login But result always return /Account/Login

答:
I'm not sure why your code doesn't work but you could try adding the below to your options.

EDIT: If you're using services.ConfigureApplicationCookie in your startup you could try adding the path and redirection to that instead.

```<code>options.Events = new CookieAuthenticationEvents
{
   OnRedirectToLogin = ctx =>
   {
      ctx.Response.Redirect("/admin/account/login");
      return Task.CompletedTask;
   }
};
</code>```

Body:
I have a problem when return login page if user is not logged.
My ConfigureServices:

services.AddAuthentication(CookieScheme) // Sets the default scheme to cookies
            .AddCookie(CookieScheme, options =>
            {
                options.AccessDeniedPath = "/admin/account/accessdenied";
                options.LoginPath = "/admin/account/login";
            });

What I want it returns /admin/account/login But result always return /Account/Login

Body:
I'm not sure why your code doesn't work but you could try adding the below to your options.

EDIT: If you're using services.ConfigureApplicationCookie in your startup you could try adding the path and redirection to that instead.

options.Events = new CookieAuthenticationEvents
{
   OnRedirectToLogin = ctx =>
   {
      ctx.Response.Redirect("/admin/account/login");
      return Task.CompletedTask;
   }
};


问:
React Navigation 5.x stack navigation show blank screen
//app.js  "react": "16.9.0","react-native": "0.61.5", offic
follow the official document but show blank screen react native

```<code>import React from 'react';
import { SafeAreaView, StatusBar, View, Text } from 'react-native';
import { Provider } from 'react-redux';
import configureStore from './App/redux/store/store'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AppSplashScreen from './App/screens/splashScreen/SplashScreen';
const Stack = createStackNavigator();

function MyStack() {
 return (
        <Stack.Navigator>
          <Stack.Screen name="Home" component={AppSplashScreen} />
        </Stack.Navigator>
 );
}

export default class App extends React.Component {
   constructor(props) {
     super(props)
     this.state = {}
   }

   render() {
        return (
                <>
                <StatusBar barStyle="dark-content" />
                  <SafeAreaView  >
                    <Provider store={configureStore()} >
                      <NavigationContainer>
                        <MyStack />
                      </NavigationContainer>
                    </Provider>
                 </SafeAreaView>
                </>
               );
             }

           };
</code>```

but replace  MyStack to AppSplashScreen then show SplashScreen

答:
This should work fine, try not to separate the Stack.Navigator from the navigation container

this works for me

```<code>function App() {
  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" component={Homepage} />
          <Stack.Screen name="Notes" component={Notes} />
        </Stack.Navigator>
     </NavigationContainer>
   </Provider>
 );
}
</code>```

export default App;

Body:
//app.js  "react": "16.9.0","react-native": "0.61.5", offic
follow the official document but show blank screen react native

import React from 'react';
import { SafeAreaView, StatusBar, View, Text } from 'react-native';
import { Provider } from 'react-redux';
import configureStore from './App/redux/store/store'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AppSplashScreen from './App/screens/splashScreen/SplashScreen';
const Stack = createStackNavigator();

function MyStack() {
 return (
        <Stack.Navigator>
          <Stack.Screen name="Home" component={AppSplashScreen} />
        </Stack.Navigator>
 );
}

export default class App extends React.Component {
   constructor(props) {
     super(props)
     this.state = {}
   }

   render() {
        return (
                <>
                <StatusBar barStyle="dark-content" />
                  <SafeAreaView  >
                    <Provider store={configureStore()} >
                      <NavigationContainer>
                        <MyStack />
                      </NavigationContainer>
                    </Provider>
                 </SafeAreaView>
                </>
               );
             }

           };

but replace  MyStack to AppSplashScreen then show SplashScreen

Body:
This should work fine, try not to separate the Stack.Navigator from the navigation container

this works for me

function App() {
  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" component={Homepage} />
          <Stack.Screen name="Notes" component={Notes} />
        </Stack.Navigator>
     </NavigationContainer>
   </Provider>
 );
}

export default App;


问:
How to copy values from one sheet and paste them into another using Google Sheets Macros?
I'm writing a Google Sheets Macros without having a lot of knowledge about syntax.

What I want to do is the following:

I want to copy the values which are matching in a source matrix into another table. However, I don't know how to write that as a Macros.

I've written the following code:

```<code>function CalcularCruces() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = spreadsheet.getSheetByName("Cruces Activo-Amenazas");
  var destinationSheet = spreadsheet.getSheetByName("Análisis de Riesgos");

  /** Total number of left column values from source table **/
  const maxAmenazas = 29;

  for(var i = 0; i < maxAmenazas; i++) {
    /** Now I need to get the column and row values which are matching with the checkbox
        and paste them into another table **/
  }

};
</code>```

Here is an example of the input table and how the output table should look like after executing the macros.

Input Table Sheet
Output Table Sheet

Edit:

I need the data to be written next to this static columns:

Actual Output

Desired Output

答:
You can do the following:

Retrieve the data from the source sheet via getDataRange and getValues.

For each row in this data (excluding the headers row, that has been retrieved and removed from the array with shift), check which columns have the checkbox marked.

If the corresponding checkbox is marked, write the corresponding values to the destination sheet with setValues.

It could be something like this:

function CalcularCruces() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = spreadsheet.getSheetByName("Cruces Activo-Amenazas");
  var destinationSheet = spreadsheet.getSheetByName("Análisis de Riesgos");
  destinationSheet.getRange("A2:B").clearContent();
  var values = sourceSheet.getDataRange().getValues(); // 2D array with all data from source sheet
  var headers = values.shift(); // Remove and retrieve the headers row
  for (var i = 1; i < values[0].length; i++) { // Iterate through each column
    for (var j = 0; j < values.length; j++) { // Iterate through each row
      var activo = values[j][0]; // Activo corresponding to this row
      if (values[j][i]) { // Check that checkbox is marked
        // Get the row index to write to (first row in which column A and B are empty):
        var firstRow = 2;
        var firstCol = 1;
        var numRows = destinationSheet.getLastRow() - firstRow + 1;
        var numCols = 2;
        var firstEmptyRow = destinationSheet.getRange(firstRow, firstCol, numRows, numCols).getValues().filter(function(row) {
          return row[0] !== "" && row[1] !== "";
        }).length + firstRow;
        // Write data to first row with empty columns A/B:
        destinationSheet.getRange(firstEmptyRow, firstCol, 1, numCols).setValues([[headers[i], activo]]);
      }
    }
  }
};
```

<h3>Notes:</h3>

<ul>
<li>All data is added to the target sheet every time the script is run, and this can lead to duplicate rows. If you want to avoid that, you can use clearContent at the beginning of your script, after declaring <code>destinationSheet</code>, to remove all previous content (headers excluded):</li>
</ul>

<pre class="lang-js prettyprint-override"><code>destinationSheet.getRange("A2:B").clearContent();
</code>```

In this sample, the number of amenazas is not hard-coded, but it dynamically gets the number of rows in the source sheet with getValues().length. I'm assuming that's a good outcome for you.

UPDATE: Since you have other columns in your target sheet, you cannot use appendRow but setValues. First, you have to find the index of the first row in which columns A and B are empty. This is achieved with filtering the array of values in columns A-B and filtering out the elements in which the two values are empty (with filter).

Reference:

Sheet.getDataRange

Range.getValues

Array.prototype.shift()

Sheet.appendRow(rowContents)

Array.prototype.filter()

Range.clearContent()

Body:
I'm writing a Google Sheets Macros without having a lot of knowledge about syntax.

What I want to do is the following:

I want to copy the values which are matching in a source matrix into another table. However, I don't know how to write that as a Macros.

I've written the following code:

function CalcularCruces() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = spreadsheet.getSheetByName("Cruces Activo-Amenazas");
  var destinationSheet = spreadsheet.getSheetByName("Análisis de Riesgos");

  /** Total number of left column values from source table **/
  const maxAmenazas = 29;

  for(var i = 0; i < maxAmenazas; i++) {
    /** Now I need to get the column and row values which are matching with the checkbox
        and paste them into another table **/
  }

};

Here is an example of the input table and how the output table should look like after executing the macros.

Input Table Sheet
Output Table Sheet

Edit:

I need the data to be written next to this static columns:

Actual Output

Desired Output

Body:
You can do the following:

Retrieve the data from the source sheet via getDataRange and getValues.

For each row in this data (excluding the headers row, that has been retrieved and removed from the array with shift), check which columns have the checkbox marked.

If the corresponding checkbox is marked, write the corresponding values to the destination sheet with setValues.

It could be something like this:

function CalcularCruces() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = spreadsheet.getSheetByName("Cruces Activo-Amenazas");
  var destinationSheet = spreadsheet.getSheetByName("Análisis de Riesgos");
  destinationSheet.getRange("A2:B").clearContent();
  var values = sourceSheet.getDataRange().getValues(); // 2D array with all data from source sheet
  var headers = values.shift(); // Remove and retrieve the headers row
  for (var i = 1; i < values[0].length; i++) { // Iterate through each column
    for (var j = 0; j < values.length; j++) { // Iterate through each row
      var activo = values[j][0]; // Activo corresponding to this row
      if (values[j][i]) { // Check that checkbox is marked
        // Get the row index to write to (first row in which column A and B are empty):
        var firstRow = 2;
        var firstCol = 1;
        var numRows = destinationSheet.getLastRow() - firstRow + 1;
        var numCols = 2;
        var firstEmptyRow = destinationSheet.getRange(firstRow, firstCol, numRows, numCols).getValues().filter(function(row) {
          return row[0] !== "" && row[1] !== "";
        }).length + firstRow;
        // Write data to first row with empty columns A/B:
        destinationSheet.getRange(firstEmptyRow, firstCol, 1, numCols).setValues([[headers[i], activo]]);
      }
    }
  }
};

Notes:

All data is added to the target sheet every time the script is run, and this can lead to duplicate rows. If you want to avoid that, you can use clearContent at the beginning of your script, after declaring destinationSheet, to remove all previous content (headers excluded):

destinationSheet.getRange("A2:B").clearContent();

In this sample, the number of amenazas is not hard-coded, but it dynamically gets the number of rows in the source sheet with getValues().length. I'm assuming that's a good outcome for you.

UPDATE: Since you have other columns in your target sheet, you cannot use appendRow but setValues. First, you have to find the index of the first row in which columns A and B are empty. This is achieved with filtering the array of values in columns A-B and filtering out the elements in which the two values are empty (with filter).

Reference:

Sheet.getDataRange

Range.getValues

Array.prototype.shift()

Sheet.appendRow(rowContents)

Array.prototype.filter()

Range.clearContent()


问:
sql server 2005 'update from' query
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

```<code>    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid
</code>```

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

答:
```<code>update jared_test
set user_count = 1
where userid =
  (select userID from users where email = 'j@j.co.uk')
</code>```

<p>try this </p>

Title: sql server 2005 'update from' query

Body:
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

Body:
update jared_test
set user_count = 1
where userid =
  (select userID from users where email = 'j@j.co.uk')

try this


答:
You can use the std::transform overload that takes two input iterator ranges:

```<code>std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(),
  [](auto const& a, auto const& b) {
     if (a % 2)
        return b;
     return a;
  }
);
</code>```

Body:
You can use the std::transform overload that takes two input iterator ranges:

std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(),
  [](auto const& a, auto const& b) {
     if (a % 2)
        return b;
     return a;
  }
);


问:
TypeScript Array of Tuples
So I have this simple example:

```<code>type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK
</code>```

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

答:
```<code>type TypeOfOptions = typeof options[number] // (string | number)[]
type IsTypeOfOptionsSubsetOfSomeTuple =
  TypeOfOptions extends SomeTuple ? true : false // false is not assignable to SomeTuple

</code>```

It meansTypeOfOptions is just more general type then SomeTuple and naturally cannot be used as SomeTuple, this is exactly why you do have the error. You want [string, number] you get by automatic inference (string | number)[], clearly not the same.

Why its more general because TS type inference works like that, we can change the behavior by assert our type to more specific by as or : or make value constructor which will do that.

Below few possible options how to change the initial inference:

```<code>// value constructor
const makeOptions = (...a: SomeTuple[]): SomeTuple[] => a
const options1 = makeOptions(
    ['first', 1],
    ['second', 2],
) // a is SomeTuple[]

// using :
const options2: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

// using as
const options3 = [
    ['first', 1],
    ['second', 2],
] as SomeTuple[]

foo(options1) // ok
foo(options2) // ok
foo(options3) // ok
</code>```

Additional note about question in the comment. Generally type SomeTuple is a specification of type TypeOfOptions, it means that if you have value which is TypeOfOptions it can be also SomeTuple but does not must be. Lets check if such relation is true:

```<code>type IsSomeTupleSubsetOfTypeOfOptions = SomeTuple extends TypeOfOptions ? true : false // true
</code>```

So yes SomeTuple is specific variant of TypeOfOptions. It means we can assert type of TypeOfOptions into SomeTuple saying we are narrowing to this specific case. But if we do that - TS will validate the value to the narrowed type right away, if its match, type assertion is successful.

Title: TypeScript Array of Tuples

Body:
So I have this simple example:

type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

Body:
type TypeOfOptions = typeof options[number] // (string | number)[]
type IsTypeOfOptionsSubsetOfSomeTuple =
  TypeOfOptions extends SomeTuple ? true : false // false is not assignable to SomeTuple

It meansTypeOfOptions is just more general type then SomeTuple and naturally cannot be used as SomeTuple, this is exactly why you do have the error. You want [string, number] you get by automatic inference (string | number)[], clearly not the same.

Why its more general because TS type inference works like that, we can change the behavior by assert our type to more specific by as or : or make value constructor which will do that.

Below few possible options how to change the initial inference:

// value constructor
const makeOptions = (...a: SomeTuple[]): SomeTuple[] => a
const options1 = makeOptions(
    ['first', 1],
    ['second', 2],
) // a is SomeTuple[]

// using :
const options2: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

// using as
const options3 = [
    ['first', 1],
    ['second', 2],
] as SomeTuple[]

foo(options1) // ok
foo(options2) // ok
foo(options3) // ok

Additional note about question in the comment. Generally type SomeTuple is a specification of type TypeOfOptions, it means that if you have value which is TypeOfOptions it can be also SomeTuple but does not must be. Lets check if such relation is true:

type IsSomeTupleSubsetOfTypeOfOptions = SomeTuple extends TypeOfOptions ? true : false // true

So yes SomeTuple is specific variant of TypeOfOptions. It means we can assert type of TypeOfOptions into SomeTuple saying we are narrowing to this specific case. But if we do that - TS will validate the value to the narrowed type right away, if its match, type assertion is successful.


问:
How can I install a tweepy package via pip?
Can't get pip to work; trying to install Tweepy per this article.

This thread managed to solve it for someone installing a different package, but I've tried all the strategies listed there including changing PATH in my environment variables, and I get "syntax error" for each of these three attempts:

```<code>pip install tweepy

python -m pip install tweepy

C:\Python27\Scripts\pip.exe install tweepy
</code>```

答: For python3 use pip3 install tweepy command from your terminal

Body:
Can't get pip to work; trying to install Tweepy per this article.

This thread managed to solve it for someone installing a different package, but I've tried all the strategies listed there including changing PATH in my environment variables, and I get "syntax error" for each of these three attempts:

pip install tweepy

python -m pip install tweepy

C:\Python27\Scripts\pip.exe install tweepy