问:
Can I print tibbles in Rmarkdown / xaringan so they look like the RStudio console
If I print a tibble with the console in the RStudio IDE the NA values appear in red. When I print the table on a xaringan slide the table is black and white and the NA_character_ values display as <NA>. Is there a way to get the output on a xaringan slide to look like the console output (without using a screen shot)?

Here is an example:

```<code>---
title: "x"
output:
  xaringan::moon_reader
---

```{r}
library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)
example
```
</code>```

答:
I tried to account for 'I didn't know what I didn't know' in regards to where your R Markdown script goes down the line (as you add more content). This works for what you have here, in addition to looking for coded negative numbers.

I have the styling called out individually. If you want to update/change these styles, you should be able to see what and where to change the styles from how this is written. I added comments to the Javascript, as well.

I used the same YAML as you have above.

I updated example so that it would contain a negative number. That way you can see that negative numbers will change color, as well.

```<code>library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA,
  "George", -1
)
example
</code>```

Add this chunk anywhere inside your R Markdown script file.

```<code>```{r doAsYouAreTold,results="asis",echo=FALSE,engine="js"}
// var str = text.innerHTML,
// reg = /red|blue|green|orange/ig; //g is to replace all occurrences

text = document.querySelectorAll("pre>code.remark-code:not(.hljs)>div.remark-code-line");

for (i = 0; i < text.length; ++i) {
  str = text[i].innerHTML,
  reg = /NA|##|-[0-9]+|<chr>|<dbl>|<int>|<fct>|<num>/ig;
        //g is to replace all occurrences
   // fix the structure
  toStr = String(reg);
  color = (toStr.replace('\/g', '|')).substring(1);

  //split the list
  colors = color.split("|");

  //remove the <> around NA
  str = str.replace(/<NA>/g, 'NA  '); // added whitespace to keep spacing even

  //remove the ## preceding each code line
  str = str.replace(/##/g, '');

  // look for negative numbers - make them dark red
  if(colors.indexOf("-[0-9]+") > -1) {
    str = str.replace(/(-[0-9]+)/g, '$1');
  }

  // look for NA - make them dark red
  if (colors.indexOf("NA") > -1) {
    str = str.replace(/NA/g, 'NA');
  }

  // look for field types - make them italicized and the color gray
  if (colors.indexOf("<chr>") > -1) {
    str = str.replace(/<chr>/g, '<chr>');
  }
  if (colors.indexOf("<dbl>") > -1) {
    str = str.replace(/<dbl>/g, '<dbl>');
  }
  if (colors.indexOf("<int>") > -1) {
    str = str.replace(/<int>/g, '<int>');
  }
  if (colors.indexOf("<fct>") > -1) {
    str = str.replace(/<fct>/g, '<fct>');
  }
  if (colors.indexOf("<num>") > -1) {
    str = str.replace(/<num>/g, '<num>');
  }

  // replace the updated content of str
  text[i].innerHTML = str;
}

// look for A tibble (A tsibble.. A ... anything else that could land here)
// make the text gray
text2 = document.querySelectorAll("pre>code.remark-code>div.remark-code-line:First-child");
for(j = 0; j < text2.length; ++j) {
  if(text2[j].innerText.includes("# A")) {
    str2 = text2[j].innerHTML
    text2[j].innerHTML = ''+str2+'';
  }
}

```
</code>```

Before and After the Javascript Chunk is Added

Body:
If I print a tibble with the console in the RStudio IDE the NA values appear in red. When I print the table on a xaringan slide the table is black and white and the NA_character_ values display as <NA>. Is there a way to get the output on a xaringan slide to look like the console output (without using a screen shot)?

Here is an example:

---
title: "x"
output:
  xaringan::moon_reader
---

```{r}
library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)
example
```

Body:
I tried to account for 'I didn't know what I didn't know' in regards to where your R Markdown script goes down the line (as you add more content). This works for what you have here, in addition to looking for coded negative numbers.

I have the styling called out individually. If you want to update/change these styles, you should be able to see what and where to change the styles from how this is written. I added comments to the Javascript, as well.

I used the same YAML as you have above.

I updated example so that it would contain a negative number. That way you can see that negative numbers will change color, as well.

library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA,
  "George", -1
)
example

Add this chunk anywhere inside your R Markdown script file.

```{r doAsYouAreTold,results="asis",echo=FALSE,engine="js"}
// var str = text.innerHTML,
// reg = /red|blue|green|orange/ig; //g is to replace all occurrences

text = document.querySelectorAll("pre>code.remark-code:not(.hljs)>div.remark-code-line");

for (i = 0; i < text.length; ++i) {
  str = text[i].innerHTML,
  reg = /NA|##|-[0-9]+|&lt;chr&gt;|&lt;dbl&gt;|&lt;int&gt;|&lt;fct&gt;|&lt;num&gt;/ig;
        //g is to replace all occurrences
   // fix the structure
  toStr = String(reg);
  color = (toStr.replace('\/g', '|')).substring(1);

  //split the list
  colors = color.split("|");

  //remove the <> around NA
  str = str.replace(/&lt;NA&gt;/g, 'NA  '); // added whitespace to keep spacing even

  //remove the ## preceding each code line
  str = str.replace(/##/g, '');

  // look for negative numbers - make them dark red
  if(colors.indexOf("-[0-9]+") > -1) {
    str = str.replace(/(-[0-9]+)/g, '<span style="color:darkred;">$1</span>');
  }

  // look for NA - make them dark red
  if (colors.indexOf("NA") > -1) {
    str = str.replace(/NA/g, '<span style="color:darkred;">NA</span>');
  }

  // look for field types - make them italicized and the color gray
  if (colors.indexOf("&lt;chr&gt;") > -1) {
    str = str.replace(/&lt;chr&gt;/g, '<i style="color:gray;">&lt;chr&gt;</i>');
  }
  if (colors.indexOf("&lt;dbl&gt;") > -1) {
    str = str.replace(/&lt;dbl&gt;/g, '<i style="color:gray;">&lt;dbl&gt;</i>');
  }
  if (colors.indexOf("&lt;int&gt;") > -1) {
    str = str.replace(/&lt;int&gt;/g, '<i style="color:gray;">&lt;int&gt;</i>');
  }
  if (colors.indexOf("&lt;fct&gt;") > -1) {
    str = str.replace(/&lt;fct&gt;/g, '<i style="color:gray;">&lt;fct&gt;</i>');
  }
  if (colors.indexOf("&lt;num&gt;") > -1) {
    str = str.replace(/&lt;num&gt;/g, '<i style="color:gray;">&lt;num&gt;</i>');
  }

  // replace the updated content of str
  text[i].innerHTML = str;
}

// look for A tibble (A tsibble.. A ... anything else that could land here)
// make the text gray
text2 = document.querySelectorAll("pre>code.remark-code>div.remark-code-line:First-child");
for(j = 0; j < text2.length; ++j) {
  if(text2[j].innerText.includes("# A")) {
    str2 = text2[j].innerHTML
    text2[j].innerHTML = '<span style="color:gray;">'+str2+'</span>';
  }
}

```

Before and After the Javascript Chunk is Added


来源: stackexchange

问:
You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without the 'an
Issue: You uploaded an APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported

My AndroidManifest.xml file

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.c4life.guardianangel">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

<application
   tools:replace="android:label"
   android:label="GA"
   android:exported="true"
   android:icon="@mipmap/ic_launcher">
   <meta-data android:name="com.google.android.geo.API_KEY"
       android:value="[insert API key here]"/>
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
   <service android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService" android:exported="false"/>
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

</application>

<uses-sdk
    android:targetSdkVersion="30"
    tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" />
</code>```

答:
In my case, I just add this line to my manifest:

```<code>android:exported="true"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Issue: You uploaded an APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported

My AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.c4life.guardianangel">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

<application
   tools:replace="android:label"
   android:label="GA"
   android:exported="true"
   android:icon="@mipmap/ic_launcher">
   <meta-data android:name="com.google.android.geo.API_KEY"
       android:value="[insert API key here]"/>
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
   <service android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService" android:exported="false"/>
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

</application>

<uses-sdk
    android:targetSdkVersion="30"
    tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" />

Body:
In my case, I just add this line to my manifest:

android:exported="true"


问:
Javascript for simple menu expanding
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

```<code><div id="submenu">
  <ul>
   <li>
     Something
   </li>
   <li>
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>
</code>```

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

答:
You can do this sort of thing easily with jQuery, take this drop down example:

HTML:

```<code><ul>
   <li>Nav Item 1</li>
   <li class="dropdown">
       Nav Item 2
       <ul style="display:none">
           <li>Sub Menu Item 1</li>
           <li>Sub Menu Item 2</li>
           <li>Sub Menu Item 3</li>
       </ul>
   </li>
   <li>Nav Item 3</li>
</ul>
</code>```

jQuery:

```<code>$('.dropdown').hover(function() {
   $('ul', $(this)).show();
}, function() {
   $('ul', $(this)).hide();
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript for simple menu expanding

Body:
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

     Something

     Another

Something-sub

Something-sub

Something-sub

Another-sub

Another-sub

Another-sub

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

Body:
You can do this sort of thing easily with jQuery, take this drop down example:

HTML:

<ul>
   <li>Nav Item 1</li>
   <li class="dropdown">
       Nav Item 2
       <ul style="display:none">
           <li>Sub Menu Item 1</li>
           <li>Sub Menu Item 2</li>
           <li>Sub Menu Item 3</li>
       </ul>
   </li>
   <li>Nav Item 3</li>
</ul>

jQuery:

$('.dropdown').hover(function() {
   $('ul', $(this)).show();
}, function() {
   $('ul', $(this)).hide();
});


问:
Access function in class A from non related class B using object of class A

Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

```<code>    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();
</code>```

答:
This does not work because $a is not a global variable.
It should work if you declare $a as global in class B beforehand.

```<code>class B {
        function two() {
            global $a;
            echo "Class B";
            $a->one();
        }
    }
</code>```

Body:
Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();

Body:
This does not work because $a is not a global variable.
It should work if you declare $a as global in class B beforehand.

class B {
        function two() {
            global $a;
            echo "Class B";
            $a->one();
        }
    }


问:
Python - How to convert list back into it's original dataframe after using .apply(pd.eval) function?
I have a panda dataframe (defined in my code as 'df1') where the data are text but I want them converted to integers/numbers. I have years (row/left column) and word descriptions (column) as my dataframe indices. Example below

```<code>     |Alpha   |Bravo   |Charlie |Delta  |
2020 |1.98M   | -7.40M |0.00    |29.55K |
2021 |-5.30K  | 23.2B  |-       |35.01K |
</code>```

I applied below code to clean the data above to ensure values can be recognised as integers rather than text:

```<code>repl_dict = {'−':'-', '—':'','[kK]': '*1e3', '[mM]': '*1e6', '[bB]': '*1e9'}
df2 = df1.replace(repl_dict, regex=True).apply(pd.eval)
print(df2)
</code>```

The above code manages to convert my values to integers, however the .apply(pd.eval) function also reformats my dataframe by re-transposing, making each row of values back into a list, and my years disappear, and the list goes into one column. Example of output:

```<code>       |0                        |
Alpha  |[1980000, -5300]         |
Bravo  |[-74000000, 23200000000] |
Charlie|[0.00, 0.00]             |
Delta  |[29550, 35010]           |
</code>```

Please can someone help, I have been unable to find a solution to make this work? I do not need to use .apply(pd.eval) function if there's another method to achieve the below output

Desired Output:

```<code>     |Alpha     |Bravo         |Charlie |Delta  |
2020 |1980000   | -7400000     |0.00    |29550  |
2021 |-5300     | 23200000000  |-       |35010  |
</code>```

Many thanks in advance!

Also tried:

```<code>.apply(pd.eval, axis=0, result_type = 'broadcast')
</code>```

Returns "ValueError: cannot broadcast result"

答:
You can use the 'normal' eval, not 'pd.eval', combined with stack/unstack:

```<code>df1.stack().replace(repl_dict, regex=True).apply(eval).unstack()
</code>```

output:

```<code>
        Alpha        Bravo          Charlie Delta
2020    1980000.0   -7.400000e+06   0.0     29550.0
2021    -5300.0      2.320000e+10   NaN     35010.0
</code>```

Note I had to tweak you repl_dict for this to work, but this may not be quite the right thing for you depending on how you construct your df1, the white spaces etc so you may have to experiment a bit:

```<code>repl_dict = {'−':'-', '-$':'None','[kK]': '*1e3', '[mM]': '*1e6', '[bB]': '*1e9'}
</code>```

Body:
I have a panda dataframe (defined in my code as 'df1') where the data are text but I want them converted to integers/numbers. I have years (row/left column) and word descriptions (column) as my dataframe indices. Example below

     |Alpha   |Bravo   |Charlie |Delta  |
2020 |1.98M   | -7.40M |0.00    |29.55K |
2021 |-5.30K  | 23.2B  |-       |35.01K |

I applied below code to clean the data above to ensure values can be recognised as integers rather than text:

repl_dict = {'−':'-', '—':'','[kK]': '*1e3', '[mM]': '*1e6', '[bB]': '*1e9'}
df2 = df1.replace(repl_dict, regex=True).apply(pd.eval)
print(df2)

The above code manages to convert my values to integers, however the .apply(pd.eval) function also reformats my dataframe by re-transposing, making each row of values back into a list, and my years disappear, and the list goes into one column. Example of output:

       |0                        |
Alpha  |[1980000, -5300]         |
Bravo  |[-74000000, 23200000000] |
Charlie|[0.00, 0.00]             |
Delta  |[29550, 35010]           |

Please can someone help, I have been unable to find a solution to make this work? I do not need to use .apply(pd.eval) function if there's another method to achieve the below output

Desired Output:

     |Alpha     |Bravo         |Charlie |Delta  |
2020 |1980000   | -7400000     |0.00    |29550  |
2021 |-5300     | 23200000000  |-       |35010  |

Many thanks in advance!

Also tried:

.apply(pd.eval, axis=0, result_type = 'broadcast')

Returns "ValueError: cannot broadcast result"

Body:
You can use the 'normal' eval, not 'pd.eval', combined with stack/unstack:

df1.stack().replace(repl_dict, regex=True).apply(eval).unstack()

output:

        Alpha        Bravo          Charlie Delta
2020    1980000.0   -7.400000e+06   0.0     29550.0
2021    -5300.0      2.320000e+10   NaN     35010.0

Note I had to tweak you repl_dict for this to work, but this may not be quite the right thing for you depending on how you construct your df1, the white spaces etc so you may have to experiment a bit:

repl_dict = {'−':'-', '-$':'None','[kK]': '*1e3', '[mM]': '*1e6', '[bB]': '*1e9'}


问:
Make OL Tag from Bottom
Can anyone help me? i'm looking for how to make  tag @html code but count the numbers from below. Because what I know is just creating  tags but always counting the numbers from above like this :

```<code><ol>
  <li>Aaaa</li>
  <li>Aaaa</li>
  <li>Aaaa</li>
</ol>
</code>```

答:
Let me help my friend. It might help you ^_^

<!DOCTYPE html>

The ol reversed attribute

Coffee

Tea

Milk

Note: The reversed attribute of the ol tag is not supported in Edge prior version 79.

```

Title: Make OL Tag from Bottom

Body:
Can anyone help me? i'm looking for how to make  tag @html code but count the numbers from below. Because what I know is just creating  tags but always counting the numbers from above like this :

Aaaa

Aaaa

Aaaa

Body:
Let me help my friend. It might help you ^_^

<!DOCTYPE html>
<html>
<body>

<h1>The ol reversed attribute</h1>

<ol reversed>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

<p><strong>Note:</strong> The reversed attribute of the ol tag is not supported in Edge prior version 79.</p>

</body>
</html>


问:
How do I force the Xcode compiler to ignore a library when building for the iOS simulator
I am getting a series of linker errors when building a specific library for the iOS simulator.  The source of the issue seems to the be architecture that the library was build for which seems to cause issue when compiling for the iOS simulator.  The specific library is the Aurasma augmented reality library.

My question would be this, is there a way to not compile a library when the code is being compiled for the iOS simulator?  Although I do have some code that is dependent on that library I could easily use an #ifdef statement to only use that code when NOT in the iOS simulator.

I can easily admit I may not understand the full root of the issue.  I have attempted some solutions using a -weak_library linker flag with no specific progress or success.

答: I had the same problem, what I did is configured the unity project to compile to a simulator SDK, then in Xcode I changed the target>Build settings to compile to release , if I remember well and bingo the project worked and I had the unsigned ipa file.</p>


问:
How do I measure how long the user held down a button?
I tried using the Timer class but that only counts down from a fixed duration AFAIK. I have a button where the user can either single tap it or long press and hold it for X amount of seconds, up to a maximum of 10 seconds. I already figured out the single tap code, but if the user presses and holds the button I want to record how long he held it for and also do other stuff.</p>
```<code>Timer startRecordingTimer() => Timer(Duration(milliseconds: 10 * 1000), handleTimeout);

void handleTimeout() {
  //when startRecordingTimer() reaches 0, do the following
  stopRecording();
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      startRecording();
                    },
                    onLongPressDown: (details) {
                      startRecordingTimer();
                      startRecording();
                    },
                    onLongPressUp: () {
                      //Need to measure how long user held down button
                      //Do other stuff using the aforementioned duration
                    },
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }
</code>```

答:
Use a Stopwatch

Create an instance in the class:
Stopwatch stopwatch = Stopwatch();

```<code> GestureDetector(
    onTap: () async {
       startRecording();
    },
    onLongPressDown: (details) {
      startRecordingTimer();
      startRecording();
      stopwatch.start();
    },
    onLongPressUp: () {
      stopwatch.stop();
      var timeElapsedInSeconds =     stopwatch.elapsed.inSeconds;
      print("Time elapsed: $timeElapsedInSeconds");
    },
)
</code>```

Body:
I tried using the Timer class but that only counts down from a fixed duration AFAIK. I have a button where the user can either single tap it or long press and hold it for X amount of seconds, up to a maximum of 10 seconds. I already figured out the single tap code, but if the user presses and holds the button I want to record how long he held it for and also do other stuff.

Timer startRecordingTimer() => Timer(Duration(milliseconds: 10 * 1000), handleTimeout);

void handleTimeout() {
  //when startRecordingTimer() reaches 0, do the following
  stopRecording();
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      startRecording();
                    },
                    onLongPressDown: (details) {
                      startRecordingTimer();
                      startRecording();
                    },
                    onLongPressUp: () {
                      //Need to measure how long user held down button
                      //Do other stuff using the aforementioned duration
                    },
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }

Body:
Use a Stopwatch

Create an instance in the class:
Stopwatch stopwatch = Stopwatch();

 GestureDetector(
    onTap: () async {
       startRecording();
    },
    onLongPressDown: (details) {
      startRecordingTimer();
      startRecording();
      stopwatch.start();
    },
    onLongPressUp: () {
      stopwatch.stop();
      var timeElapsedInSeconds =     stopwatch.elapsed.inSeconds;
      print("Time elapsed: $timeElapsedInSeconds");
    },
)


问:
Recursive function to add path to nested object using parent object values
I'm trying to add a "path" to all nested objects using their ancestor's attributes. Essentially I want to represent a "path" of the hierarchical structure to a nested object using a concatenation of its parent object's attribute values instead of using keys (like I could with dot notation, lodash, etc).

What I've tried:

```<code>interface SimpleObject {
    name : string
    slug : string
    slug_path? : string
    fields? : SimpleObject[]
}

const addNestedObjSlug = (data:SimpleObject[], parents:SimpleObject[] = []) => {

    data.map((obj) => {
        obj.slug_path = parents.length > 0 ? `${parents.map(({slug}) => slug).join('.')}.${obj.slug}` : obj.slug
        if(obj.fields && obj.fields.length > 0) {
            parents.push(obj)

            // I think the issue is here, that I probably need to set parents to an empty array at some point
            return addNestedObjSlug(obj.fields, parents)
        }
    })

    return data
}

const desiredResult = addNestedObjSlug([
    {
        name : 'Item 1',
        slug : 'i1',
        fields : [
            {
                name : 'Item 1 - 1',
                slug : 'i1-1'
            },
            {
                name : 'Item 1 - 2',
                slug : 'i1-2'
            },
            {
                name : 'Item 1 - 3',
                slug : 'i1-3'
            }
        ]
    },
    {
        name : 'Item 2',
        slug : 'i2',
        fields : [
            {
                name : 'Item 2 - 1',
                slug : 'i2-1',
                fields : [
                    {
                        name : 'Item 2 - 1 - 1',
                        slug : 'i2-1-1'
                    }
                ]
            }
        ]
    }
])
</code>```

My expected result is:

```<code>[
    {
        "name": "Item 1",
        "slug": "i1",
        "fields": [
            {
                "name": "Item 1 - 1",
                "slug": "i1-1",
                "slug_path": "i1.i1-1"
            },
            {
                "name": "Item 1 - 2",
                "slug": "i1-2",
                "slug_path": "i1.i1-2"
            },
            {
                "name": "Item 1 - 3",
                "slug": "i1-3",
                "slug_path": "i1.i1-3"
            }
        ],
        "slug_path": "i1"
    },
    {
        "name": "Item 2",
        "slug": "i2",
        "fields": [
            {
                "name": "Item 2 - 1",
                "slug": "i2-1",
                "fields": [
                    {
                        "name": "Item 2 - 1 - 1",
                        "slug": "i2-1-1",
                        "slug_path": "i2.i2-1.i2-1-1"
                    }
                ],
                "slug_path": "i2.i2-1"
            }
        ],
        "slug_path": "i2"
    }
]
</code>```

But instead I get the following, where the original nested object's slug is part of the new slug_path attribute of objects which are not ancestors.

```<code>[
    {
        "name": "Item 1",
        "slug": "i1",
        "fields": [
            {
                "name": "Item 1 - 1",
                "slug": "i1-1",
                "slug_path": "i1.i1-1" // correct
            },
            {
                "name": "Item 1 - 2",
                "slug": "i1-2",
                "slug_path": "i1.i1-2" // correct
            },
            {
                "name": "Item 1 - 3",
                "slug": "i1-3",
                "slug_path": "i1.i1-3" // correct
            }
        ],
        "slug_path": "i1" // correct
    },
    {
        "name": "Item 2",
        "slug": "i2",
        "fields": [
            {
                "name": "Item 2 - 1",
                "slug": "i2-1",
                "fields": [
                    {
                        "name": "Item 2 - 1 - 1",
                        "slug": "i2-1-1",
                        "slug_path": "i1.i2.i2-1.i2-1-1" // incorrect
                    }
                ],
                "slug_path": "i1.i2.i2-1" // incorrect
            }
        ],
        "slug_path": "i1.i2" // incorrect
    }
]
</code>```

答:
If you don't mind also adding the slugPath to your root elements (which I personally think is better for consistency in any case), then this should do:

const addSlugPath = (items, path = []) =>
  items .map (({slug, fields, ...rest}, _, __, newPath = [...path, slug]) => ({
    ... rest,
    slug,
    slugPath: newPath .join ('.'),
    ... (fields ? {fields: addSlugPath (fields, newPath)} : {})
  }))

const input = [{name: "Item 1", slug: "i1", fields: [{name: "Item 1 - 1", slug: "i1-1"}, {name: "Item 1 - 2", slug: "i1-2"}, {name: "Item 1 - 3", slug: "i1-3"}]}, {name: "Item 2", slug: "i2", fields: [{name: "Item 2 - 1", slug: "i2-1", fields: [{name: "Item 2 - 1 - 1", slug: "i2-1-1"}]}]}]

console .log (addSlugPath (input))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

Note that we don't mutate any input data here but only return a copy with the slugPath added appropriately.

We keep an array of nodes in path and add to it at each recursive level.  The _ and __ parameters are just to cover the index and full array that map supplies to its callback function.

Body:
I'm trying to add a "path" to all nested objects using their ancestor's attributes. Essentially I want to represent a "path" of the hierarchical structure to a nested object using a concatenation of its parent object's attribute values instead of using keys (like I could with dot notation, lodash, etc).

What I've tried:

interface SimpleObject {
    name : string
    slug : string
    slug_path? : string
    fields? : SimpleObject[]
}

const addNestedObjSlug = (data:SimpleObject[], parents:SimpleObject[] = []) => {

    data.map((obj) => {
        obj.slug_path = parents.length > 0 ? `${parents.map(({slug}) => slug).join('.')}.${obj.slug}` : obj.slug
        if(obj.fields && obj.fields.length > 0) {
            parents.push(obj)

            // I think the issue is here, that I probably need to set parents to an empty array at some point
            return addNestedObjSlug(obj.fields, parents)
        }
    })

    return data
}

const desiredResult = addNestedObjSlug([
    {
        name : 'Item 1',
        slug : 'i1',
        fields : [
            {
                name : 'Item 1 - 1',
                slug : 'i1-1'
            },
            {
                name : 'Item 1 - 2',
                slug : 'i1-2'
            },
            {
                name : 'Item 1 - 3',
                slug : 'i1-3'
            }
        ]
    },
    {
        name : 'Item 2',
        slug : 'i2',
        fields : [
            {
                name : 'Item 2 - 1',
                slug : 'i2-1',
                fields : [
                    {
                        name : 'Item 2 - 1 - 1',
                        slug : 'i2-1-1'
                    }
                ]
            }
        ]
    }
])

My expected result is:

[
    {
        "name": "Item 1",
        "slug": "i1",
        "fields": [
            {
                "name": "Item 1 - 1",
                "slug": "i1-1",
                "slug_path": "i1.i1-1"
            },
            {
                "name": "Item 1 - 2",
                "slug": "i1-2",
                "slug_path": "i1.i1-2"
            },
            {
                "name": "Item 1 - 3",
                "slug": "i1-3",
                "slug_path": "i1.i1-3"
            }
        ],
        "slug_path": "i1"
    },
    {
        "name": "Item 2",
        "slug": "i2",
        "fields": [
            {
                "name": "Item 2 - 1",
                "slug": "i2-1",
                "fields": [
                    {
                        "name": "Item 2 - 1 - 1",
                        "slug": "i2-1-1",
                        "slug_path": "i2.i2-1.i2-1-1"
                    }
                ],
                "slug_path": "i2.i2-1"
            }
        ],
        "slug_path": "i2"
    }
]

But instead I get the following, where the original nested object's slug is part of the new slug_path attribute of objects which are not ancestors.

[
    {
        "name": "Item 1",
        "slug": "i1",
        "fields": [
            {
                "name": "Item 1 - 1",
                "slug": "i1-1",
                "slug_path": "i1.i1-1" // correct
            },
            {
                "name": "Item 1 - 2",
                "slug": "i1-2",
                "slug_path": "i1.i1-2" // correct
            },
            {
                "name": "Item 1 - 3",
                "slug": "i1-3",
                "slug_path": "i1.i1-3" // correct
            }
        ],
        "slug_path": "i1" // correct
    },
    {
        "name": "Item 2",
        "slug": "i2",
        "fields": [
            {
                "name": "Item 2 - 1",
                "slug": "i2-1",
                "fields": [
                    {
                        "name": "Item 2 - 1 - 1",
                        "slug": "i2-1-1",
                        "slug_path": "i1.i2.i2-1.i2-1-1" // incorrect
                    }
                ],
                "slug_path": "i1.i2.i2-1" // incorrect
            }
        ],
        "slug_path": "i1.i2" // incorrect
    }
]

Body:
If you don't mind also adding the slugPath to your root elements (which I personally think is better for consistency in any case), then this should do:

const addSlugPath = (items, path = []) =>
  items .map (({slug, fields, ...rest}, _, __, newPath = [...path, slug]) => ({
    ... rest,
    slug,
    slugPath: newPath .join ('.'),
    ... (fields ? {fields: addSlugPath (fields, newPath)} : {})
  }))

const input = [{name: "Item 1", slug: "i1", fields: [{name: "Item 1 - 1", slug: "i1-1"}, {name: "Item 1 - 2", slug: "i1-2"}, {name: "Item 1 - 3", slug: "i1-3"}]}, {name: "Item 2", slug: "i2", fields: [{name: "Item 2 - 1", slug: "i2-1", fields: [{name: "Item 2 - 1 - 1", slug: "i2-1-1"}]}]}]

console .log (addSlugPath (input))

.as-console-wrapper {max-height: 100% !important; top: 0}

Note that we don't mutate any input data here but only return a copy with the slugPath added appropriately.

We keep an array of nodes in path and add to it at each recursive level.  The _ and __ parameters are just to cover the index and full array that map supplies to its callback function.


问:
Non direct son to take the entire width of a grid layout
i've been trying to make the text div to take the entire width of the grid layout but have it's content in line with the rest of the layout itself
I've used width: 100vw, tried padding the corners yet it doesn't work properly and is a bit clunky.

I've uploaded it to the codepen for better understanding
https://codepen.io/Aegtar/pen/PoObBdG

what is needed is that the green part will take the entire width yet the text inside will stay within the lightsalmon div.

the HTML :

```<code>      <div class='main-layout'>
        <div class='weather-page'>
          <div class='top-side'>
            <div>WeatherPage</div>
            <div class='text-container'>
              <div class='ha'>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est,
                tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet.
              </div>
            </div>
            <button>
              2
            </button>
            <button>
             2
            </button>
          </div>

        </div>
      </div>
      <section class='footer'>Footer</section>
    </div>
</code>```

the scss :

```<code>
.main-layout {
  display: grid;
  grid-template-columns: minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);

  > * {
    grid-column: 2;
  }

  > *.full {
    grid-column: 1 / -1;
  }
}

.home-page {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  width: 50%;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.weather-page {
  gap: 10px;
  grid-auto-flow: column;
  background-color: lightsalmon;
  .top-side {
    gap: 20px;
    align-items: center;
    flex-direction: column;
    display: flex;
    margin-bottom: 30px;

    .text-container {
      background-color: lightgreen;
      .ha {
        text-align: center;
      }
    }
}

.footer {
  background-color: rgb(25, 118, 210);
}
</code>```

any help is appreciated!

答:
Just remove the grid-template-columns:minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);
from the .main-layout and then add

```<code>body{
    padding:0;
    margin:0;
}
</code>```

so that it can strech all the way.
Also, if you want the grid-template-columns , then comment on this post and I will (probably) find another solution.

Code Pen: https://codepen.io/576031/pen/rNYWqbz

Body:
i've been trying to make the text div to take the entire width of the grid layout but have it's content in line with the rest of the layout itself
I've used width: 100vw, tried padding the corners yet it doesn't work properly and is a bit clunky.

I've uploaded it to the codepen for better understanding
https://codepen.io/Aegtar/pen/PoObBdG

what is needed is that the green part will take the entire width yet the text inside will stay within the lightsalmon div.

the HTML :

WeatherPage

                Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est,
                tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet.

            <button>
              2
            </button>
            <button>
             2
            </button>

Footer

the scss :

.main-layout {
  display: grid;
  grid-template-columns: minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);

  > * {
    grid-column: 2;
  }

  > *.full {
    grid-column: 1 / -1;
  }
}

.home-page {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  width: 50%;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.weather-page {
  gap: 10px;
  grid-auto-flow: column;
  background-color: lightsalmon;
  .top-side {
    gap: 20px;
    align-items: center;
    flex-direction: column;
    display: flex;
    margin-bottom: 30px;

    .text-container {
      background-color: lightgreen;
      .ha {
        text-align: center;
      }
    }
}

.footer {
  background-color: rgb(25, 118, 210);
}

any help is appreciated!

Body:
Just remove the grid-template-columns:minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);
from the .main-layout and then add

body{
    padding:0;
    margin:0;
}

so that it can strech all the way.
Also, if you want the grid-template-columns , then comment on this post and I will (probably) find another solution.

Code Pen: https://codepen.io/576031/pen/rNYWqbz


问:
Please help me understand Javascript anonymous functions and jQuery .proxy()
I've been trying to wrap my head around how javascript functions and scope work, and it just doesn't make sense to me. Can someone please explain why the following code outputs: 'animal says meow' instead of 'kitty says meow'?

```<code>(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);

(function($, Animal){
  var kitty = new Animal;
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }
  $($.proxy(function(){
    $('#js_test').click($.proxy(kitty.sayHi, kitty));
  }, kitty))
})(jQuery, Animal);
</code>```

UPDATE

@FunkyFresh pointed out in the comments that console.log calls toString when it's passed an object, which by default returns the object's type (animal). When I update the above code with

```<code>animal.prototype.name = 'Mammal';
</code>```

in the top block of code, and

```<code>kitty.name = 'Zax';
</code>```

in the bottom, the console outputs 'Zax says meow', which seems about right.

答:
Update: kitty is an instance of Animal. So it'll never say kitty. All those proxy wrappers are careful misdirections.

Lets see:

```<code>(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);
</code>```

Just a disguise to say: window.Animal = function(){};

You're creating an anonymous function passing jQuery and window object to it and executing it immediately. This creates Animal class in window scope

Now jquery.proxy allows you to change the context of a function: jQuery.proxy( functionName, context ) - so inside functionName, this refers to context (this == context).

$.proxy(kitty.sayHi, kitty) says call sayHi passing kitty as context.

Now kitty = new Animal (this is called a closure actaully since you're accessing parent function's variable), so this -> Animal

```<code>(function($, Animal){

  // create a new instance of Animal, assign it to local variable kitty
  var kitty = new Animal;

  // assign sayHi to kitty object
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }

  // $() shortcut that says run this code on DOM ready
  $($.proxy(function(){
    // this proxy almost does nothing as we do not refer to this object insdie it

    // says on click of js_Test, call kitty.sayHi with context = kitty
    $('#js_test').click($.proxy(kitty.sayHi, kitty));

  }, kitty))

})(jQuery, Animal);
</code>```

So when the click handler is called, its actually Animal.sayHi.

Body:
I've been trying to wrap my head around how javascript functions and scope work, and it just doesn't make sense to me. Can someone please explain why the following code outputs: 'animal says meow' instead of 'kitty says meow'?

(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);

(function($, Animal){
  var kitty = new Animal;
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }
  $($.proxy(function(){
    $('#js_test').click($.proxy(kitty.sayHi, kitty));
  }, kitty))
})(jQuery, Animal);

UPDATE

@FunkyFresh pointed out in the comments that console.log calls toString when it's passed an object, which by default returns the object's type (animal). When I update the above code with

animal.prototype.name = 'Mammal';

in the top block of code, and

kitty.name = 'Zax';

in the bottom, the console outputs 'Zax says meow', which seems about right.

Body:
Update: kitty is an instance of Animal. So it'll never say kitty. All those proxy wrappers are careful misdirections.

Lets see:

(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);

Just a disguise to say: window.Animal = function(){};

You're creating an anonymous function passing jQuery and window object to it and executing it immediately. This creates Animal class in window scope

Now jquery.proxy allows you to change the context of a function: jQuery.proxy( functionName, context ) - so inside functionName, this refers to context (this == context).

$.proxy(kitty.sayHi, kitty) says call sayHi passing kitty as context.

Now kitty = new Animal (this is called a closure actaully since you're accessing parent function's variable), so this -> Animal

(function($, Animal){

  // create a new instance of Animal, assign it to local variable kitty
  var kitty = new Animal;

  // assign sayHi to kitty object
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }

  // $() shortcut that says run this code on DOM ready
  $($.proxy(function(){
    // this proxy almost does nothing as we do not refer to this object insdie it

    // says on click of js_Test, call kitty.sayHi with context = kitty
    $('#js_test').click($.proxy(kitty.sayHi, kitty));

  }, kitty))

})(jQuery, Animal);

So when the click handler is called, its actually Animal.sayHi.


问:
"java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent"
I'm struggling with Maven plugins issues since days now doing a Maven > Lifecycle > Site

The errors I'm getting:

https://codeshare.io/GLXByl

```<code>java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent
</code>```

I know I'm missing some plugins. I've tried all the solutions in previous posts and many version last and older ones but still missing them and I don't know what I'm missing in my pom.xml:

https://codeshare.io/5MO1Xe

答:
Apparently you miss certain plugins in your <build/>. Add these:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-site-plugin</artifactId>
      <version>3.10.0</version>
    </plugin>

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-project-info-reports-plugin</artifactId>
      <version>3.2.1</version>
    </plugin>
  </plugins>
</build>
```

and see if it helps.

Body:
I'm struggling with Maven plugins issues since days now doing a Maven > Lifecycle > Site

The errors I'm getting:

https://codeshare.io/GLXByl

java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent

I know I'm missing some plugins. I've tried all the solutions in previous posts and many version last and older ones but still missing them and I don't know what I'm missing in my pom.xml:

https://codeshare.io/5MO1Xe

Body:
Apparently you miss certain plugins in your <build/>. Add these:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-site-plugin</artifactId>
      <version>3.10.0</version>
    </plugin>

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-project-info-reports-plugin</artifactId>
      <version>3.2.1</version>
    </plugin>
  </plugins>
</build>

and see if it helps.


问:
trying to add two arrays and get a function object error
I am trying to add these two three-dimensional arrays. I am getting the following error message:

Traceback (most recent call last):

File "C:\Users\ablev\eclipse-workspace\matrix\matrix.py", line 88, in

print(np.add(matrix_one.matrix1,matrix_two.matrix2))

AttributeError: 'function' object has no attribute 'matrix1'

Code:

```<code>def matrix_one():
    print("Enter your first 3x3 matrix: ")
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)

    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()
print(np.add(matrix_one.matrix1,matrix_two.matrix2))
</code>```

Thanks for the help in advance.

答:
Here is one possible way to get your code to work.

```<code>def matrix_one():
    print("Enter your first 3x3 matrix: ")
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()
    return matrix1

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)

    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()
    return matrix2
print(np.add(matrix_one(),matrix_two()))
</code>```

Example run:

```<code>Enter your first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Your first 3x3 matrix is:
1 2 3
4 5 6
7 8 9
Enter your second 3x3 matrix:
2 3 4
3 4 5
5 6 7
Your second 3x3 matrix is:
2 3 4
3 4 5
5 6 7
[[ 3  5  7]
 [ 7  9 11]
 [12 14 16]]
</code>```

Body:
I am trying to add these two three-dimensional arrays. I am getting the following error message:

Traceback (most recent call last):

File "C:\Users\ablev\eclipse-workspace\matrix\matrix.py", line 88, in

print(np.add(matrix_one.matrix1,matrix_two.matrix2))

AttributeError: 'function' object has no attribute 'matrix1'

Code:

def matrix_one():
    print("Enter your first 3x3 matrix: ")
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)

    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()
print(np.add(matrix_one.matrix1,matrix_two.matrix2))

Thanks for the help in advance.

Body:
Here is one possible way to get your code to work.

def matrix_one():
    print("Enter your first 3x3 matrix: ")
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()
    return matrix1

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)

    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()
    return matrix2
print(np.add(matrix_one(),matrix_two()))

Example run:

Enter your first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Your first 3x3 matrix is:
1 2 3
4 5 6
7 8 9
Enter your second 3x3 matrix:
2 3 4
3 4 5
5 6 7
Your second 3x3 matrix is:
2 3 4
3 4 5
5 6 7
[[ 3  5  7]
 [ 7  9 11]
 [12 14 16]]


问:
Range() returning different output than "list" in "for" loop
I'm a beginner trying to understand why I get a different output when I use the range function. If I use (len(arr)) the output: 5 0 3  vs using arr the output: 3 2 1

```<code> arr = [-4, 3, -9, 0, 4, 1]

 def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in range(len(arr)):
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
    print(count_pos)
    print(count_neg)
    print(count_zero)
</code>```

Comparing that version to not using range() and just arr:

```<code>def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in arr:
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)
</code>```

答:
Thanks everyone for your explanations!

So it turns out I wasn't aware that range() calls upon indexing, and if my function doesn't also index the variable ( arr[i] ) then I am just looping through and making calculations off the index numbers [0,1,2,3,4,5] instead of the actual values[-4, 3, -9, 0, 4, 1]. Good to know! Thanks everyone!

Body:
I'm a beginner trying to understand why I get a different output when I use the range function. If I use (len(arr)) the output: 5 0 3  vs using arr the output: 3 2 1

 arr = [-4, 3, -9, 0, 4, 1]

 def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in range(len(arr)):
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
    print(count_pos)
    print(count_neg)
    print(count_zero)

Comparing that version to not using range() and just arr:

def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in arr:
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)


问:
MYSQL statement to quickly select group from n:n table
I have an n:n set of data (for example, 'programmers' and 'languages'.  Programmers write code in many languages, and a language can be used by many programmers).  This data is in a table programmers_languages

How do I quickly select programmers who code in all of a set of languages?

More information if this is confusing:

Jon codes in C++, Pascal, and Ruby.  Joe codes in C++ and Ruby.  Moe codes in Ruby and Pascal.  Steve Codes in C++ and Pascal.

If the set of languages in question is C++ and Pascal, I would want Jon and Steve from this list.

Note the size of this set can get pretty large, so I don't want to join the table to itself n times.

答:
edit: this was my first answer and doesn't work for the question.

Assuming the table Programmers_Languages has two VARCHAR columns, one called Programmer and the other called Languages:

```<code>SELECT DISTINCT Programmer
FROM Programmers_Languages
WHERE Language IN ('C++', 'Pascal')
ORDER BY Programmer
</code>```

DISTINCT so that you only get each result once.  ORDER BY if you want it sorted alphabetically.

edit: different query, this works.

```<code>SELECT Programmers
FROM Programmers_Languages
WHERE Languages IN ('C++', 'Pascal')
GROUP BY Programmers
HAVING COUNT(*) >= 2
ORDER BY Programmers
</code>```

Looks like TokenMacGuy came up with something very similar.  I'm assuming that the list of languages and the count of languages will be inserted in this query by some other code.  If you're building the query dynamically, the following would be even quicker, of course:

```<code>SELECT DISTINCT Programmers
FROM Programmers_Languages
WHERE Languages = 'C++'
AND   Languages = 'Pascal'
AND   <...>
ORDER BY Programmers
</code>```

Body:
edit: this was my first answer and doesn't work for the question.

Assuming the table Programmers_Languages has two VARCHAR columns, one called Programmer and the other called Languages:

SELECT DISTINCT Programmer
FROM Programmers_Languages
WHERE Language IN ('C++', 'Pascal')
ORDER BY Programmer

DISTINCT so that you only get each result once.  ORDER BY if you want it sorted alphabetically.

edit: different query, this works.

SELECT Programmers
FROM Programmers_Languages
WHERE Languages IN ('C++', 'Pascal')
GROUP BY Programmers
HAVING COUNT(*) >= 2
ORDER BY Programmers

Looks like TokenMacGuy came up with something very similar.  I'm assuming that the list of languages and the count of languages will be inserted in this query by some other code.  If you're building the query dynamically, the following would be even quicker, of course:

SELECT DISTINCT Programmers
FROM Programmers_Languages
WHERE Languages = 'C++'
AND   Languages = 'Pascal'
AND   <...>
ORDER BY Programmers


问:
The claim process removes the secretKey, how to restore it if I do a reclaim?
We're using the thingsboard CE for a smarthome application. We're considering the claim process to let the user to add a new device. We developed a proof of concept following the process described in here: https://thingsboard.io/docs/user-guide/claiming-devices/

Now we're considering the use case of removing the device to let another user to add it (like selling the device to another person), but when we reclaim the device (according to "Device Reclaiming API Request") the device doesn't have the secretKey, so, we cannot let another user claim the device.

Are we missing something? Is there another way to do what we want?

答:
I'd suggest handling it in the rule chain. One solution would be to have a button on a management dashboard. Clicking the button sets a "reclaim flag" to true (or you can do it direct from default attribute edit window). The rule chain receives this action, notices the flag and does the following:

Adds a secretKey attribute

Re-enables device claiming (I think once a device is claimed it can't be reclaimed again by default)

Flips the "reclaim flag" back to false

Changes the "owner" of the device back to the tenant (optional but I recommend it).

Alternatively, if you didn't want to deal with the flag bit, you could have the rule chain listen for any time an device has it's owner changed to the tenant. Might be a little less secure though.


问:
In-place sort_values in pandas what does it exactly mean?
Maybe a very naive question, but I am stuck in this: pandas.Series has a method sort_values and there is an option to do it "in place" or not. I have Googled for it a while, but I am not very clear about it. It seems that this thing is assumed to be perfectly known to everybody but me. Could anyone give me some illustrative explanation how these two options differ each other for dummies...?

Thank you for any assistance.

答:
inplace = True changes the actual list itself while sorting.

inplace = False will return a new sorted list without changing the original.

By default, inplace is set to False if unspecified.


问:
next js state change doesnt change value of input
I have this piece of code but that does not change value of input field when state changes.State changes when user clicks on a row. State is changing as i printed the value outside text field but that does not reflect in input field. I tried with value instead of defaultValue but it doesnt work.</p>
```<code>                           <Controller
                            name="name"
                            control={control}
                            defaultValue={selectedRow.name}
                            value={selectedRow.name}
                            rules={{
                              required: true,
                            }}
                            render={({ field }) => (
                              <TextField
                                variant="outlined"
                                fullWidth
                                id="name"
                                label="Name"
                                error={Boolean(errors.name)}
                                helperText={
                                  errors.name ? 'Name is required' : ''
                                }
                                {...field}
                              ></TextField>
                            )}
                          ></Controller>
</code>```

答:
It looks like you use react-hook-from (https://react-hook-form.com/).

value and onChange should be inside of TextField like this.

```<code><Controller
  name="name"
  control={control}
  rules={{
    required: true,
  }}
  render={({ field, value, onChange }) => (
    <TextField
      value={value}
      onChange={onChange}
      variant="outlined"
      fullWidth
      id="name"
      label="Name"
      error={Boolean(errors.name)}
      helperText={
        errors.name ? 'Name is required' : ''
      }
      {...field}>
    </TextField>
  )}
/>

</code>```

Body:
I have this piece of code but that does not change value of input field when state changes.State changes when user clicks on a row. State is changing as i printed the value outside text field but that does not reflect in input field. I tried with value instead of defaultValue but it doesnt work.

                           <Controller
                            name="name"
                            control={control}
                            defaultValue={selectedRow.name}
                            value={selectedRow.name}
                            rules={{
                              required: true,
                            }}
                            render={({ field }) => (
                              <TextField
                                variant="outlined"
                                fullWidth
                                id="name"
                                label="Name"
                                error={Boolean(errors.name)}
                                helperText={
                                  errors.name ? 'Name is required' : ''
                                }
                                {...field}
                              ></TextField>
                            )}
                          ></Controller>

Body:
It looks like you use react-hook-from (https://react-hook-form.com/).

value and onChange should be inside of TextField like this.

<Controller
  name="name"
  control={control}
  rules={{
    required: true,
  }}
  render={({ field, value, onChange }) => (
    <TextField
      value={value}
      onChange={onChange}
      variant="outlined"
      fullWidth
      id="name"
      label="Name"
      error={Boolean(errors.name)}
      helperText={
        errors.name ? 'Name is required' : ''
      }
      {...field}>
    </TextField>
  )}
/>


问:
$(d).attr("id") is undefined javascript
I have a variable d that I use like this:

```<code>$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if ($(d).attr("id").substr(4,2) == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
}
</code>```

However I get the following error in firebug:

```

$(d).attr("id") is undefined
index.html    (L23)   (?)()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L21)   nodeName()([function(), function()], function(), undefined)
onreadystatechange()()

```

I really don't understand why. Does anyone know?

Edit

I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)

答:
Missing the closing bracket?</p>

```<code>$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if (i == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
// shouldn't the next line be });
}
</code>```

OwnerDisplayName: Proxify

ContentLicense: CC BY-SA 2.5

Title: $(d).attr("id") is undefined javascript

Body:
I have a variable d that I use like this:

$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if ($(d).attr("id").substr(4,2) == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
}

However I get the following error in firebug:

$(d).attr("id") is undefined
index.html    (L23)   (?)()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L21)   nodeName()([function(), function()], function(), undefined)
onreadystatechange()()

I really don't understand why. Does anyone know?

Edit

I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)

LastEditorDisplayName: Proxify

Body:
Missing the closing bracket?

$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if (i == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
// shouldn't the next line be });
}

OwnerDisplayName: gs


问:
Testing if all values in a numpy array are equal
I have a numpy one dimensional array c that is supposed to be filled with the contents of
a + b. I'm first executing a + b on a device using PyOpenCL.

I want to quickly determine the correctness of the result array c in python using numpy slicing.

This is what I currently have

```<code>def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"
</code>```

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But it seems a.any or a.all will just determine whether the values aren't 0.

What should I do if I want to test if all of the scalers in the numpy array temp are equal to every value in the numpy array c?

答:
You would call any on the result of the comparison: if np.any(a+b != c): or equivalently if np.all(a+b == c):.  a+b != c creates an array of dtype=bool, and then any looks at that array to see if any member is True.

```<code>>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,2])
>>> c = a+b
>>> c
array([5, 7, 5]) # <---- numeric, so any/all not useful
>>> a+b == c
array([ True,  True,  True], dtype=bool) # <---- BOOLEAN result, not numeric
>>> all(a+b == c)
True
</code>```

Having said all that, though, Amber's solution is probably faster since it doesn't have to create the whole boolean result array.

Body:
I have a numpy one dimensional array c that is supposed to be filled with the contents of
a + b. I'm first executing a + b on a device using PyOpenCL.

I want to quickly determine the correctness of the result array c in python using numpy slicing.

This is what I currently have

def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But it seems a.any or a.all will just determine whether the values aren't 0.

What should I do if I want to test if all of the scalers in the numpy array temp are equal to every value in the numpy array c?

Body:
You would call any on the result of the comparison: if np.any(a+b != c): or equivalently if np.all(a+b == c):.  a+b != c creates an array of dtype=bool, and then any looks at that array to see if any member is True.

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,2])
>>> c = a+b
>>> c
array([5, 7, 5]) # <---- numeric, so any/all not useful
>>> a+b == c
array([ True,  True,  True], dtype=bool) # <---- BOOLEAN result, not numeric
>>> all(a+b == c)
True

Having said all that, though, Amber's solution is probably faster since it doesn't have to create the whole boolean result array.


问:
Why do bootstrap tooltips not work in bootstrap modals?
My tooltips are working on the mainpage perfectly. In a modal which is generated later by an ajax call the tooltips won't work.

I have included the following code inside the generated modal (result of the ajax call).

To re-ini the tooltips

```<code><script>
  $('.tooltips').tooltip();
</script>
</code>```

In the html of the modal

```<code>  <button class="btn btn-lg default tooltips blue-madison" type="submit"
   name="O" data-container="body" data-placement="top"
   data-original-title="THIS TEXT FOR TOOLTIPS">
     <i class="fa fa-industry blue-madison"></i> BUTTON1
   </button>

  <button class="btn btn-lg default tooltips green-jungle" type="submit"
    name="P" data-container="body" data-placement="top"
    data-original-title="THIS TEXT FOR TOOLTIPS">
      <i class="fa fa-user green-jungle "></i> BUTTON2
  </button>
</code>```

Why don't the tooltips show- what I'm doing wrong?

答:
If you are using react I had success with a different answer. All you have to
do is give the parent container a ref and then in the overlayTrigger component you just have to pass in the ref as a param to the container.</p>
```<code>import React, { Component } from 'react';
import { OverlayTrigger, Tooltip } from 'react-bootstrap';

class random extends Component {
  constructor(props) {
    super(props);
    this.ref= React.createRef()

  }

  render() {
    return (
      <div ref={this.ref}>
            <OverlayTrigger
              placement="top"
              container={this.ref}
              overlay={
                <Tooltip data-container="body">Some text</Tooltip>
              }
            >
              <span className="d-inline-block">
                <i className="mdi mdi-help-circle pointer"></i>
              </span>
            </OverlayTrigger>
      </div>
    );
  }
}
</code>```

Body:
My tooltips are working on the mainpage perfectly. In a modal which is generated later by an ajax call the tooltips won't work.

I have included the following code inside the generated modal (result of the ajax call).

To re-ini the tooltips

In the html of the modal

  <button class="btn btn-lg default tooltips blue-madison" type="submit"
   name="O" data-container="body" data-placement="top"
   data-original-title="THIS TEXT FOR TOOLTIPS">
      BUTTON1
   </button>

  <button class="btn btn-lg default tooltips green-jungle" type="submit"
    name="P" data-container="body" data-placement="top"
    data-original-title="THIS TEXT FOR TOOLTIPS">
       BUTTON2
  </button>

Why don't the tooltips show- what I'm doing wrong?

Body:
If you are using react I had success with a different answer. All you have to
do is give the parent container a ref and then in the overlayTrigger component you just have to pass in the ref as a param to the container.

import React, { Component } from 'react';
import { OverlayTrigger, Tooltip } from 'react-bootstrap';

class random extends Component {
  constructor(props) {
    super(props);
    this.ref= React.createRef()

  }

  render() {
    return (
      <div ref={this.ref}>
            <OverlayTrigger
              placement="top"
              container={this.ref}
              overlay={
                <Tooltip data-container="body">Some text</Tooltip>
              }
            >
              <span className="d-inline-block">
                <i className="mdi mdi-help-circle pointer"></i>
              </span>
            </OverlayTrigger>
      </div>
    );
  }
}


问:
Split comma separated values based on another table
I would like to split comma separated values based on another table

I cannot normalize it since original table has over 8 million rows. It crushed my laptop when I tried it.

How can I put data into relevant columns and create a new column if data is not found.

For example:

TableA,

```<code>Type1        Type2
---------------------
 A            F
 B            G
 C            H
 D            I
 E           NULL
</code>```

TableB

```<code>ID     Country     AllTypes
---------------------------------
1       Italy      A, B, C
2       USA        D, E, A, F
4       Japan      I, O, Z
5       UK         NULL
</code>```

By using these two tables, I would like to get the output such as

```<code>ID     Country     AllTypes          Type1        Type2    UnCaptured
----------------------------------------------------------------------
1       Italy      A, B, C           A, B, C       NULL     NULL
2       USA        D, E, G, F        D, E          G, F     NULL
4       Japan      I, O, Z           NULL          I        O, Z
5       UK         NULL              NULL          NULL     NULL
</code>```

This is I have done so far

```<code>with TableA as (
  select 'A' as Type1, 'F' as Type2 union all
  select 'B', 'G' union all
  select 'C', 'H' union all
  select 'D', 'I' union all
  select 'E', NULL
),
TableB as (
  select 1 as ID, 'Italy' as Country, 'A, B, C' as Alltypes union all
  select 2, 'USA', 'D, E, A, F' union all
  select 4, 'Japan', 'I', 'O', 'Z' union all
  select 5, 'UK', NULL
)

select b.Id, b.Country, b.Alltypes,
    String_Agg(v.type1,',') Type1,
    String_Agg(v.type2,',') Type2
    **String_Agg(v.Type3,',') Uncaptured*** ------- This query

from tableb b
outer apply (
    select Trim(value) t,
        case when exists
          (select * from tablea a where a.type1=Trim(value))
        then Trim(value) end type1,
        case when exists
          (select * from tablea a where a.type2=Trim(value))
        then Trim(value) end Type2,
        Case when not exists                                  ------------This query
          ( (select * from tablea a where a.type1=Trim(value)) -------
             and                                               ------
             (select * from tablea a where a.type2=Trim(value))------
          ) then Trim(value) end Type3**                        -------------
    from String_Split(alltypes, ',')
)v
group by Id, Country, AllTypes
</code>```

Without highlighted queries(-----) which are for creating a new column (Uncaptured), it works ok like below.

```<code>Id  Country Alltypes    Type1   Type2
1   Italy   A, B, C     A,B,C   NULL
2   USA     D, E, A, F  D,E,A   F
4   Japan   I, O, Z     I       NULL
5   UK      NULL        NULL    NULL
</code>```

But if I add those highlighted queries, it shows error. I was also thinking of else but did not work as well.

Could someone help me please?

答:
```<code>----------------------- DDL+DML: Should have been provided by the OP !
DROP TABLE IF EXISTS TableA,TableB
GO

create table TableA(Type1 CHAR(1), Type2 char(1))
GO
INSERT TableA (Type1,Type2) VALUES
    ('A', 'F'  ),
    ('B', 'G'  ),
    ('C', 'H'  ),
    ('D', 'I'  ),
    ('E', NULL )
GO

CREATE TABLE TableB (ID INT, Country NVARCHAR(100), AllTypes NVARCHAR(100))
GO
INSERT TableB (ID,Country,AllTypes)VALUES
(1, 'Italy','A, B, C'     ),
(2, 'USA  ','D, E, G, F'  ),
(4, 'Japan','I, O, Z'     ),
(5, 'UK   ','NULL'        )
GO

----------------------- Solution
;WITH MyCTE AS (
    SELECT ID,Country,AllTypes, MyType = TRIM([value])
    FROM TableB
    CROSS APPLY string_split(AllTypes,',')
)
,MyCTE02 as (
    SELECT ID,Country,AllTypes, MyType,a1.Type1,a2.Type2,
        UnCaptured = CASE WHEN a1.Type1 IS NULL and a2.Type2 IS NULL THEN MyType END
    FROM MyCTE c
    LEFT JOIN TableA a1 ON c.MyType = a1.Type1
    LEFT JOIN TableA a2 ON c.MyType = a2.Type2
)
SELECT ID,Country,AllTypes--,MyType
    ,Type1 = STRING_AGG(Type1,','),Type2 = STRING_AGG(Type2,','),UnCaptured = STRING_AGG(UnCaptured,',')
FROM MyCTE02
GROUP BY ID,Country,AllTypes
GO
</code>```

Body:
I would like to split comma separated values based on another table

I cannot normalize it since original table has over 8 million rows. It crushed my laptop when I tried it.

How can I put data into relevant columns and create a new column if data is not found.

For example:

TableA,

Type1        Type2
---------------------
 A            F
 B            G
 C            H
 D            I
 E           NULL

TableB

ID     Country     AllTypes
---------------------------------
1       Italy      A, B, C
2       USA        D, E, A, F
4       Japan      I, O, Z
5       UK         NULL

By using these two tables, I would like to get the output such as

ID     Country     AllTypes          Type1        Type2    UnCaptured
----------------------------------------------------------------------
1       Italy      A, B, C           A, B, C       NULL     NULL
2       USA        D, E, G, F        D, E          G, F     NULL
4       Japan      I, O, Z           NULL          I        O, Z
5       UK         NULL              NULL          NULL     NULL

This is I have done so far

with TableA as (
  select 'A' as Type1, 'F' as Type2 union all
  select 'B', 'G' union all
  select 'C', 'H' union all
  select 'D', 'I' union all
  select 'E', NULL
),
TableB as (
  select 1 as ID, 'Italy' as Country, 'A, B, C' as Alltypes union all
  select 2, 'USA', 'D, E, A, F' union all
  select 4, 'Japan', 'I', 'O', 'Z' union all
  select 5, 'UK', NULL
)

select b.Id, b.Country, b.Alltypes,
    String_Agg(v.type1,',') Type1,
    String_Agg(v.type2,',') Type2
    **String_Agg(v.Type3,',') Uncaptured*** ------- This query

from tableb b
outer apply (
    select Trim(value) t,
        case when exists
          (select * from tablea a where a.type1=Trim(value))
        then Trim(value) end type1,
        case when exists
          (select * from tablea a where a.type2=Trim(value))
        then Trim(value) end Type2,
        Case when not exists                                  ------------This query
          ( (select * from tablea a where a.type1=Trim(value)) -------
             and                                               ------
             (select * from tablea a where a.type2=Trim(value))------
          ) then Trim(value) end Type3**                        -------------
    from String_Split(alltypes, ',')
)v
group by Id, Country, AllTypes

Without highlighted queries(-----) which are for creating a new column (Uncaptured), it works ok like below.

Id  Country Alltypes    Type1   Type2
1   Italy   A, B, C     A,B,C   NULL
2   USA     D, E, A, F  D,E,A   F
4   Japan   I, O, Z     I       NULL
5   UK      NULL        NULL    NULL

But if I add those highlighted queries, it shows error. I was also thinking of else but did not work as well.

Could someone help me please?


问:
How to build gradle subprojects with consistent command?
I'm trying to create a parameterised jenkins task that can build any of my projects. My projects have some stuff in common, so they are organised under the one hierarchy:

```<code>---p1
 |-p2
 |-p3
 |-p4
 |-p5--p5a
     |-p5b
</code>```

so I build any of p1-p4 with a command like:

```<code>gradle :${project}:bootWar
</code>```

and I have in my top level settings.gradle:

```<code>include 'p1', 'p2', 'p3', 'p4', 'p5:p5a', 'p5:p5b'
</code>```

but p5 is different, it has 2 sub projects. I can't build p5 with the above command, because it says:

Task 'bootWar' not found in project ':p5'.

This seems odd, because I can do:

```<code>cd p5 ; gradle bootWar
</code>```

and that somehow works, it calls the bootWar task in the 2 subprojects. But it's not really convenient to do that in Jenkins.

How can I configure gradle, so that I can be in the top level folder, and enter

```<code>gradle :p5:bootWar
</code>```

and have it do the bootWar task in both sub projects?

答:
I found that the following build.gradle in the p5 subdirectory works...

```<code>tasks.register("bootWar") {
  dependsOn(':p5:p5a:bootWar')
  dependsOn(':p5:p5b:bootWar')
}

tasks.register("clean") {
  dependsOn(':p5:p5a:clean')
  dependsOn(':p5:p5b:clean')
}
</code>```

This is not ideal because every conceivable task has to be listed in build.gradle. For some reason with only a single level hierarchy gradle seems able to deal with it automatically.

Body:
I'm trying to create a parameterised jenkins task that can build any of my projects. My projects have some stuff in common, so they are organised under the one hierarchy:

---p1
 |-p2
 |-p3
 |-p4
 |-p5--p5a
     |-p5b

so I build any of p1-p4 with a command like:

gradle :${project}:bootWar

and I have in my top level settings.gradle:

include 'p1', 'p2', 'p3', 'p4', 'p5:p5a', 'p5:p5b'

but p5 is different, it has 2 sub projects. I can't build p5 with the above command, because it says:

Task 'bootWar' not found in project ':p5'.

This seems odd, because I can do:

cd p5 ; gradle bootWar

and that somehow works, it calls the bootWar task in the 2 subprojects. But it's not really convenient to do that in Jenkins.

How can I configure gradle, so that I can be in the top level folder, and enter

gradle :p5:bootWar

and have it do the bootWar task in both sub projects?

Body:
I found that the following build.gradle in the p5 subdirectory works...

tasks.register("bootWar") {
  dependsOn(':p5:p5a:bootWar')
  dependsOn(':p5:p5b:bootWar')
}

tasks.register("clean") {
  dependsOn(':p5:p5a:clean')
  dependsOn(':p5:p5b:clean')
}

This is not ideal because every conceivable task has to be listed in build.gradle. For some reason with only a single level hierarchy gradle seems able to deal with it automatically.


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
You can use grid on the scroll container to prevent the misalignment with the header, and align-self: center; to the content to align itself vertically inside the container and justify-self to align itself horizontally without being clipped. I've also changed overflow to overflow: auto; as you only need the vertical scrolling in your sample. I've included two snippets to show the behavior when the content is bigger than container and another one when content is smaller than smaller than scroll, both with the same code. See the snippets below:

Behavior when content is bigger than scroll:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: auto;
  height: 100%;
  display: grid;
}

.content {
  height: 1000px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  align-self: center;
  justify-self: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

Behavior when content is smaller than scroll(same code):

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: auto;
  height: 100%;
  display: grid;
}

.content {
  height: 1000px;
  width: 2000px;
  margin: 12px;
  border: 2px solid blue;
  align-self: center;
  justify-self: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

Body:
You can use grid on the scroll container to prevent the misalignment with the header, and align-self: center; to the content to align itself vertically inside the container and justify-self to align itself horizontally without being clipped. I've also changed overflow to overflow: auto; as you only need the vertical scrolling in your sample. I've included two snippets to show the behavior when the content is bigger than container and another one when content is smaller than smaller than scroll, both with the same code. See the snippets below:

Behavior when content is bigger than scroll:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: auto;
  height: 100%;
  display: grid;
}

.content {
  height: 1000px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  align-self: center;
  justify-self: center;
}

<div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div>

Behavior when content is smaller than scroll(same code):

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: auto;
  height: 100%;
  display: grid;
}

.content {
  height: 1000px;
  width: 2000px;
  margin: 12px;
  border: 2px solid blue;
  align-self: center;
  justify-self: center;
}

<div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div>


问:
Flutter FutureBuilder not triggered when onPressed of ElevatedButton runs
I'm facing an issue, my FutureBuilder widget is not firing when ElevatedButton's onPress is run.

Within that method I made a call to an http service. So the Future is being setted within onPress.

Here is the ElevatedButton snippet:

 ElevatedButton(
                      style:  ElevatedButton.styleFrom(
                        primary: Colors.red,
                        minimumSize: Size(size.width / 30,size.height / 15),
                        shadowColor: Colors.redAccent,
                        shape:  new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(15.0),
                        )
                      ),
                      onPressed: () {
                          FocusScope.of(context).unfocus();

                          _future = _searchRoutes.findProductsByNameAndCity(
                              createFilterProducts(_productNameController.text,
                            _cityNameController.text,
                            _ufController.text,
                            int.parse(_itensPerPageController.text),
                            _orderByController.text),
                            _authScreenRoutes.getLocalJwtToken()
                          );
                        },
                      child: Icon(Icons.search),
                  ),
```
<p>The method <code>findProductsByNameAndCity()</code> just return a List and it is working.</p>
<p>Here are the FutureBuilder:</p>
<pre class="lang-dart prettyprint-override"><code>Expanded(
                child:  FutureBuilder<List<Product>>(
                    future:  _future,
                    builder:  (context, snapshot) {
                      if(snapshot.hasData){
                        if(snapshot.data!.length <=0){
                          return Container(
                            alignment: Alignment.center,
                            width: size.width,
                            height: size.height,
                            child: setText("Oops, ainda não temos esse produto nessa cidade.", padding / 1.5),
                          );
                        }else{
                          return Padding(
                              padding: sidePadding,
                              child: Container(
                                width: size.width,
                                height: size.height,
                                child: ListView.builder(
                                  itemCount: snapshot.data!.length ,
                                  itemBuilder: (context, index){
                                    return ProductBox(
                                      product: snapshot.data![index],
                                    );
                                  },
                                ),
                              )
                          );
                        }

                      }else if(snapshot.connectionState == ConnectionState.waiting){
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: CircularProgressIndicator(),
                        );
                      }else if (!snapshot.hasData){
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: setText("Pesquise um produto.", padding / 1.5),
                        );
                      }else{
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: CircularProgressIndicator(),
                        );
                      }
                    }
                )
            ),
</code>```

I know the Http call is working because I debugged and when the breakpoint inside ElevatedButton takes me to inside the method findProductsByNameAndCity() I see the items that i am waiting to receive.

I dont understand why the FutureBuilder does not display the items.

What am I doing wrong?

答:
You missed setState

Try this:

```<code>   onPressed: () {
                          FocusScope.of(context).unfocus();

                          _future = _searchRoutes.findProductsByNameAndCity(
                              createFilterProducts(_productNameController.text,
                            _cityNameController.text,
                            _ufController.text,
                            int.parse(_itensPerPageController.text),
                            _orderByController.text),
                            _authScreenRoutes.getLocalJwtToken()
                          );
                          setState((){});
                        }
</code>```

Body:
I'm facing an issue, my FutureBuilder widget is not firing when ElevatedButton's onPress is run.

Within that method I made a call to an http service. So the Future is being setted within onPress.

Here is the ElevatedButton snippet:

 ElevatedButton(
                      style:  ElevatedButton.styleFrom(
                        primary: Colors.red,
                        minimumSize: Size(size.width / 30,size.height / 15),
                        shadowColor: Colors.redAccent,
                        shape:  new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(15.0),
                        )
                      ),
                      onPressed: () {
                          FocusScope.of(context).unfocus();

                          _future = _searchRoutes.findProductsByNameAndCity(
                              createFilterProducts(_productNameController.text,
                            _cityNameController.text,
                            _ufController.text,
                            int.parse(_itensPerPageController.text),
                            _orderByController.text),
                            _authScreenRoutes.getLocalJwtToken()
                          );
                        },
                      child: Icon(Icons.search),
                  ),

The method findProductsByNameAndCity() just return a List and it is working.

Here are the FutureBuilder:

Expanded(
                child:  FutureBuilder<List<Product>>(
                    future:  _future,
                    builder:  (context, snapshot) {
                      if(snapshot.hasData){
                        if(snapshot.data!.length <=0){
                          return Container(
                            alignment: Alignment.center,
                            width: size.width,
                            height: size.height,
                            child: setText("Oops, ainda não temos esse produto nessa cidade.", padding / 1.5),
                          );
                        }else{
                          return Padding(
                              padding: sidePadding,
                              child: Container(
                                width: size.width,
                                height: size.height,
                                child: ListView.builder(
                                  itemCount: snapshot.data!.length ,
                                  itemBuilder: (context, index){
                                    return ProductBox(
                                      product: snapshot.data![index],
                                    );
                                  },
                                ),
                              )
                          );
                        }

                      }else if(snapshot.connectionState == ConnectionState.waiting){
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: CircularProgressIndicator(),
                        );
                      }else if (!snapshot.hasData){
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: setText("Pesquise um produto.", padding / 1.5),
                        );
                      }else{
                        return Container(
                          alignment: Alignment.center,
                          width: size.width,
                          height: size.height,
                          child: CircularProgressIndicator(),
                        );
                      }
                    }
                )
            ),

I know the Http call is working because I debugged and when the breakpoint inside ElevatedButton takes me to inside the method findProductsByNameAndCity() I see the items that i am waiting to receive.

I dont understand why the FutureBuilder does not display the items.

What am I doing wrong?

Body:
You missed setState

Try this:

   onPressed: () {
                          FocusScope.of(context).unfocus();

                          _future = _searchRoutes.findProductsByNameAndCity(
                              createFilterProducts(_productNameController.text,
                            _cityNameController.text,
                            _ufController.text,
                            int.parse(_itensPerPageController.text),
                            _orderByController.text),
                            _authScreenRoutes.getLocalJwtToken()
                          );
                          setState((){});
                        }