问:
how to extract content from
 tag java
i have a serious problem.
i would like to extract the content from  tag such as:

```<code><div class="main-content">
    <div class="sub-content">Sub content here</div>
      Main content here </div>
</code>```

output i would expect is:

Sub content here
Main content here

i've tried using regex, but the result isn't so impressive.
By using:

```<code>Pattern.compile("<div>(\\S+)</div>");
</code>```

would return all the strings before the first <*/div> tag
so, could anyone help me pls?

答:
I'd recommend avoiding regex for parsing HTML. You can easily do what you ask by using Jsoup:

```<code>public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}
</code>```

In response to comment: if you want to put the content of the div elements into an array of Strings you can simply do:

```<code>    String[] divsTexts = new String[divs.size()];
    for (int i = 0; i < divs.size(); i++) {
        divsTexts[i] = divs.get(i).ownText();
    }
</code>```

In response to comment: if you have nested elements and you want to get own text for each element than you can use jquery multiple selector syntax. Here's an example:

```<code>public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">" +
            "<p>a paragraph <b>with some bold text</b></p>" +
            "Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div, p, b");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}
</code>```

The code above will parse the following HTML:

```<code><html>
<head />
<body>
<div class="main-content">
<div class="sub-content">
<p>a paragraph <b>with some bold text</b></p>
Sub content here</div>
Main content here</div>
</body>
</html>
</code>```

and print the following output:

```<code>Main content here
Sub content here
a paragraph
with some bold text
</code>```

Title: how to extract content from <div> tag java

Body:
i have a serious problem.
i would like to extract the content from  tag such as:

Sub content here

      Main content here

output i would expect is:

Sub content here
Main content here

i've tried using regex, but the result isn't so impressive.
By using:

Pattern.compile("
(\\S+)
");

would return all the strings before the first <*/div> tag
so, could anyone help me pls?

Body:
I'd recommend avoiding regex for parsing HTML. You can easily do what you ask by using Jsoup:

public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}

In response to comment: if you want to put the content of the div elements into an array of Strings you can simply do:

    String[] divsTexts = new String[divs.size()];
    for (int i = 0; i < divs.size(); i++) {
        divsTexts[i] = divs.get(i).ownText();
    }

In response to comment: if you have nested elements and you want to get own text for each element than you can use jquery multiple selector syntax. Here's an example:

public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">" +
            "<p>a paragraph <b>with some bold text</b></p>" +
            "Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div, p, b");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}

The code above will parse the following HTML:

<html>
<head />
<body>
<div class="main-content">
<div class="sub-content">
<p>a paragraph <b>with some bold text</b></p>
Sub content here</div>
Main content here</div>
</body>
</html>

and print the following output:

Main content here
Sub content here
a paragraph
with some bold text


来源: stackexchange

问:
Appium Automatic Server - No Chromedriver found that can automate Chrome '68.0.3440'
I'm trying to connect a physical Android device to Appium Automatic Server.  The capabilities are:

```<code>{
  "platformName": "Android",
  "platformVersion": "8.1.0",
  "deviceName": "Oreo",
  "browserName": "Chrome"
}
</code>```

When I click "Start Session" it says

```<code>An unknown server-side error occurred while processing the command. Original error: No Chromedriver found that can automate Chrome '68.0.3440'. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md for more details.
</code>```

Going to https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md it says I need version 2.4.2.  I tried installing it with npm install -g appium-chromedriver --chromedriver_version="2.42", is this not the right command?

I also tried downloading the zip here https://chromedriver.storage.googleapis.com/index.html?path=2.42/ and running it to no avail.

答:
When I had the same issue, I resolved it like this :

cd  /usr/local/lib/node_modules/

npm uninstall appium

npm install appium --chromedriver_version="79.0.3945.36"

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to connect a physical Android device to Appium Automatic Server.  The capabilities are:

{
  "platformName": "Android",
  "platformVersion": "8.1.0",
  "deviceName": "Oreo",
  "browserName": "Chrome"
}

When I click "Start Session" it says

An unknown server-side error occurred while processing the command. Original error: No Chromedriver found that can automate Chrome '68.0.3440'. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md for more details.

Going to https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md it says I need version 2.4.2.  I tried installing it with npm install -g appium-chromedriver --chromedriver_version="2.42", is this not the right command?

I also tried downloading the zip here https://chromedriver.storage.googleapis.com/index.html?path=2.42/ and running it to no avail.


问:
How to select words with apostrophe using regular expression
I am trying to separate a string into a list, but I need to have the string contain words that are joined by apostrophes. For example :

```<code>String="My name is Melvin_JESUS, Guatemala, Dean'Olvier, 501soy...@ 1231 !"
</code>```

should give me a result as:

```<code>['my', 'name', 'is', 'melvin', 'jesus', 'guatemala', '"dean'oliver"', 'soy']
</code>```

i have tried the following regular expression:

```<code>my_patern= r"(?:^|(?<=\s)|-)[A-Za-z'\.]+(?=\s|\t|$|\b)"
</code>```

but doesn't give me the desired results.

答:
You may use

```<code>(?<![^\W\d_])[^\W\d_]+(?:['.][^\W\d_]+)*(?![^\W\d_])
</code>```

See the regex demo

Details

(?<![^\W\d_]) - no letter right before the match is allowed

[^\W\d_]+ - 1 or more letters

(?:['.][^\W\d_]+)* - 0 or more sequences of ' or . and then 1+ letters

(?![^\W\d_]) - no letter right after the match is allowed.

In Python, use

```<code>re.findall(r'(?<![^\W\d_])[^\W\d_]+(?:['.][^\W\d_]+)*(?![^\W\d_])', text)
</code>```

Body:
I am trying to separate a string into a list, but I need to have the string contain words that are joined by apostrophes. For example :

String="My name is Melvin_JESUS, Guatemala, Dean'Olvier, 501soy...@ 1231 !"

should give me a result as:

['my', 'name', 'is', 'melvin', 'jesus', 'guatemala', '"dean'oliver"', 'soy']

i have tried the following regular expression:

my_patern= r"(?:^|(?<=\s)|-)[A-Za-z'\.]+(?=\s|\t|$|\b)"

but doesn't give me the desired results.

Body:
You may use

(?<![^\W\d_])[^\W\d_]+(?:['.][^\W\d_]+)*(?![^\W\d_])

See the regex demo

Details

(?<![^\W\d_]) - no letter right before the match is allowed

[^\W\d_]+ - 1 or more letters

(?:['.][^\W\d_]+)* - 0 or more sequences of ' or . and then 1+ letters

(?![^\W\d_]) - no letter right after the match is allowed.

In Python, use

re.findall(r'(?<![^\W\d_])[^\W\d_]+(?:['.][^\W\d_]+)*(?![^\W\d_])', text)


问:
Find sum of given value in ArrayList of double values
Im having troubling with finding the sum of certain given value in a Double ArrayList.

I have these values in a double ArrayList:

```<code>{0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.20, 0.20, 0.20, 0.20, 0.20, 0.50, 0.50, 0.50, 0.50, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00}
</code>```

10 values = 0.1

5 values = 0.20

4 values = 0.50

6 values = 1.0

I need a method that passing it the value i want, let's say 3.5, it returns me for example

```<code>1.0, 1.0, 1.0, 0.5
</code>```

But if I want 1.5 it may return

```<code>1.0, 0.5
</code>```

I would appreciate any help. Thanks in advance

答:
Found the solution. Thanks @kaya3 for the clarification. This is what i found and I applied it to my problem:

https://www.geeksforgeeks.org/recursive-program-to-print-all-subsets-with-given-sum/

```<code>import java.util.ArrayList;
</code>```

import java.util.Vector;

public class test {

```<code>public static void main(String[] args) {
    ArrayList<Double> arrayDoubles = new ArrayList<>();
    for (int i = 0; i < 10; i++){
        arrayDoubles.add(0.10);
    }

    for (int j = 0; j < 5; j++){
        arrayDoubles.add(0.20);
    }

    for (int k = 0; k < 4; k++){
        arrayDoubles.add(0.50);
    }

    for (int l = 0; l < 6; l++){
        arrayDoubles.add(1.00);
    }

    printAllSubsets(arrayDoubles, arrayDoubles.size(), 3.20);

}

static void printAllSubsetsRec(ArrayList<Double> arr, int n, Vector<Double> v,
                               double sum)
{
    // If remaining sum is 0, then print all
    // elements of current subset.
    if (Math.round(sum * 10.0) / 10.0 == 0) {
        for (int i=0;i<v.size();i++)
            System.out.print( v.get(i) + " ");
        System.out.println();
        return;
    }

    // If no remaining elements,
    if (n == 0)
        return;

    // We consider two cases for every element.
    // a) We do not include last element.
    // b) We include last element in current subset.
    printAllSubsetsRec(arr, n - 1, v, Math.round(sum * 10.0) / 10.0);
    Vector<Double> v1=new Vector<Double>(v);
    v1.add(arr.get(n-1));
    printAllSubsetsRec(arr, n - 1, v1, Math.round(sum * 10.0) / 10.0 - arr.get(n-1));
}

static void printAllSubsets(ArrayList<Double> arr, int n, double sum)
{
    Vector<Double> v= new Vector<Double>();
    printAllSubsetsRec(arr, n, v, Math.round(sum * 10.0) / 10.0);
}
</code>```

}

Body:
Im having troubling with finding the sum of certain given value in a Double ArrayList.

I have these values in a double ArrayList:

{0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.20, 0.20, 0.20, 0.20, 0.20, 0.50, 0.50, 0.50, 0.50, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00}

10 values = 0.1

5 values = 0.20

4 values = 0.50

6 values = 1.0

I need a method that passing it the value i want, let's say 3.5, it returns me for example

1.0, 1.0, 1.0, 0.5

But if I want 1.5 it may return

1.0, 0.5

I would appreciate any help. Thanks in advance

Body:
Found the solution. Thanks @kaya3 for the clarification. This is what i found and I applied it to my problem:

https://www.geeksforgeeks.org/recursive-program-to-print-all-subsets-with-given-sum/

import java.util.ArrayList;

import java.util.Vector;

public class test {

public static void main(String[] args) {
    ArrayList<Double> arrayDoubles = new ArrayList<>();
    for (int i = 0; i < 10; i++){
        arrayDoubles.add(0.10);
    }

    for (int j = 0; j < 5; j++){
        arrayDoubles.add(0.20);
    }

    for (int k = 0; k < 4; k++){
        arrayDoubles.add(0.50);
    }

    for (int l = 0; l < 6; l++){
        arrayDoubles.add(1.00);
    }

    printAllSubsets(arrayDoubles, arrayDoubles.size(), 3.20);

}

static void printAllSubsetsRec(ArrayList<Double> arr, int n, Vector<Double> v,
                               double sum)
{
    // If remaining sum is 0, then print all
    // elements of current subset.
    if (Math.round(sum * 10.0) / 10.0 == 0) {
        for (int i=0;i<v.size();i++)
            System.out.print( v.get(i) + " ");
        System.out.println();
        return;
    }

    // If no remaining elements,
    if (n == 0)
        return;

    // We consider two cases for every element.
    // a) We do not include last element.
    // b) We include last element in current subset.
    printAllSubsetsRec(arr, n - 1, v, Math.round(sum * 10.0) / 10.0);
    Vector<Double> v1=new Vector<Double>(v);
    v1.add(arr.get(n-1));
    printAllSubsetsRec(arr, n - 1, v1, Math.round(sum * 10.0) / 10.0 - arr.get(n-1));
}

static void printAllSubsets(ArrayList<Double> arr, int n, double sum)
{
    Vector<Double> v= new Vector<Double>();
    printAllSubsetsRec(arr, n, v, Math.round(sum * 10.0) / 10.0);
}

}


问:
How to get the class type of the contents of an Iterable in scala?
Say I have a method like this:

```<code>def getClassFromIterable(iterable: Iterable[Any]): Class[_] = {
  iterable.head.getClass
}
</code>```

This will get the class of the top of the list, but will fail if the list is empty.

How can I get the class of a passed list that has zero or more elements?

答:
Supplementing Luis' answer with a reflective solution, consider

```<code>import scala.reflect.runtime.universe._

def toTable[A <: Product](ps: List[A])(implicit ev: TypeTag[A]) = {
  val separator = "\t\t"
  ps match {
    case Nil =>
      val header = typeOf[A].members.collect { case m: MethodSymbol if m.isCaseAccessor => m.name }.toList
      header.mkString("", separator , "\n")

    case head :: _ =>
      val header = head.productElementNames.toList
      val rows = ps.map(_.productIterator.mkString(separator))
      header.mkString("", separator, "\n") + rows.mkString("\n")
  }
}
</code>```

which outputs

```<code>case class Point(x: Double, y: Double)
println(toTable(List(Point(1,2), Point(3,4))))

x       y
1.0     2.0
3.0     4.0
</code>```

Based on Get field names list from case class

Body:
Say I have a method like this:

def getClassFromIterable(iterable: Iterable[Any]): Class[_] = {
  iterable.head.getClass
}

This will get the class of the top of the list, but will fail if the list is empty.

How can I get the class of a passed list that has zero or more elements?

Body:
Supplementing Luis' answer with a reflective solution, consider

import scala.reflect.runtime.universe._

def toTable[A <: Product](ps: List[A])(implicit ev: TypeTag[A]) = {
  val separator = "\t\t"
  ps match {
    case Nil =>
      val header = typeOf[A].members.collect { case m: MethodSymbol if m.isCaseAccessor => m.name }.toList
      header.mkString("", separator , "\n")

    case head :: _ =>
      val header = head.productElementNames.toList
      val rows = ps.map(_.productIterator.mkString(separator))
      header.mkString("", separator, "\n") + rows.mkString("\n")
  }
}

which outputs

case class Point(x: Double, y: Double)
println(toTable(List(Point(1,2), Point(3,4))))

x       y
1.0     2.0
3.0     4.0

Based on Get field names list from case class


问:
Exception won't be caught if I don't debug the application
There are two DLLs, A and B, in A.DLL there is a form class like this:

```<code>namespace AAA
public class AForm: Form
{
  ...
  private void btnOK_Click(object sender, EventArgs e)
  {
      DoSomeSth();
  }
}
</code>```

In B.DLL, there is some code like this

```<code>try
{
   AForm dlg = new AAA.AForm();
   dlg.ShowDialog();
}
catch(Exception ex)
{
   MessageBox.Show(ex.Message);
}
</code>```

There will be exception in the function DoSomeSth after OK button is clicked
When I debug the code using vs2005, the exception could be caught in B.DLL, but if I ran the application directly without debug, the exception won't be caught in B.DLL, what is the reason?

答:
This is a known issue. According to the KB article:

When you run your Windows Forms
  application without using the
  debugger, you use the
  NativeWindow.CallBack method to catch
  the exception and to prevent the
  program from unexpectedly quitting
  (crashing). In the
  NativeWindow.CallBack method, you
  populate the exception message by
  using a standard exception dialog box.

However, if you run your Windows Forms
  application with the debugger, you do
  not catch the exception because you
  use the
  NativeWindow.DebuggableCallBack
  method. When you use the
  NativeWindow.DebuggableCallBack
  method, the just-in-time (JIT)
  debugger stops the application from
  running.

ContentLicense: CC BY-SA 3.0

Body:
There are two DLLs, A and B, in A.DLL there is a form class like this:

namespace AAA
public class AForm: Form
{
  ...
  private void btnOK_Click(object sender, EventArgs e)
  {
      DoSomeSth();
  }
}

In B.DLL, there is some code like this

try
{
   AForm dlg = new AAA.AForm();
   dlg.ShowDialog();
}
catch(Exception ex)
{
   MessageBox.Show(ex.Message);
}

There will be exception in the function DoSomeSth after OK button is clicked
When I debug the code using vs2005, the exception could be caught in B.DLL, but if I ran the application directly without debug, the exception won't be caught in B.DLL, what is the reason?


问:
Change TabBar Items after changing app language from inside of app
I have an app and from inside of it I am changing its language.
Language getting properly updated to other screens by changing UIView appearance.

```<code>Localize.setCurrentLanguage("ar")
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
</code>```

I'm not able to get control back in my tabcontroller file. TabBar is custom created. I checked with awakefromNib() but it is not getting invocated every time. Is there any tab bar method where I can get control when it appears every time or is there any way to change language of tab bar item titles?

答:
After changing app language in your VC create and call function localizeTabBar():

```<code>func localizeTabBar() {
    tabBar.items![0].title = "1tab".localized
    tabBar.items![1].title = "2tab".localized
    tabBar.items![2].title = "3tab".localized
    tabBar.items![3].title = "4tab".localized
}
</code>```

For .localized use this String Extension

Body:
I have an app and from inside of it I am changing its language.
Language getting properly updated to other screens by changing UIView appearance.

Localize.setCurrentLanguage("ar")
        UIView.appearance().semanticContentAttribute = .forceRightToLeft

I'm not able to get control back in my tabcontroller file. TabBar is custom created. I checked with awakefromNib() but it is not getting invocated every time. Is there any tab bar method where I can get control when it appears every time or is there any way to change language of tab bar item titles?

Body:
After changing app language in your VC create and call function localizeTabBar():

func localizeTabBar() {
    tabBar.items![0].title = "1tab".localized
    tabBar.items![1].title = "2tab".localized
    tabBar.items![2].title = "3tab".localized
    tabBar.items![3].title = "4tab".localized
}

For .localized use this String Extension


问:
Import XML files with different structures using SSIS
I have multiple XML files with different structures, yet they all share a specific set of nodes.

My objective is to only import those mutual nodes into an SQL Server table.
How can I proceed, knowing that I can't generate an .Xsd for every type as there are many possible XML files variations?
Thanks in advance.

答:
So what I did as a solution to this particular case was:
1- add a C# script that reads the xml file and keep the common nodes only and save their values to my dts variables.
2- insert into my SQL Server table the variables I just populated.
Both tasks were in a for each loop to go through all the xml files in a specific directory.
Hope it helps!</p>


问:
Why is my program returning a garbage value when k == 0 in the for-loop?
This is a simple C++ program which computes f(x) using a formula for a fixed number of values between 2 given numbers.

There seems to be some problem when k = 0 in the for loop. It is returning a garbage value.

Can anyone tell me why?

Any help is highly appreciated. Thanks in advance.

```<code>#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main ()
{

  int const POINTS = 21;
  double const PI = 3.1416;
  double min, max, increment, dataPoints[21];

  cout << "Enter max value: ";
  cin >> max;

  cout << "Enter min value: ";
  cin >> min;

  increment = (max - min) / (POINTS - 1);

  cout << setw (20) << "X-Value" << "|";
  cout << setw (20) << "Y-Value" << endl;

  double k;
  int l;

  for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
    {
      dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1 / 64) * PI * cos (24.44 * k);
      cout << setw (20) << k << setw (20) << dataPoints[l] << endl;
    }

}

</code>```

Output:

```<code>Enter max value: 4
Enter min value: -4
             X-Value|             Y-Value
                  -4            0.164018
                -3.6          -0.0507715
                -3.2          -0.0881608
                -2.8            0.182492
                -2.4           -0.184497
                  -2           0.0931637
                -1.6           0.0453027
                -1.2            -0.16085
                -0.8            0.195021
                -0.4           -0.130529
       -5.55112e-016       -6.57901e-016
                 0.4            0.130529
                 0.8           -0.195021
                 1.2             0.16085
                 1.6          -0.0453027
                   2          -0.0931637
                 2.4            0.184497
                 2.8           -0.182492
                 3.2           0.0881608
                 3.6           0.0507715
                   4           -0.164018

Process returned 0 (0x0)   execution time : 3.634 s
Press any key to continue.
</code>```

答: Because of rounding error when you increment by 0.2, your k value never gets to be exactly zero -- its off by a little bit.  See What every computer scientist should know about floating point

Body:
This is a simple C++ program which computes f(x) using a formula for a fixed number of values between 2 given numbers.

There seems to be some problem when k = 0 in the for loop. It is returning a garbage value.

Can anyone tell me why?

Any help is highly appreciated. Thanks in advance.

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main ()
{

  int const POINTS = 21;
  double const PI = 3.1416;
  double min, max, increment, dataPoints[21];

  cout << "Enter max value: ";
  cin >> max;

  cout << "Enter min value: ";
  cin >> min;

  increment = (max - min) / (POINTS - 1);

  cout << setw (20) << "X-Value" << "|";
  cout << setw (20) << "Y-Value" << endl;

  double k;
  int l;

  for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
    {
      dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1 / 64) * PI * cos (24.44 * k);
      cout << setw (20) << k << setw (20) << dataPoints[l] << endl;
    }

}

Output:

Enter max value: 4
Enter min value: -4
             X-Value|             Y-Value
                  -4            0.164018
                -3.6          -0.0507715
                -3.2          -0.0881608
                -2.8            0.182492
                -2.4           -0.184497
                  -2           0.0931637
                -1.6           0.0453027
                -1.2            -0.16085
                -0.8            0.195021
                -0.4           -0.130529
       -5.55112e-016       -6.57901e-016
                 0.4            0.130529
                 0.8           -0.195021
                 1.2             0.16085
                 1.6          -0.0453027
                   2          -0.0931637
                 2.4            0.184497
                 2.8           -0.182492
                 3.2           0.0881608
                 3.6           0.0507715
                   4           -0.164018

Process returned 0 (0x0)   execution time : 3.634 s
Press any key to continue.


问:
macOS send keystroke to the active app periodically
I am trying to send a keystroke (command+ shift+ r) to a macOS (Mojave) app called "Dbeaver" every minute as long as DBeaver is the active app. I have tried the following with no effect.

```<code>tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "DBeaver" is in activeApp then
        tell application "System Events" to keystroke "r" using {command down, shift down}

    end if
end tell
</code>```

The script works perfectly fine if its simple like the following:

```<code>activate application "DBeaver"
tell application "System Events" to keystroke "r" using {command down, shift down}
</code>```

答:
I do not have the application you referred to but I tested this following AppleScript code using TextEdit.app and it worked.  Let me know if you run into any errors or issues</p>

```<code>tell application "System Events"
    repeat while (exists of application process "DBeaver")
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell its application process "DBeaver"
                repeat while frontmost
                    keystroke "r" using {command down, shift down}
                    delay 60
                end repeat
            end tell
        end if
    end repeat
end tell
</code>```

Body:
I am trying to send a keystroke (command+ shift+ r) to a macOS (Mojave) app called "Dbeaver" every minute as long as DBeaver is the active app. I have tried the following with no effect.

tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "DBeaver" is in activeApp then
        tell application "System Events" to keystroke "r" using {command down, shift down}

    end if
end tell

The script works perfectly fine if its simple like the following:

activate application "DBeaver"
tell application "System Events" to keystroke "r" using {command down, shift down}

Body:
I do not have the application you referred to but I tested this following AppleScript code using TextEdit.app and it worked.  Let me know if you run into any errors or issues

tell application "System Events"
    repeat while (exists of application process "DBeaver")
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell its application process "DBeaver"
                repeat while frontmost
                    keystroke "r" using {command down, shift down}
                    delay 60
                end repeat
            end tell
        end if
    end repeat
end tell


问:
Cypress: How to wait and then read innertext of an element that will only appear somewhere between 30 seconds to 120 seconds
I have a requirement whereby once I sign-up for a user registration my ID gets generated in the back-end and the web page shows that ID nearly after somewhere between 30 seconds to 120 seconds.

So when I use:

```<code>cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
})
</code>```

I may not have it just after the sign-up is complete, so I need to wait in a loop check every 10 seconds or so until the User Id is displayed as part of the selector 'header > p'

Tried different looping logics etc., incl. wait and check, but due to async nature of the requests the variable scoping is not working for me, hence tried cy.wrap('false').as('found') and then tried to use that in cy.get(this.found), but once that i need to chain that into .then.

So is there an easy way to store a global variable value using command.js perhaps? Which I can update in

```<code>while(!variableFound) {
cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
    if(text.length > 0) {
        variableFound = true
    } else {
        variableFound = false
    }
})
}
</code>```

Finally tried the following code from a forum, even when User Id is available inside header>p tag it keeps failing to identify that.

```<code>    let found = false
    let count=0
    while (!found) {

        const nonExistent = Cypress.$('header > p')

        // this is always evaluating to 0 even when p is become available and contains has the text
        cy.log("Length: " + nonExistent.length)

        if (!nonExistent.length) {
            cy.visit("/profile/")
            found = false
            count=count+1
            cy.wait(5000)
            cy.visit("/dashboard/")

            if(count==18) {
                found = true
                cy.log('Element not found after 18 attempts.Exit from loop!!!')
            }
        } else {
            found = true
            cy.get('header > p').invoke('text').then((useridtext) => {
                cy.log("User Id: " + useridtext)
            })
        }
    }
</code>```

Any advise is sincerely appreciated. Many thanks.

答:
The problem is not all command chains apply the automatic retry mechanism as you might expect.

So cy.get('header > p').invoke('text') retries the first part (looking for the element) but as soon as the element is present, it grabs whatever text it has at that time.

The cy.contains() command is better for retrying until both the element and the right content is present.

Since it can take up to 120 seconds, you have to extend the retry timeout.

Ref cy.contains(), the 4th pattern .contains(selector, content, options).

Some ideas,

If you know what user id will be sent

Do this if you always get a known user id, of if you can stub the call and return a value for testing.

cy.contains('header > p', 'expectedUserId', { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )
```

<hr>

<p><strong>If you only know the general form of user id that will be sent</strong></p>

<p>Use a <strong>regexp</strong> if you don't know the exact user id, but know it's form (e.g always a number).</p>

<pre class="lang-js prettyprint-override"><code>cy.contains('header > p', /\d+/, { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )
</code>```

If you know that the element will be empty before user id arrives

Use a regexp for non-empty content.

cy.contains('header > p', /.+/, { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )
```

Body:
I have a requirement whereby once I sign-up for a user registration my ID gets generated in the back-end and the web page shows that ID nearly after somewhere between 30 seconds to 120 seconds.

So when I use:

cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
})

I may not have it just after the sign-up is complete, so I need to wait in a loop check every 10 seconds or so until the User Id is displayed as part of the selector 'header > p'

Tried different looping logics etc., incl. wait and check, but due to async nature of the requests the variable scoping is not working for me, hence tried cy.wrap('false').as('found') and then tried to use that in cy.get(this.found), but once that i need to chain that into .then.

So is there an easy way to store a global variable value using command.js perhaps? Which I can update in

while(!variableFound) {
cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
    if(text.length > 0) {
        variableFound = true
    } else {
        variableFound = false
    }
})
}

Finally tried the following code from a forum, even when User Id is available inside header>p tag it keeps failing to identify that.

    let found = false
    let count=0
    while (!found) {

        const nonExistent = Cypress.$('header > p')

        // this is always evaluating to 0 even when p is become available and contains has the text
        cy.log("Length: " + nonExistent.length)

        if (!nonExistent.length) {
            cy.visit("/profile/")
            found = false
            count=count+1
            cy.wait(5000)
            cy.visit("/dashboard/")

            if(count==18) {
                found = true
                cy.log('Element not found after 18 attempts.Exit from loop!!!')
            }
        } else {
            found = true
            cy.get('header > p').invoke('text').then((useridtext) => {
                cy.log("User Id: " + useridtext)
            })
        }
    }

Any advise is sincerely appreciated. Many thanks.

Body:
The problem is not all command chains apply the automatic retry mechanism as you might expect.

So cy.get('header > p').invoke('text') retries the first part (looking for the element) but as soon as the element is present, it grabs whatever text it has at that time.

The cy.contains() command is better for retrying until both the element and the right content is present.

Since it can take up to 120 seconds, you have to extend the retry timeout.

Ref cy.contains(), the 4th pattern .contains(selector, content, options).

Some ideas,

If you know what user id will be sent

Do this if you always get a known user id, of if you can stub the call and return a value for testing.

cy.contains('header > p', 'expectedUserId', { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )

If you only know the general form of user id that will be sent

Use a regexp if you don't know the exact user id, but know it's form (e.g always a number).

cy.contains('header > p', /\d+/, { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )

If you know that the element will be empty before user id arrives

Use a regexp for non-empty content.

cy.contains('header > p', /.+/, { timeout: 120000 })
  .invoke('text')
  .then(text => cy.log("User Id: " + text) )


问:
create tuple of nth element in the cartesian product of input vectors
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out
```

<p>This works great:</p>

<pre class="lang-py prettyprint-override"><code>a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)
</code>```

```<code>[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]
</code>```

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}
```

Can someone help me with the template magic required to construct the tuple using the above formula?

答:
First, let's just auto-deduce the function's return type for simplicity.

Next, index-sequences are neat. With them, it can be done.

With C++20, we could get the indices from the sequence in a lambda. Before that, we need an extra function.

Finally, we have to start creating the indices from the end, either storing the indices and then using them in reverse order or reversing the resulting tuple.

```<code>template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    auto x = std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(tuple)[f(std::get<(sizeof...(Ns)) - Ns - 1>(tuple).size())]...);
    return std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(x)...);
}

template<class... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), std::make_index_sequence<sizeof...(vs)>());
}
</code>```

Simpler alternative for the inner function using an array of indices:

```<code>template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    std::size_t Is[] = { f(std::get<sizeof...(Ns) - Ns - 1>(tuple).size())... , 0};
    return std::forward_as_tuple(std::get<Ns>(tuple)[sizeof...(Ns) - Ns - 1]...);
}
</code>```

Body:
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out

This works great:

a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)

[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}

Can someone help me with the template magic required to construct the tuple using the above formula?

Body:
First, let's just auto-deduce the function's return type for simplicity.

Next, index-sequences are neat. With them, it can be done.

With C++20, we could get the indices from the sequence in a lambda. Before that, we need an extra function.

Finally, we have to start creating the indices from the end, either storing the indices and then using them in reverse order or reversing the resulting tuple.

template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    auto x = std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(tuple)[f(std::get<(sizeof...(Ns)) - Ns - 1>(tuple).size())]...);
    return std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(x)...);
}

template<class... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), std::make_index_sequence<sizeof...(vs)>());
}

Simpler alternative for the inner function using an array of indices:

template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    std::size_t Is[] = { f(std::get<sizeof...(Ns) - Ns - 1>(tuple).size())... , 0};
    return std::forward_as_tuple(std::get<Ns>(tuple)[sizeof...(Ns) - Ns - 1]...);
}


问:
Eliminate duplicates in Array
(Eliminate duplicates) Write a method that returns a new array by eliminating the
duplicate values in the array using the following method header:

```<code>public static int[] eliminateDuplicates(int[] list)
</code>```

Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers separated by exactly one space. Here is a sample run of the
program:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

```<code>package bucky;

import java.util.Scanner;

public class Arrays {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");

        int[] list = new int[10];

        for (int i = 0; i < list.length; i++) {
            list[i] = in.nextInt();
        }
        eliminateDuplicates(list);

        System.out.print("The distinct numbers are: ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]);
        }
    }

    public static int[] eliminateDuplicates(int[] list) {

        int count = 0;
        int j = 0;
        int[] nArray = new int[list.length];
        while (j < list.length) {
            for (int i = 1; i < list.length; i++) {
                int low = list[j];
                if (list[i] == low) {
                    count++;
                } else {
                    nArray[i] = low;
                }
            }
            j++;
        }
        return nArray;
    }
}
</code>```

答:
Array can be simply converted to a HashSet which eliminates duplicate automatically.

Set list2 = Arrays.stream(list).boxed().collect(Collectors.toSet());
System.out.print("The distinct numbers are: " + list2);

Title: Eliminate duplicates in Array

Body:
(Eliminate duplicates) Write a method that returns a new array by eliminating the
duplicate values in the array using the following method header:

public static int[] eliminateDuplicates(int[] list)

Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers separated by exactly one space. Here is a sample run of the
program:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

package bucky;

import java.util.Scanner;

public class Arrays {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");

        int[] list = new int[10];

        for (int i = 0; i < list.length; i++) {
            list[i] = in.nextInt();
        }
        eliminateDuplicates(list);

        System.out.print("The distinct numbers are: ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]);
        }
    }

    public static int[] eliminateDuplicates(int[] list) {

        int count = 0;
        int j = 0;
        int[] nArray = new int[list.length];
        while (j < list.length) {
            for (int i = 1; i < list.length; i++) {
                int low = list[j];
                if (list[i] == low) {
                    count++;
                } else {
                    nArray[i] = low;
                }
            }
            j++;
        }
        return nArray;
    }
}


问:
Automapper refer to existing subtype mapping in custom member mapping
My database entities look as follows (redacted down to relevant information):

public class Task
{
    public Guid? StatusId { get; set; }
    public Status Status { get; set; }

    public DateTime? StatusLastModified { get; set; }
}

public class Status
{
    public string Name { get; set; }
    // several other properties redacted
}
```

<p>Tasks initially have no status (StatusLastModified is then also null), and once the first status has been assigned, tasks will always have a status (and StatusLastModified is then also not null). </p>

<p>For the sake of this question, you can assume that these properties will always both be null or not-null, I don't need to account for anomalies where one is null and the other isn't.</p>

<p>For my DTOs, I want to map this to the following structure:</p>

<pre class="lang-cs prettyprint-override"><code>public struct TaskDto
{
    public TaskStatusDto? Status { get; set; }
}

public struct TaskStatusDto
{
    public DateTime Timestamp { get; set; } // maps from Task.StatusLastModified
    public StatusDto Status { get; set; } // maps from Task.Status
}

public struct StatusDto
{
    public string Name { get; set; }
    // and all the other properties from the Status entity
}
</code>```

The goal here is that my TaskDto only has an underlying TaskStatusDto when there is an actual status, and otherwise it should be null. This is helpful as it negates the need to constantly null check both the status object and the last modified date.

However, I am struggling to configure this mapping in Automapper. I have created the mapping between Status and StatusDto:

configuration
     .CreateMap<Status, StatusDto>();
```

<p>My real mapping is more complicated but it's also proven to work so you can assume that this is a valid and working mapping.</p>

<p>The problem I'm faced with is how I can refer to this mapping when creating the custom mapping between <code>Task</code> and <code>TaskDto</code>. I've currently tried the following:</p>

<pre class="lang-cs prettyprint-override"><code>configuration
    .CreateMap<Task, TaskDto>()
    .ForMember(
            dto => dto.Status,
            opt => opt.MapFrom(entity =>
                entity.Status == null
                    ? null as TaskStatusDto?
                    : new TaskStatusDto()
                    {
                        TimeStamp = entity.StatusLastModified.Value,
                        Status = // ??? make me a StatusDto from entity.Status
                    }
        ));
</code>```

The part I don't know how to fill in is the comment. I have access to the original entity (entity.Status), but I don't know how to tell Automapper to convert this object to a StatusDto according to a mapping that it should already know.

My approach also feels more contrived than it should be, but I don't know how to otherwise introduce this intermediary TaskStatusDto object if it isn't backed by an actual entity in my source data.

A small footnote, unsure if relevant: I am using Heroic.Automapper, which means that the TaskDto and StatusDto maps are being configured in separate locations (i.e. inside the TaskDto and StatusDto class, respectively) and the Heroic framework will combine all these maps at runtime.

public class TaskDto : IMapFrom<Task>, IHaveCustomMappings
{
     public void CreateMappings(IMapperConfigurationExpression configuration)
     {
         // mapping from Task to TaskDto
     }
}

public class StatusDto : IMapFrom<Status>, IHaveCustomMappings
{
     public void CreateMappings(IMapperConfigurationExpression configuration)
     {
         // mapping from Status to StatusDto
     }
}
```

However, as far as I understand it, the setting up of the map itself isn't Heroic-specific and should be purely Automapper syntax.

答:
I think a cleaner solution would be to create your own CustomResolver:

```<code>public class TaskStatusDtoResolver : IValueResolver<Task, TaskDto, TaskStatusDto?>
{
    public TaskStatusDto? Resolve(Task source, TaskDto destination, TaskStatusDto? member, ResolutionContext context)
    {
        if (source.Status == null)
        {
            return null;
        }

        return new TaskStatusDto
        {
            Status = context.Mapper.Map<StatusDto>(source.Status),
            Timestamp = source.StatusLastModified.Value
        };
    }
}
</code>```

And you can use the following configuration:

```<code>cfg.CreateMap<Status, StatusDto>();
cfg.CreateMap<Task, TaskDto>()
    .ForMember(dest => dest.Status, opt => opt.MapFrom<TaskStatusDtoResolver>());
</code>```

See the working example here

Alternatively you can define all the mappings in the configuration:

```<code>var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Status, StatusDto>();
    cfg.CreateMap<Task, TaskDto>().ForMember(
         dest => dest.Status,
         src => src.MapFrom((task, taskDto, member, context) =>
         {
             return task.Status == null ? null as TaskStatusDto? : new TaskStatusDto()
             {
                 Timestamp = task.StatusLastModified.Value,
                 Status = context.Mapper.Map<StatusDto>(task.Status)
             };
         }
     ));
});
</code>```

Body:
My database entities look as follows (redacted down to relevant information):

public class Task
{
    public Guid? StatusId { get; set; }
    public Status Status { get; set; }

    public DateTime? StatusLastModified { get; set; }
}

public class Status
{
    public string Name { get; set; }
    // several other properties redacted
}

Tasks initially have no status (StatusLastModified is then also null), and once the first status has been assigned, tasks will always have a status (and StatusLastModified is then also not null).

For the sake of this question, you can assume that these properties will always both be null or not-null, I don't need to account for anomalies where one is null and the other isn't.

For my DTOs, I want to map this to the following structure:

public struct TaskDto
{
    public TaskStatusDto? Status { get; set; }
}

public struct TaskStatusDto
{
    public DateTime Timestamp { get; set; } // maps from Task.StatusLastModified
    public StatusDto Status { get; set; } // maps from Task.Status
}

public struct StatusDto
{
    public string Name { get; set; }
    // and all the other properties from the Status entity
}

The goal here is that my TaskDto only has an underlying TaskStatusDto when there is an actual status, and otherwise it should be null. This is helpful as it negates the need to constantly null check both the status object and the last modified date.

However, I am struggling to configure this mapping in Automapper. I have created the mapping between Status and StatusDto:

configuration
     .CreateMap<Status, StatusDto>();

My real mapping is more complicated but it's also proven to work so you can assume that this is a valid and working mapping.

The problem I'm faced with is how I can refer to this mapping when creating the custom mapping between Task and TaskDto. I've currently tried the following:

configuration
    .CreateMap<Task, TaskDto>()
    .ForMember(
            dto => dto.Status,
            opt => opt.MapFrom(entity =>
                entity.Status == null
                    ? null as TaskStatusDto?
                    : new TaskStatusDto()
                    {
                        TimeStamp = entity.StatusLastModified.Value,
                        Status = // ??? make me a StatusDto from entity.Status
                    }
        ));

The part I don't know how to fill in is the comment. I have access to the original entity (entity.Status), but I don't know how to tell Automapper to convert this object to a StatusDto according to a mapping that it should already know.

My approach also feels more contrived than it should be, but I don't know how to otherwise introduce this intermediary TaskStatusDto object if it isn't backed by an actual entity in my source data.

A small footnote, unsure if relevant: I am using Heroic.Automapper, which means that the TaskDto and StatusDto maps are being configured in separate locations (i.e. inside the TaskDto and StatusDto class, respectively) and the Heroic framework will combine all these maps at runtime.

public class TaskDto : IMapFrom<Task>, IHaveCustomMappings
{
     public void CreateMappings(IMapperConfigurationExpression configuration)
     {
         // mapping from Task to TaskDto
     }
}

public class StatusDto : IMapFrom<Status>, IHaveCustomMappings
{
     public void CreateMappings(IMapperConfigurationExpression configuration)
     {
         // mapping from Status to StatusDto
     }
}

However, as far as I understand it, the setting up of the map itself isn't Heroic-specific and should be purely Automapper syntax.

Body:
I think a cleaner solution would be to create your own CustomResolver:

public class TaskStatusDtoResolver : IValueResolver<Task, TaskDto, TaskStatusDto?>
{
    public TaskStatusDto? Resolve(Task source, TaskDto destination, TaskStatusDto? member, ResolutionContext context)
    {
        if (source.Status == null)
        {
            return null;
        }

        return new TaskStatusDto
        {
            Status = context.Mapper.Map<StatusDto>(source.Status),
            Timestamp = source.StatusLastModified.Value
        };
    }
}

And you can use the following configuration:

cfg.CreateMap<Status, StatusDto>();
cfg.CreateMap<Task, TaskDto>()
    .ForMember(dest => dest.Status, opt => opt.MapFrom<TaskStatusDtoResolver>());

See the working example here

Alternatively you can define all the mappings in the configuration:

var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Status, StatusDto>();
    cfg.CreateMap<Task, TaskDto>().ForMember(
         dest => dest.Status,
         src => src.MapFrom((task, taskDto, member, context) =>
         {
             return task.Status == null ? null as TaskStatusDto? : new TaskStatusDto()
             {
                 Timestamp = task.StatusLastModified.Value,
                 Status = context.Mapper.Map<StatusDto>(task.Status)
             };
         }
     ));
});


问:
Java Sort after GroupBy
How can I sort these into a SortedMap instead of just a Map?</p>

```<code>    class Person {
        String name;
        double weight;

        public Person(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public double getWeight() {
            return this.weight;
        }
    }
    List<Person> people = Arrays.asList(
            new Person("Alex", 150.0),
            new Person("Courtney", 120.0),
            new Person("Billy", 180.0)
            );

    Map<Double, List<Person>> grouped = people.stream()
            .collect(Collectors.groupingBy(Person::getWeight));
</code>```

答:
You can use the overloaded groupingBy() that takes a supplier:

```<code>SortedMap<Double, List<Person>> grouped = people.stream()
        .collect(Collectors.groupingBy(
                Person::getWeight,
                TreeMap::new,
                Collectors.toList()));
</code>```

Title: Java Sort after GroupBy

Body:
How can I sort these into a SortedMap instead of just a Map?

    class Person {
        String name;
        double weight;

        public Person(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public double getWeight() {
            return this.weight;
        }
    }
    List<Person> people = Arrays.asList(
            new Person("Alex", 150.0),
            new Person("Courtney", 120.0),
            new Person("Billy", 180.0)
            );

    Map<Double, List<Person>> grouped = people.stream()
            .collect(Collectors.groupingBy(Person::getWeight));

Body:
You can use the overloaded groupingBy() that takes a supplier:

SortedMap<Double, List<Person>> grouped = people.stream()
        .collect(Collectors.groupingBy(
                Person::getWeight,
                TreeMap::new,
                Collectors.toList()));


问:
issues with angular to call api input via parameters
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

```<code>import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}
</code>```

as well the is my app.component.html

```<code><h1> test app</h1>
<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>
<hr>
phone{{phone}}
</code>```

https://stackblitz.com/edit/angular-dryp3b

答:
I realized you are handling your response incorrectly. So I modified the code as you can see below.

I checked jsonplacerholde.typicode.com API and realized that users' service doesn't receive a numeric value. The users' service returns 10 users, therefore I removed id from the HTTP request.

app.component.ts

```<code>getsearcha(){
  // this service doesn't receive a numeric value
  this._http.get('https://jsonplaceholder.typicode.com/users)
  .subscribe(
    (data: any) => {
      // data is an array of users, so I get the first element with [0]
      this.results = data;
      this.phone = this.results[0].phone
    })
}
</code>```

app.component.html

```<code><h1>
 test app
</h1>
<input type="text" [(ngModel)]="id">

<button (click)="getsearcha()">Click</button>
<hr>
phone {{phone}}
</code>```

Body:
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}

as well the is my app.component.html

 test app

<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>

phone{{phone}}

https://stackblitz.com/edit/angular-dryp3b

Body:
I realized you are handling your response incorrectly. So I modified the code as you can see below.

I checked jsonplacerholde.typicode.com API and realized that users' service doesn't receive a numeric value. The users' service returns 10 users, therefore I removed id from the HTTP request.

app.component.ts

getsearcha(){
  // this service doesn't receive a numeric value
  this._http.get('https://jsonplaceholder.typicode.com/users)
  .subscribe(
    (data: any) => {
      // data is an array of users, so I get the first element with [0]
      this.results = data;
      this.phone = this.results[0].phone
    })
}

app.component.html

<h1>
 test app
</h1>
<input type="text" [(ngModel)]="id">

<button (click)="getsearcha()">Click</button>
<hr>
phone {{phone}}


问:
Update nested Firestore value (subcollection) using redux-saga-firebase
I'm trying to build a football office pool app and I'm having trouble saving the weekly picks.  I'm using redux-saga-firebase for my calls.  I've added a helper to go with it, but it's mostly just for error handling.  I think my issue is figuring out the right data structure and how to update it.

```<code>export function* saveWeeklyPicks({ payload }) {
  const user = yield select(getUserProfile);
  const league = yield select(getCurrentLeague);
  const userUid = user.uid;
  const leagueUid = league.uid;

  yield call(
    callFirestore, {
      fsAction: 'updateDocument',
      // TODO: determine week dynamically
      coll: `leagues/${leagueUid}`,
      params: {
        [userUid]: {
          week1: payload.picks,
        },
      },
      successAction: t.SAVE_PICKS_SUCCESS,
      failAction: t.SAVE_PICKS_FAILURE,
    }
  );
}
</code>```

I've also tried this, but it just errors (No document to update):

```<code>  coll: `leagues/${leagueUid}/${userUid}/week1`,
  params: {
      week1: payload.picks,
  }
</code>```

And my helper:

```<code>export function* callFirestore({ fsAction, coll, params, successAction, failAction }) {
    try {
    const response = yield call(
            rsf.firestore[fsAction],
            coll,
            params
    );
    console.log('FIRESTORE SUCCESS RESPONSE: ', response);
    yield put({
      type: successAction,
      payload: response,
      params,
    });
  } catch (err) {
    console.log('FIRESTORE ERROR: ', err);
    yield put({
      type: failAction,
      payload: err,
    });
  }
}
</code>```

So in my db, I have a leagues tables, that I access with the leagueUid, and that works fine, and the above call will replace the ${userUid}/week1 value correctly.  However, it wipes out all the other data alongside it (week2, week3, etc.).  What is the right way to save my picks to Firestore?

答:
Turns out I needed to use options: { merge: true }

```<code>    yield call(
    callFirestore, {
      fsAction: 'updateDocument',
      // TODO: determine week dynamically
      coll: `leagues/${leagueUid}`,
      params: {
        [userUid]: {
          week1: payload.picks,
        },
      },
      options: { merge: true }
      successAction: t.SAVE_PICKS_SUCCESS,
      failAction: t.SAVE_PICKS_FAILURE,
    }
  );
</code>```

Body:
I'm trying to build a football office pool app and I'm having trouble saving the weekly picks.  I'm using redux-saga-firebase for my calls.  I've added a helper to go with it, but it's mostly just for error handling.  I think my issue is figuring out the right data structure and how to update it.

export function* saveWeeklyPicks({ payload }) {
  const user = yield select(getUserProfile);
  const league = yield select(getCurrentLeague);
  const userUid = user.uid;
  const leagueUid = league.uid;

  yield call(
    callFirestore, {
      fsAction: 'updateDocument',
      // TODO: determine week dynamically
      coll: `leagues/${leagueUid}`,
      params: {
        [userUid]: {
          week1: payload.picks,
        },
      },
      successAction: t.SAVE_PICKS_SUCCESS,
      failAction: t.SAVE_PICKS_FAILURE,
    }
  );
}

I've also tried this, but it just errors (No document to update):

  coll: `leagues/${leagueUid}/${userUid}/week1`,
  params: {
      week1: payload.picks,
  }

And my helper:

export function* callFirestore({ fsAction, coll, params, successAction, failAction }) {
    try {
    const response = yield call(
            rsf.firestore[fsAction],
            coll,
            params
    );
    console.log('FIRESTORE SUCCESS RESPONSE: ', response);
    yield put({
      type: successAction,
      payload: response,
      params,
    });
  } catch (err) {
    console.log('FIRESTORE ERROR: ', err);
    yield put({
      type: failAction,
      payload: err,
    });
  }
}

So in my db, I have a leagues tables, that I access with the leagueUid, and that works fine, and the above call will replace the ${userUid}/week1 value correctly.  However, it wipes out all the other data alongside it (week2, week3, etc.).  What is the right way to save my picks to Firestore?

Body:
Turns out I needed to use options: { merge: true }

    yield call(
    callFirestore, {
      fsAction: 'updateDocument',
      // TODO: determine week dynamically
      coll: `leagues/${leagueUid}`,
      params: {
        [userUid]: {
          week1: payload.picks,
        },
      },
      options: { merge: true }
      successAction: t.SAVE_PICKS_SUCCESS,
      failAction: t.SAVE_PICKS_FAILURE,
    }
  );


问:
Access page controls in jquery
I have a web application in VS 2008. I used jquery for validation of different Forms and used it for other purposes. In VS 2008 I get the IDs of page controls in jquery like Ctl001_.... , but now I have upgraded the application to VS 2010 and now all my page controls are giving error in jquery because its changed its ID there as ContentBody_....., I can not convert all these to the new prefix ContentBody_.... because on the server my project runs on .Net Framework 3.5 and there the IDs are with the Prefix of Ctl001_....,
can any one tell me a way that I can easily get control's ID in jquery without depending on the .Net Framework.

any help would be greatly appreciated.

答: You should use the ClientID property of the asp controls. $('#<%=textBox1.ClientID%>') would return $('#ctl001_textBox1') or whatever asp decides to rename it.

Title: Access page controls in jquery


问:
CGImage from images stored on iCloud look wrong
I'm extracting pixel colors from a CGImage using the code described in this answer.

However, I just realized that if I load an image that was created on another device, the pixels values look wrong. The first obvious problem is that the alpha is gone. The CGImageAlphaInfo reports .noneSkipLast, but I know the image is RGBA. If I read it from the same device it was created, it looks fine. The second problem is that there is some color bleeding, as if the image had been resized. Perhaps is being compressed or something.

Here's an example:

Source image is this watermelon, 12x12

It was created on my iPad. But if I load it on my iPhone through iCloud using that code I linked, I get this:

The alpha channel is gone, and colors bleed.

If from the same iPhone I send the little watermelon to my Mac using Airdrop, and send it back using Airdrop again (so it is supposedly the same image!), and load it now, I get the correct image:

(dark brown areas is where alpha is 0)

If you have a couple of iOS device with iCloud enabled, you can reproduce this behavior in this app: http://swiftpixels.endavid.com
where I'm using that code to read pixel colors.

What could be the difference between those images? How can I read the correct image from iCloud? Should I look for hints in UIImage instead of CGImage?

Any clues? Thanks!

Update

For reference, I'm reading the image using a UIImagePickerController, using this code:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            loadImageInMemory(image)
        }
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

    fileprivate func loadImageInMemory(_ image: UIImage) {
       /// skipping some preparation
       guard let cgImage = image.cgImage else {
          return
       }
       /// getImageData is a function like getPixelColor linked above,
       /// but for a Rect
       self.imageData = cgImage.getImageData(rect, width, height)
    }
```

I also found this question which may be related: UIImagePickerController and iCloud photos

As Rob suggested in the comments below, I changed the Photos settings in my phone to "Download and Keep Originals" (instead of "Optimize iPhone Storage"), and that fixes the problem. So I guess the question is why iCloud tries to compress a PNG image that it's just 1,355 bytes, and whether it's possible to access the original image from the UIImagePickerController

答:
In the Settings app, under “Photos” there is an “Optimize iPhone Storage” vs “Download and Keep Originals” option. The latter should synchronize the photos library without altering the images in any way.

It seems Airdrop can access the original image, though.

Airdrop is not relying upon photo library iCloud synchronization to send the image. That's why the asset makes it across, unaltered.

How can I make my app access the original as well?

It comes down to whether you really want to use the Photos library to synchronize your assets. This seems especially true as many people may not choose to sync their huge Photos library to iCloud at all. I'm not sure you want to rely upon that.

You might want to just use CloudKit yourself rather than relying upon the Photos library. Perhaps you should have an option in the app so a user can choose to use iCloud storage at all, and if so, do the iCloud storage within your app rather than relying upon the Photos library.

Body:
I'm extracting pixel colors from a CGImage using the code described in this answer.

However, I just realized that if I load an image that was created on another device, the pixels values look wrong. The first obvious problem is that the alpha is gone. The CGImageAlphaInfo reports .noneSkipLast, but I know the image is RGBA. If I read it from the same device it was created, it looks fine. The second problem is that there is some color bleeding, as if the image had been resized. Perhaps is being compressed or something.

Here's an example:

Source image is this watermelon, 12x12

It was created on my iPad. But if I load it on my iPhone through iCloud using that code I linked, I get this:

The alpha channel is gone, and colors bleed.

If from the same iPhone I send the little watermelon to my Mac using Airdrop, and send it back using Airdrop again (so it is supposedly the same image!), and load it now, I get the correct image:

(dark brown areas is where alpha is 0)

If you have a couple of iOS device with iCloud enabled, you can reproduce this behavior in this app: http://swiftpixels.endavid.com
where I'm using that code to read pixel colors.

What could be the difference between those images? How can I read the correct image from iCloud? Should I look for hints in UIImage instead of CGImage?

Any clues? Thanks!

Update

For reference, I'm reading the image using a UIImagePickerController, using this code:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            loadImageInMemory(image)
        }
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

    fileprivate func loadImageInMemory(_ image: UIImage) {
       /// skipping some preparation
       guard let cgImage = image.cgImage else {
          return
       }
       /// getImageData is a function like getPixelColor linked above,
       /// but for a Rect
       self.imageData = cgImage.getImageData(rect, width, height)
    }

I also found this question which may be related: UIImagePickerController and iCloud photos

As Rob suggested in the comments below, I changed the Photos settings in my phone to "Download and Keep Originals" (instead of "Optimize iPhone Storage"), and that fixes the problem. So I guess the question is why iCloud tries to compress a PNG image that it's just 1,355 bytes, and whether it's possible to access the original image from the UIImagePickerController


问:
Wordpress stylesheet not loading
SOLUTION

The problem was that I didn't include the header on index.php

```<code><?php
    get_header();
?>
</code>```

I added this on the first line of index.php, removing the opening  and  tags and it started working.

ORIGINAL POST

I know this has been posted about already, but none of the solutions I try seem to be working.

I am trying to load a stylesheet for my wordpress theme, but it doesn't seem to be working. My stylesheet is named style.css and it resides in the root folder (the theme folder), alongside index.php, header.php, footer.php and functions.php.

Edit: Using the firefox debugger shows that the stylesheet is definitely not loading. The style editor section gives me a, "This page has no stylesheet."

Here are the contents of those files:

index.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css"/>
</head>
<body>

</body>
</html>
</code>```

style.css

```<code>body{
    background-color: green;
    background: green;
}
</code>```

header.php

```<code><!DOCTYPE html>
<html>
<head>
    <?php wp_head();?>
</head>
</html>
</code>```

footer.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <footer class="site-footer"></footer>
    <?php wp_footer(); ?>
</body>
</html>
</code>```

functions.php

```<code><?php
    function load_css(){
        wp_enqueue_style('styles',get_stylesheet_uri());
    }
    add_action('wp_enqueue_scripts', 'load_css');
?>
</code>```

答:
Your templates are being used incorrectly. You should not be starting and ending a complete HTML document in each of these files.

Template Hierarchy

WordPress will compose a page for you by using the sub-templates header.php at the top, footer.php at the bottom, and with the appropriate template in between. Very important to note the template hierarchy in WordPress. Different template parts will be called for based on which view is being rendered. Any good theme has a variety of templates for different contexts and purposes. Read: https://developer.wordpress.org/themes/basics/template-hierarchy/.

Example

Your blog will be rendered like this:

```<code>header.php

index.php

footer.php
</code>```

A single blog post will use this:

```<code>header.php

single.php

footer.php
</code>```

A page will use this:

```<code>header.php

page.php

footer.php
</code>```

etc...

Theming

A good idea is to take a look at the contents of these files in a default WordPress theme, note how the document is started in header.php, and is closed in footer.php. Follow this and your stylesheet will be enqueued as expected. More reading on themes: https://developer.wordpress.org/themes/getting-started/what-is-a-theme/

Title: Wordpress stylesheet not loading

Body:
SOLUTION

The problem was that I didn't include the header on index.php

<?php
    get_header();
?>

I added this on the first line of index.php, removing the opening  and  tags and it started working.

ORIGINAL POST

I know this has been posted about already, but none of the solutions I try seem to be working.

I am trying to load a stylesheet for my wordpress theme, but it doesn't seem to be working. My stylesheet is named style.css and it resides in the root folder (the theme folder), alongside index.php, header.php, footer.php and functions.php.

Edit: Using the firefox debugger shows that the stylesheet is definitely not loading. The style editor section gives me a, "This page has no stylesheet."

Here are the contents of those files:

index.php

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css"/>

style.css

body{
    background-color: green;
    background: green;
}

header.php

<!DOCTYPE html>

    <?php wp_head();?>

footer.php

<!DOCTYPE html>

    <meta charset="UTF-8">

    <?php wp_footer(); ?>

functions.php

<?php
    function load_css(){
        wp_enqueue_style('styles',get_stylesheet_uri());
    }
    add_action('wp_enqueue_scripts', 'load_css');
?>

Body:
Your templates are being used incorrectly. You should not be starting and ending a complete HTML document in each of these files.

Template Hierarchy

WordPress will compose a page for you by using the sub-templates header.php at the top, footer.php at the bottom, and with the appropriate template in between. Very important to note the template hierarchy in WordPress. Different template parts will be called for based on which view is being rendered. Any good theme has a variety of templates for different contexts and purposes. Read: https://developer.wordpress.org/themes/basics/template-hierarchy/.

Example

Your blog will be rendered like this:

header.php

index.php

footer.php

A single blog post will use this:

header.php

single.php

footer.php

A page will use this:

header.php

page.php

footer.php

etc...

Theming

A good idea is to take a look at the contents of these files in a default WordPress theme, note how the document is started in header.php, and is closed in footer.php. Follow this and your stylesheet will be enqueued as expected. More reading on themes: https://developer.wordpress.org/themes/getting-started/what-is-a-theme/


问:
How do I create a circular (endless) RecyclerView?
I am trying to make my RecyclerView loop back to the start of my list.

I have searched all over the internet and have managed to detect when I have reached the end of my list, however I am unsure where to proceed from here.

This is what I am currently using to detect the end of the list (found here):

```<code> @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        visibleItemCount = mLayoutManager.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
                loading = false;
                Log.v("...", ""+visibleItemCount);
            }
        }
 }
</code>```

When scrolled to the end, I would like to views to be visible while the displaying data from the top of the list or when scrolled to the top of the list I would display data from the bottom of the list.

For example:

View1 View2 View3 View4 View5

View5 View1 View2 View3 View4

答:
I have created a LoopingLayoutManager that fixes this issue.

It works without having to modify the adapter, which allows for greater flexibility and reusability.

It comes fully featured with support for:

Vertical and Horizontal Orientations

LTR and RTL

ReverseLayout for both orientations, as well as LTR, and RTL

Public functions for finding items and positions

Public functions for scrolling programmatically

Snap Helper support

Accessibility (TalkBack and Voice Access) support

And it is hosted on maven central, which means you just need to add it as a dependency in your build.gradle file:

```<code>dependencies {
    implementation 'com.github.beksomega:loopinglayout:0.3.1'
}
</code>```

and change your LinearLayoutManager to a LoopingLayoutManager.

It has a suite of 132 unit tests that make me confident it's stable, but if you find any bugs please put up an issue on the github!

I hope this helps!

Body:
I am trying to make my RecyclerView loop back to the start of my list.

I have searched all over the internet and have managed to detect when I have reached the end of my list, however I am unsure where to proceed from here.

This is what I am currently using to detect the end of the list (found here):

 @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        visibleItemCount = mLayoutManager.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
                loading = false;
                Log.v("...", ""+visibleItemCount);
            }
        }
 }

When scrolled to the end, I would like to views to be visible while the displaying data from the top of the list or when scrolled to the top of the list I would display data from the bottom of the list.

For example:

View1 View2 View3 View4 View5

View5 View1 View2 View3 View4

Body:
I have created a LoopingLayoutManager that fixes this issue.

It works without having to modify the adapter, which allows for greater flexibility and reusability.

It comes fully featured with support for:

Vertical and Horizontal Orientations

LTR and RTL

ReverseLayout for both orientations, as well as LTR, and RTL

Public functions for finding items and positions

Public functions for scrolling programmatically

Snap Helper support

Accessibility (TalkBack and Voice Access) support

And it is hosted on maven central, which means you just need to add it as a dependency in your build.gradle file:

dependencies {
    implementation 'com.github.beksomega:loopinglayout:0.3.1'
}

and change your LinearLayoutManager to a LoopingLayoutManager.

It has a suite of 132 unit tests that make me confident it's stable, but if you find any bugs please put up an issue on the github!

I hope this helps!


问:
shell script which opens python with arguments to python script
I want to debug some Python code in PyCharm but the repository I got the code from uses a shell script of the form

```<code>python main.py arg1 ... argN
</code>```

which is run from the command line. The main.py module in turn has a if __name__ == '__main__': part which uses argparse to parse the arguments passed via the script.

How can I write a Python script which also calls the main of main.py without touching main.py?

答:
For example: define new def main(): function and move all your if __name__ == '__main__': stuff there, then rewrite main.py as:

```<code>def main():
    <original "if __name__ == '__main__'" stuff>

if __name__ == '__main__':
    main()
</code>```

, and then call main() function from an external python script.

Body:
I want to debug some Python code in PyCharm but the repository I got the code from uses a shell script of the form

python main.py arg1 ... argN

which is run from the command line. The main.py module in turn has a if __name__ == '__main__': part which uses argparse to parse the arguments passed via the script.

How can I write a Python script which also calls the main of main.py without touching main.py?

Body:
For example: define new def main(): function and move all your if __name__ == '__main__': stuff there, then rewrite main.py as:

def main():
    <original "if __name__ == '__main__'" stuff>

if __name__ == '__main__':
    main()

, and then call main() function from an external python script.


问:
Python: How to extract multiple strings from pandas dataframe column
I have a dataset which has a specific column containing strings in the format of:
Building = Building_A and Floor = Floor_4
Building = Building_D and Floor = Floor_2

I would like to extract only the building and floor names, concatenated into a single string / new column.
E.g. Building_A/Floor_4
Building_D/Floor_2

I've spent about an hour looking through previous posts and was not able to find something to match what I am trying to do. Any help would be appreciated.

答:
Assume we have dataframe df:

```<code>import pandas as pd
df = pd.DataFrame({'txt': ["Building = Building_A and Floor = Floor_4",\
                           "Building = Building_Z and Floor = Floor_9",\
                           "Building = Martello and Floor = Ground"]})
</code>```

First define pattern to extract:

```<code>pat = "(Floor_\d+)|(Building_\w{1})"
</code>```

Alternatively if You look for all words after "= ":

```<code>pat = r"(?<== )(\w+)"
</code>```

Please note lookbehind (?<=) in pattern definition.

Then apply lambda function to column txt:

```<code>df['txt_extract'] = \
df[['txt']].apply(lambda r: "/".join(r.str.extractall(pat).stack()), axis=1)
</code>```

Result:

```<code>0    Building_A/Floor_4
1    Building_Z/Floor_9
2    Martello/Ground
</code>```

Instead of str.extract use str.extractall which looks for all occurences of pattern. Resulting searches are stacked and joined with "/" separator.
Please note that order of patterns found is preserved what may be important in Your case.

Body:
Assume we have dataframe df:

import pandas as pd
df = pd.DataFrame({'txt': ["Building = Building_A and Floor = Floor_4",\
                           "Building = Building_Z and Floor = Floor_9",\
                           "Building = Martello and Floor = Ground"]})

First define pattern to extract:

pat = "(Floor_\d+)|(Building_\w{1})"

Alternatively if You look for all words after "= ":

pat = r"(?<== )(\w+)"

Please note lookbehind (?<=) in pattern definition.

Then apply lambda function to column txt:

df['txt_extract'] = \
df[['txt']].apply(lambda r: "/".join(r.str.extractall(pat).stack()), axis=1)

Result:

0    Building_A/Floor_4
1    Building_Z/Floor_9
2    Martello/Ground

Instead of str.extract use str.extractall which looks for all occurences of pattern. Resulting searches are stacked and joined with "/" separator.
Please note that order of patterns found is preserved what may be important in Your case.


问:
How would you find the maximum number a string has been repeated consecutively in a list?
Say for example a list looks like this:

```<code>['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']
</code>```

And you pass in 'ABC'
It should return the number 3, since the maximum number of times 'ABC' has repeated consecutively is 3.
How would you go about doing this?

I've tried iterating through the list checking if the index is 'ABC', and if the next index is 'ABC', but this makes finding the maximum number almost impossible.

答:
You can do this using itertools.groupby, which groups consecutive elements. By providing no key function, it groups equal elements.

We need to use sum(1 for _ in v) to get the length of the run (since it is an iterable rather than a list, we can't use len), and max to get the biggest length.

from itertools import groupby

def longest_run_of(lst, element):
    return max(sum(1 for _ in v) for k, v in groupby(lst) if k == element)
```

<p>Example:</p>

<pre class="lang-py prettyprint-override"><code>>>> longest_run_of(lst, 'ABC')
3
>>> longest_run_of(lst, 'XYZ')
1
</code>```

Body:
Say for example a list looks like this:

['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']

And you pass in 'ABC'
It should return the number 3, since the maximum number of times 'ABC' has repeated consecutively is 3.
How would you go about doing this?

I've tried iterating through the list checking if the index is 'ABC', and if the next index is 'ABC', but this makes finding the maximum number almost impossible.

Body:
You can do this using itertools.groupby, which groups consecutive elements. By providing no key function, it groups equal elements.

We need to use sum(1 for _ in v) to get the length of the run (since it is an iterable rather than a list, we can't use len), and max to get the biggest length.

from itertools import groupby

def longest_run_of(lst, element):
    return max(sum(1 for _ in v) for k, v in groupby(lst) if k == element)

Example:

>>> longest_run_of(lst, 'ABC')
3
>>> longest_run_of(lst, 'XYZ')
1


问:
How to validate PATCH requests on large objects with Spring
I can't seem to find a lot of information about this. I've read that PUT requests should be used for replacing an entire resource with an updated resource, and that PATCH requests should be used to update only the fields you want to change. But let's say I have a very large object with lots of nested fields and objects, and I want to update only specific fields in one of its nested objects rather than having to resubmit the entire thing (because it's just too large). I would have to create a PATCH endpoint. How would I go about validating such an endpoint in a Spring REST API? I can't get my head around how the endpoint would know which fields or nested fields it has received and how to validate them, and have it work for any possible field I could give it.

答:
When a request comes into spring, it will cast it to an object for example.

```<code> @PatchMapping("/customer/1")
 public void updateCustomer(@RequestBody CustomerPatch updateRequest) {
 }
</code>```

Here we are casting the customer patch request to a CustomerPatch object.

With this, we can validate the object just as we would with any other object.

I personally use the @Valid annotation paired with hibernate validator.

so my spring controller would look like.

```<code>@PatchMapping("/customer/1")
public void updateCustomer(@RequestBody @Valid CustomerPatch updateRequest) {
}

public class CustomerPatch{
    @NotNull
    String cusotmerName;
}
</code>```

Body:
When a request comes into spring, it will cast it to an object for example.

 @PatchMapping("/customer/1")
 public void updateCustomer(@RequestBody CustomerPatch updateRequest) {
 }

Here we are casting the customer patch request to a CustomerPatch object.

With this, we can validate the object just as we would with any other object.

I personally use the @Valid annotation paired with hibernate validator.

so my spring controller would look like.

@PatchMapping("/customer/1")
public void updateCustomer(@RequestBody @Valid CustomerPatch updateRequest) {
}

public class CustomerPatch{
    @NotNull
    String cusotmerName;
}


问:
Reduce array of objects within ES6 function
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)```
</div>
</div>
</p>

<p>However, if I try to write this as ES6 function, it tells me that sum is not defined:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))</code>```

What am I missing here?

Thanks a lot in advance

答:
When your trying to use ES6 Arrow function, try not to use return if your using direct change, because its the one of the advantage of using the arrow function.

For the reduce, every iteration, we need to return the value, so it will update in the accumulator, otherwise, it will consider as a undefined.

Check MDN for more detail info about reduce

You can use the single line of code like below.

movies = [
  { title: 'The Shawshank Redemption', rate: '9.3' },
  { title: 'The Godfather', rate: '9.2' },
  { title: 'The Godfather: Part II', rate: '9.0' }
];

ratesAverage = list => list.reduce((acc,movie) => ((acc + parseFloat(movie.rate))/3), 0);

console.log(ratesAverage(movies));```

Body:
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)

However, if I try to write this as ES6 function, it tells me that sum is not defined:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))

What am I missing here?

Thanks a lot in advance


问:
How to pass a string to a child view?
I want to pass the text in the textBox to the child view and create a scrollable Button there. As for the output status, we hope that 'a ~ c' are arranged vertically and that each is a button.

struct ContentView: View {
  var textBox = ["a","b","c"]
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false) {
        ForEach(0..<textBox.count) { number in
          ScrollText(text: self.textBox[number].lowercased())
        }
      }
    }
  }
}

struct ScrollText: View {
  @Binding  var text: String
  @State private var flag: Bool = false

  var body: some View {
    Button(action: {
      self.flag.toggle()
    }) {
      Text(text)
    }
  }
}
```

答:
I'm not totally clear what the problem is, or what you want, but I solved some compiler errors in your code, and it's showing three buttons as expected:

struct ContentView : View {
  var textBox = ["a","b","c"]
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false){
        ForEach(textBox, id: \.self) { letter in
          ScrollText(text: letter)
        }
      }
    }
  }
}

struct ScrollText: View {
  var text: String
  @State private var flag: Bool = false

  var body: some View {
    Button(action: {
      self.flag.toggle()
    }, label: {
      Text(text)
    })
  }
}
```

Your question was how to pass a string, so you don't need @Binding for that. Just pass a string :)

Title: How to pass a string to a child view?

Body:
I'm not totally clear what the problem is, or what you want, but I solved some compiler errors in your code, and it's showing three buttons as expected:

struct ContentView : View {
  var textBox = ["a","b","c"]
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false){
        ForEach(textBox, id: \.self) { letter in
          ScrollText(text: letter)
        }
      }
    }
  }
}

struct ScrollText: View {
  var text: String
  @State private var flag: Bool = false

  var body: some View {
    Button(action: {
      self.flag.toggle()
    }, label: {
      Text(text)
    })
  }
}

Your question was how to pass a string, so you don't need @Binding for that. Just pass a string :)


问:
Serialize Sealed class within a data class using Gson in kotlin
I have created a sealed class for the json field Value under CustomAttribute data class. This field can return String or Array of Strings.

How can we deserialize this sealed class from json?

```<code>data class CustomAttribute (
     val attributeCode: String,
     val value: Value
)

sealed class Value {
      class StringArrayValue(val value: List<String>) : Value()
      class StringValue(val value: String)            : Value()
}
</code>```

答:
I have successfully serialized and de-serialized a sealed class in the past, with a disclaimer of using Jackson, not Gson as my serialization engine.

My sealed class has been defined as:

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, visible = true)
sealed class FlexibleResponseModel
    class SnapshotResponse(val collection: List<EntityModel>): FlexibleResponseModel()
    class DifferentialResponse(val collection: List<EntityModel>): FlexibleResponseModel()
    class EventDrivenResponse(val collection: List<EntityEventModel>): FlexibleResponseModel()
    class ErrorResponse(val error: String): FlexibleResponseModel()
</code>```

With the annotations used, it required no further configuration for the Jackson instance to properly serialize and de-serialize instances of this sealed class granted that both sides of the communication possessed a uniform definition of the sealed class.

While I recognise that JsonTypeInfo is a Jackson-specific annotation, perhaps you might consider switching over from Gson if this feature is a must - or you might be able to find an equivalent configuration for Gson which would also include the class identifier in your serialized data.

Body:
I have created a sealed class for the json field Value under CustomAttribute data class. This field can return String or Array of Strings.

How can we deserialize this sealed class from json?

data class CustomAttribute (
     val attributeCode: String,
     val value: Value
)

sealed class Value {
      class StringArrayValue(val value: List<String>) : Value()
      class StringValue(val value: String)            : Value()
}

Body:
I have successfully serialized and de-serialized a sealed class in the past, with a disclaimer of using Jackson, not Gson as my serialization engine.

My sealed class has been defined as:

@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, visible = true)
sealed class FlexibleResponseModel
    class SnapshotResponse(val collection: List<EntityModel>): FlexibleResponseModel()
    class DifferentialResponse(val collection: List<EntityModel>): FlexibleResponseModel()
    class EventDrivenResponse(val collection: List<EntityEventModel>): FlexibleResponseModel()
    class ErrorResponse(val error: String): FlexibleResponseModel()

With the annotations used, it required no further configuration for the Jackson instance to properly serialize and de-serialize instances of this sealed class granted that both sides of the communication possessed a uniform definition of the sealed class.

While I recognise that JsonTypeInfo is a Jackson-specific annotation, perhaps you might consider switching over from Gson if this feature is a must - or you might be able to find an equivalent configuration for Gson which would also include the class identifier in your serialized data.


问:
Assigning an integer into index in char * pointer array
Redoing my previous question since I didn't provide enough detail.

I have a char pointer array, char* token[100]. Let's say I have a double-digit number, like 33.

How do I assign this int into an index in the token array, so that when I print out that token it will give me 33 and not some sort of ASCII value?

```<code>char* token[100];
int num = 33;
//How do I assign num into a specific token index, like for example:
token[1] = num;
//When I print out that token index, I want 33 to be printed out
cout << token[1] << endl; // I want to have 33 be the result. Right now I have '!' as an output
</code>```

答:
I'm convinced, from comments, that you want an array of integer types. If we get further clarification about why this needs to be a char array, I'll update my answer, but from all available information it seems like you really want an integer-type array.

#include <iostream>

int main(int argc, char** argv)
{
    int token[100] = {};
    int num = 33;

    token[1] = num;

    std::cout << token[1] << std::endl;

    return 0;
}
```

Body:
Redoing my previous question since I didn't provide enough detail.

I have a char pointer array, char* token[100]. Let's say I have a double-digit number, like 33.

How do I assign this int into an index in the token array, so that when I print out that token it will give me 33 and not some sort of ASCII value?

char* token[100];
int num = 33;
//How do I assign num into a specific token index, like for example:
token[1] = num;
//When I print out that token index, I want 33 to be printed out
cout << token[1] << endl; // I want to have 33 be the result. Right now I have '!' as an output