问:
json from file to file in same style in oneline per line
i wanna convert a json file has text like this design json_text https://phponlines.com/result/e2j9RgRnm7

```<code>$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
var_dump(json_encode($json_decoded));
</code>```

then after i edit it to get same design again but i get different deisng instead in one line

```<code>[{"id":"1","name":"john","bd":[]},{"id":"2","name":"gary","bd":[1,2]}]
</code>```

but what i want is

```<code>[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]
</code>```

答:
As stated in my comments above, this is not particularly advisable, and writing any portion of a JSON file by hand is even more inadvisable.

But if you do not wish to see the light, then at least the use the minimal amount of darkness.

// polyfill for PHP<8.1
if (!function_exists('array_is_list')) {
    function array_is_list(array $a)     {
        return $a === [] || (array_keys($a) === range(0, count($a) - 1));
    }
}

function do_weird_json(array $input) {
    if( ! array_is_list($input) ) {
        throw new Exception('Input data must be a list');
    }

    return sprintf("[\n%s\n]\n", implode(",\n", array_map('json_encode', $input)));
}

$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);

$json_decoded[1]['name'] = 'bill';

var_dump(do_weird_json($json_decoded));
```
<p>Output:</p>
```string(74) "[
{"id":"1","name":"john","bd":[]},
{"id":"2","name":"bill","bd":[1,2]}
]
"
```

Again, the best thing to do would be to leave the JSON as the default, not-human-friendly format and use a client-side tool like jq, etc to reformat the JSON for you for viewing purposes.

Body:
i wanna convert a json file has text like this design json_text https://phponlines.com/result/e2j9RgRnm7

$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
var_dump(json_encode($json_decoded));

then after i edit it to get same design again but i get different deisng instead in one line

[{"id":"1","name":"john","bd":[]},{"id":"2","name":"gary","bd":[1,2]}]

but what i want is

[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]

Body:
As stated in my comments above, this is not particularly advisable, and writing any portion of a JSON file by hand is even more inadvisable.

But if you do not wish to see the light, then at least the use the minimal amount of darkness.

// polyfill for PHP<8.1
if (!function_exists('array_is_list')) {
    function array_is_list(array $a)     {
        return $a === [] || (array_keys($a) === range(0, count($a) - 1));
    }
}

function do_weird_json(array $input) {
    if( ! array_is_list($input) ) {
        throw new Exception('Input data must be a list');
    }

    return sprintf("[\n%s\n]\n", implode(",\n", array_map('json_encode', $input)));
}

$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);

$json_decoded[1]['name'] = 'bill';

var_dump(do_weird_json($json_decoded));

Output:

string(74) "[
{"id":"1","name":"john","bd":[]},
{"id":"2","name":"bill","bd":[1,2]}
]
"

Again, the best thing to do would be to leave the JSON as the default, not-human-friendly format and use a client-side tool like jq, etc to reformat the JSON for you for viewing purposes.


来源: stackexchange

问:
"Docker Desktop stopped..." message after installation
Installed docker desktop for windows, after having installed the linux kernel update package and changing to wsl 2 version (virtualization is enabled) but i get the message "Docker Desktop stopped..." as shown below.

Tried:

uninstalling and reinstalling again

run application as administrator

答: I had the same problem. If you are using docker 4.5.0, try uninstall and install 4.4.4 instead. That worked for me.</p>

ContentLicense: CC BY-SA 4.0


问:
Update Gradle in Flutter project
I have this project in Flutter, but I haven't been able to build an apk for a couple of weeks, because of the Gradle version. I've tried everything, but Flutter always returns the error below:

I already install every update I found, even though, it shows that the Gradle version is 4.10.2.

flutter build apk

```<code>...
FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\israel.gomes\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\audioplayers-0.17.4\android\build.gradle' line: 25

* What went wrong:
A problem occurred evaluating root project 'audioplayers'.
> Failed to apply plugin [id 'kotlin-android']
   > The current Gradle version 4.10.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 5.3 or newer, or the previous version of the Kotlin plugin.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

The plugin audioplayers could not be built due to the issue above.

</code>```

Here some information about the project status and environment----------------------

Already changed gradle-wrapper.properties (Current file):

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip
</code>```

android/build.gradle(Current file):

```<code>buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
.
.
.
</code>```

gradle --version

```<code>------------------------------------------------------------
Gradle 5.6.2
------------------------------------------------------------

Build time:   2019-09-05 16:13:54 UTC
Revision:     55a5e53d855db8fc7b0e494412fc624051a8e781

Kotlin:       1.3.41
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.14 compiled on March 12 2019
JVM:          1.8.0_261 (Oracle Corporation 25.261-b12)
OS:           Windows 10 10.0 amd64

</code>```

flutter doctor -v

```<code>[√] Flutter (Channel dev, 2.1.0-12.1.pre, on Microsoft Windows [versÃ£o 10.0.19042.867], locale pt-BR)
    • Flutter version 2.1.0-12.1.pre at C:\Flutter
    • Framework revision 8264cb3e8a (3 weeks ago), 2021-03-10 12:37:57 -0800
    • Engine revision 711ab3fda0
    • Dart version 2.13.0 (build 2.13.0-116.0.dev)

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at C:\Users\israel.gomes\AppData\Local\Android\Sdk
    • Platform android-30, build-tools 30.0.2
    • ANDROID_HOME = C:\Users\israel.gomes\AppData\Local\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] IntelliJ IDEA Community Edition (version 2020.3)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.3
    • Flutter plugin version 55.0.4
    • Dart plugin version 203.7759

[√] VS Code (version 1.54.3)
    • VS Code at C:\Users\israel.gomes\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.20.0

[√] Connected device (3 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 7.1.1 (API 25) (emulator)
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 89.0.4389.114
    • Edge (web)                         • edge          • web-javascript • Microsoft Edge 87.0.664.75

• No issues found!

</code>```

答:
Upgrade gradle in a Flutter project.
Open the file gradle-wrapper.properties located at {yourProjectName}/android/gradle/wrapper/gradle-wrapper.properties and replace the distributionUrl by changing the gradle version.

For example if you want to upgrade gradle from version 5.1.1 to 6.1.1, change the Url from https\://services.gradle.org/distributions/gradle-5.1.1-all.zip to https\://services.gradle.org/distributions/gradle-6.1.1-all.zip and rebuild your app.

Title: Update Gradle in Flutter project

Body:
I have this project in Flutter, but I haven't been able to build an apk for a couple of weeks, because of the Gradle version. I've tried everything, but Flutter always returns the error below:

I already install every update I found, even though, it shows that the Gradle version is 4.10.2.

flutter build apk

...
FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\israel.gomes\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\audioplayers-0.17.4\android\build.gradle' line: 25

* What went wrong:
A problem occurred evaluating root project 'audioplayers'.
> Failed to apply plugin [id 'kotlin-android']
   > The current Gradle version 4.10.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 5.3 or newer, or the previous version of the Kotlin plugin.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

The plugin audioplayers could not be built due to the issue above.

Here some information about the project status and environment----------------------

Already changed gradle-wrapper.properties (Current file):

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip

android/build.gradle(Current file):

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
.
.
.

gradle --version

------------------------------------------------------------
Gradle 5.6.2
------------------------------------------------------------

Build time:   2019-09-05 16:13:54 UTC
Revision:     55a5e53d855db8fc7b0e494412fc624051a8e781

Kotlin:       1.3.41
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.14 compiled on March 12 2019
JVM:          1.8.0_261 (Oracle Corporation 25.261-b12)
OS:           Windows 10 10.0 amd64

flutter doctor -v

[√] Flutter (Channel dev, 2.1.0-12.1.pre, on Microsoft Windows [versÃ£o 10.0.19042.867], locale pt-BR)
    • Flutter version 2.1.0-12.1.pre at C:\Flutter
    • Framework revision 8264cb3e8a (3 weeks ago), 2021-03-10 12:37:57 -0800
    • Engine revision 711ab3fda0
    • Dart version 2.13.0 (build 2.13.0-116.0.dev)

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at C:\Users\israel.gomes\AppData\Local\Android\Sdk
    • Platform android-30, build-tools 30.0.2
    • ANDROID_HOME = C:\Users\israel.gomes\AppData\Local\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] IntelliJ IDEA Community Edition (version 2020.3)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.3
    • Flutter plugin version 55.0.4
    • Dart plugin version 203.7759

[√] VS Code (version 1.54.3)
    • VS Code at C:\Users\israel.gomes\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.20.0

[√] Connected device (3 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 7.1.1 (API 25) (emulator)
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 89.0.4389.114
    • Edge (web)                         • edge          • web-javascript • Microsoft Edge 87.0.664.75

• No issues found!


问:
Maximum Stack Size for C/C+ Program?
I've tried the below program. The intent by which this program was created is to discover more about stack sizes.

```<code>int main()
{
    int nStack[100000000];
    return 0;
}
</code>```

After executing the above code, the program crashes due to huge stack size allocation.
What is the maximum possible size of the stack? Is it fixed for every program/computer? Can it be increased?

I want to know for the sake of knowledge. If anyone can provide examples in C/C++, it would be very helpful.

答:
Before the days of virtual memory, for example in V7 Unix, I don't believe there was a fixed limit for the stack.  The stack grew downwards from the top of memory, and the heap grew upwards from the bottom (well, from the top of the text+data spaces, anyway), and as long as they didn't meet ("don't let the beams cross!" :-) ), you were fine.

What there was a limit on was how much the stack could grow at once.  If you had a function that allocated, say a 1K local variable, you could call it recursively several dozen times before things went south.  But if you had a function that allocated a 10K local variable, it tended to crash at once.

What was happening was that the OS was noticing whether your stack accesses exceeded the bounds of what had been allocated for the stack already.  If you went past the end of the stack by a relatively small amount, the OS assumed that the stack was growing, and it allocated a little more for you.  But if you tried to grow the stack by a lot all at once, what you got was something that looked like a stray pointer reference, midway between the top of the stack and the top of the heap, and you got a segmentation violation instead.

(This is from memory, so I could be wrong on the details.  If I ever boot up the old PDP-11 again, I'll have to remember to test this out.)

ContentLicense: CC BY-SA 3.0

Title: Maximum Stack Size for C/C+ Program?

Body:
I've tried the below program. The intent by which this program was created is to discover more about stack sizes.

int main()
{
    int nStack[100000000];
    return 0;
}

After executing the above code, the program crashes due to huge stack size allocation.
What is the maximum possible size of the stack? Is it fixed for every program/computer? Can it be increased?

I want to know for the sake of knowledge. If anyone can provide examples in C/C++, it would be very helpful.


问:
MS Graph API / Planner - Query all Task Details for a Plan
I'm trying to get all the "Task Details" for a give "Plan".

I can get the "Plan", "Buckets", "Tasks" using {plan-id}
https://graph.microsoft.com/beta/planner/plans/eAk8BBGJfU6e2_SQexZPtxxxxxx
https://graph.microsoft.com/beta/planner/plans/eAk8BBGJfU6e2_SQexZPtxxxxxx/buckets
https://graph.microsoft.com/beta/planner/plans/eAk8BBGJfU6e2_SQexZPtxxxxxx/tasks

But the "Task Details" uses {task-id}
https://graph.microsoft.com/beta/planner/tasks/{task-id}/details

Is there a way to write a single query that will return all the task details for all tasks in the plan?

Cheers, Mike

答:
You can now expand details when reading tasks in plan. /plans/id/tasks?$expand=details

Outdated previous reply:

We don't currently have a way to get this information in a single
request right now. The standard way is to get the tasks, then make
separate calls for the details of the tasks that you are interested
in. We're evaluating whether this is something that should be added.
If you don't mind, can you explain your high-level scenario and what
kind of information you are interested in task details? That would
provide valuable information for the decision-making process.


问:
Heroku BeautifulSoup + cloudscraper don't bypass cloudflare on server side
i'm using BeautifulSoup + cloudscraper to scrap a site. The problem is in local it's working but on heroku server it doesn't work.

It's look like when i launch the script via heroku server the JS or cookie are not enable. That why in local cloudscraper can bypass cloudflare and not on heroku.

My code:

```<code> import requests
 import cloudscraper
 from bs4 import BeautifulSoup

 session = requests.session()
 scraper = cloudscraper.create_scraper(browser='chrome', sess=session)
 contract_page = scraper.get("https://bscscan.com/token/0x30e650783b4046c64dcf3b7b78854f3d4a87b058",
        headers = {
            'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
            'Cache-Control': "no-cache",
        })
  soupa = BeautifulSoup(contract_page.content, 'html.parser')
  print(soupa)
  tokenholders = soupa.find(id='ContentPlaceHolder1_tr_tokenHolders').get_text()
</code>```

the print of soupa give me this HTML page:

Someone have idea how to enable JS or cookie from a heroku server that run the script please ?

答: After many tried i found a solution, to bypass it we have to use a proxy to change the IP of heroku server.</p>

Body:
i'm using BeautifulSoup + cloudscraper to scrap a site. The problem is in local it's working but on heroku server it doesn't work.

It's look like when i launch the script via heroku server the JS or cookie are not enable. That why in local cloudscraper can bypass cloudflare and not on heroku.

My code:

 import requests
 import cloudscraper
 from bs4 import BeautifulSoup

 session = requests.session()
 scraper = cloudscraper.create_scraper(browser='chrome', sess=session)
 contract_page = scraper.get("https://bscscan.com/token/0x30e650783b4046c64dcf3b7b78854f3d4a87b058",
        headers = {
            'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
            'Cache-Control': "no-cache",
        })
  soupa = BeautifulSoup(contract_page.content, 'html.parser')
  print(soupa)
  tokenholders = soupa.find(id='ContentPlaceHolder1_tr_tokenHolders').get_text()

the print of soupa give me this HTML page:

Someone have idea how to enable JS or cookie from a heroku server that run the script please ?


问:
CSS 'scroll-snap' troubleshooting
I'm trying to do simple scroll-snap css on my horizontal scrolling webpage, but it's not working. Any ideas on what to do? My webpage is jakobnatorp.com. It seems like scroll-snap-type and scroll-snap-align are not valid commands, they are marked with red in my css-tool. I'm using a css plug-in for wordpress.

CSS

```<code>/* master container */
  .elementor {
  width: 100vh;
  height: 100vw;
  overflow-x: auto;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
  scroll-snap-type: x mandatory;
  scroll-snap-type: mandatory;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  -ms-overflow-style: none;
}

/* sub-container */
.elementor-section-wrap {
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  display:flex;
  flex-direction: row;
  width: 580vw;
}

/* sections */
.section {
width:80vw;
height:100vh;
scroll-snap-align: start;
}
</code>```

All help is appreciated!

答: Had an issue with scroll-snap taking effect, turns out adding scroll-snap-type to the parent wouldn't work, I had to add it to the html. Also having overflow hidden on the html will disable scroll-snap.</p>

Title: CSS 'scroll-snap' troubleshooting

Body:
I'm trying to do simple scroll-snap css on my horizontal scrolling webpage, but it's not working. Any ideas on what to do? My webpage is jakobnatorp.com. It seems like scroll-snap-type and scroll-snap-align are not valid commands, they are marked with red in my css-tool. I'm using a css plug-in for wordpress.

CSS

/* master container */
  .elementor {
  width: 100vh;
  height: 100vw;
  overflow-x: auto;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
  scroll-snap-type: x mandatory;
  scroll-snap-type: mandatory;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  -ms-overflow-style: none;
}

/* sub-container */
.elementor-section-wrap {
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  display:flex;
  flex-direction: row;
  width: 580vw;
}

/* sections */
.section {
width:80vw;
height:100vh;
scroll-snap-align: start;
}

All help is appreciated!


问:
Html Paragraph element is not responsive with dynamic text inside
i am building this machinery page for someone and i came across this issue, i am using the latest version of tailwind css and react btw.

For now i am using a plain object to store the items, like this:

```<code>const machinery = [{
    image: Machine1,
    name: "Name",
    description: "alkjfaskldjfhaklsd",
    idx: 0
}]
</code>```

I map this data like this:

```<code><div className="flex flex-col">
    {machinery.map((machine) => {
      return (
        <div key={machine.idx}>
          <p className="text-2xl tex-slate-900 font-Spartan font-semibold">
            {machine.name}
          </p>
          <p className="text-base text-slate-600 font-Spartan font-medium">
            {machine.description}
          </p>
        </div>
      );
    })}
  </div>
</code>```

Now the issue is that the description text (the secon

 tag) is overflowing the screen (it stays in one line) when it gets smaller, the thing is, if i don't render the text inside like this
{machinery.description}
 but instead i render it normally like this
kljaklsjdfhka
 the text actually splits and does not overflow the screen.

Here is an example:

Dynamically rendered text

```<code>-------------|
asdjfhsakdfjh|adkjadfjkhsgd <- the text (it overflows)
             |
             | <- screen border
-------------|
</code>```

Normally rendered text

```<code>-------------|
asdjfhsakdfjh|
adkjadfjkhsgd|<- the text (it does not overflow)
             |
             |<- screen border
-------------|
</code>```

答:
You can use the CSS word-wrap: break-word; on the parrent div of the text, in this example you could add a class or id to your
 like this:

```<code>    <style>
    .putYourClassNameHere {
          word-wrap: break-word;
    }
    </style>
        <div className="flex flex-col">
        {machinery.map((machine) => {
          return (
            <div id="putYourClassNameHere" key={machine.idx}>
              <p className="text-2xl tex-slate-900 font-Spartan font-semibold">
                {machine.name}
              </p>
              <p className="text-base text-slate-600 font-Spartan font-medium">
                {machine.description}
              </p>
            </div>
          );
        })}
      </div>
</code>```

Body:
i am building this machinery page for someone and i came across this issue, i am using the latest version of tailwind css and react btw.

For now i am using a plain object to store the items, like this:

const machinery = [{
    image: Machine1,
    name: "Name",
    description: "alkjfaskldjfhaklsd",
    idx: 0
}]

I map this data like this:

    {machinery.map((machine) => {
      return (

            {machine.name}

            {machine.description}

      );
    })}

Now the issue is that the description text (the secon

 tag) is overflowing the screen (it stays in one line) when it gets smaller, the thing is, if i don't render the text inside like this
{machinery.description}
 but instead i render it normally like this
kljaklsjdfhka
 the text actually splits and does not overflow the screen.

Here is an example:

Dynamically rendered text

-------------|
asdjfhsakdfjh|adkjadfjkhsgd <- the text (it overflows)
             |
             | <- screen border
-------------|

Normally rendered text

-------------|
asdjfhsakdfjh|
adkjadfjkhsgd|<- the text (it does not overflow)
             |
             |<- screen border
-------------|

Body:
You can use the CSS word-wrap: break-word; on the parrent div of the text, in this example you could add a class or id to your <div key={machine.idx}> like this:

    <style>
    .putYourClassNameHere {
          word-wrap: break-word;
    }
    </style>
        <div className="flex flex-col">
        {machinery.map((machine) => {
          return (
            <div id="putYourClassNameHere" key={machine.idx}>
              <p className="text-2xl tex-slate-900 font-Spartan font-semibold">
                {machine.name}
              </p>
              <p className="text-base text-slate-600 font-Spartan font-medium">
                {machine.description}
              </p>
            </div>
          );
        })}
      </div>


问:
Can you use a POST to GET data?
A company is asking me to do an Angular assignment. They provide the following instructions, but the API URL doesn't work:

```<code>Create a single page angular application and use the following API to retrieve sports results and sort into a table of results that are displayed. Each sport result contains several data and always includes the publication time.
Method: POST
Content-Type: application/json
Url: https://ancient-wood-1161.getsandbox.com:443/results
Tasks:
-Display the sports results in reverse chronological order on the page.
-Add a filter to the page to display only certain types or events (e.g. f1Results)
-How can you confirm the code works?
-Bonus: Implement the rest call asynchronously
</code>```

You can click the URL https://ancient-wood-1161.getsandbox.com:443/results right now and see that it doesn't work - it returns {"errors":[{"message":"Error processing request"}]} and in Angular it gives me a standard CORS error.

I asked the company to please send a working URL and/or update the API to accept requests from everywhere. Their response was:
*guy's name* confirmed it worked. It is a post and the content type is json.

Can you use a POST request to GET data?

答: Yes, you can. On some cases it may be necessary, since GET doesn't take a body while POST does. So it can get you around things like URL length limits.</p>

Title: Can you use a POST to GET data?

Body:
A company is asking me to do an Angular assignment. They provide the following instructions, but the API URL doesn't work:

Create a single page angular application and use the following API to retrieve sports results and sort into a table of results that are displayed. Each sport result contains several data and always includes the publication time.
Method: POST
Content-Type: application/json
Url: https://ancient-wood-1161.getsandbox.com:443/results
Tasks:
-Display the sports results in reverse chronological order on the page.
-Add a filter to the page to display only certain types or events (e.g. f1Results)
-How can you confirm the code works?
-Bonus: Implement the rest call asynchronously

You can click the URL https://ancient-wood-1161.getsandbox.com:443/results right now and see that it doesn't work - it returns {"errors":[{"message":"Error processing request"}]} and in Angular it gives me a standard CORS error.

I asked the company to please send a working URL and/or update the API to accept requests from everywhere. Their response was:
*guy's name* confirmed it worked. It is a post and the content type is json.

Can you use a POST request to GET data?


问:
Assign multiple o365 licenses to a single user using PowerShell
I'm using a simple Powershell script to add new users to O365 and assign a license. However im trying to add multiple licenses at once to a single user.

Powershell

```<code>Connect-MsolService -Credential $UserCredential

Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose
</code>```

.CSV

```<code>DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuId
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS
</code>```

For this example i'd like to add the EMS & ENTERPRISEPACK license to the test user.

答:
I use a simple script to add multiple licenses. Only information needed is the UPN, which in my environment is the mail address.

```<code>Connect-MsolService
Import-Csv 'C:\usersmailaddress.CSV' | foreach {Set-MsolUser -UserPrincipalName $_.EmailAdress -UsageLocation BR
Set-MsolUserLicense -UserPrincipalName $_.EmailAdress -AddLicenses mydomain:ENTERPRISEPACK
Set-MsolUserLicense -UserPrincipalName $_.EmailAdress -AddLicenses mydomain:EMS
}
</code>```

You can adapt it to your needs.

Body:
I'm using a simple Powershell script to add new users to O365 and assign a license. However im trying to add multiple licenses at once to a single user.

Powershell

Connect-MsolService -Credential $UserCredential

Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose

.CSV

DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuId
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS

For this example i'd like to add the EMS & ENTERPRISEPACK license to the test user.

Body:
I use a simple script to add multiple licenses. Only information needed is the UPN, which in my environment is the mail address.

Connect-MsolService
Import-Csv 'C:\usersmailaddress.CSV' | foreach {Set-MsolUser -UserPrincipalName $_.EmailAdress -UsageLocation BR
Set-MsolUserLicense -UserPrincipalName $_.EmailAdress -AddLicenses mydomain:ENTERPRISEPACK
Set-MsolUserLicense -UserPrincipalName $_.EmailAdress -AddLicenses mydomain:EMS
}

You can adapt it to your needs.


问:
Vs Code terminal on ZSH didn't display correctly the path
I'm having some troubles with the terminal of VS Code.
I'm currently on Manjaro 5.10.89-1, using VS Code 1.63.2. I've switched from BASH to ZSH. And if you are wondering I have no problem in the terminal of VS Code when I'm using BASH, but I truly want to use ZSH, first because I like it and second I need to see the branch I'm working on, directly on the path.

My issue is that the terminal of VS Code didn't display correctly the path (see the image under).

But on my console the path is correctly is displayed (I'm using Yakuake)

If you have some workaround I'll get it,
Thx ^^

答:
Changing ZSH theme resolved the problem.

I now use Oh My ZSH, with the theme "garyblessington"
I really recomand trying out Oh My ZSH, there are a lot of cool things,


问:
MSBuild ClickOnce error: "Deployment and application do not have matching security zones"
We're trying to publish a ClickOnce application through MSBuild. We've got it working fine for an installed version of the Windows application.

However, when we set install to false, so that it just runs the application from the web, we get the following error when we try to run the application from the URL: "Deployment and application do not have matching security zones" This works fine in Internet Explorer. We only get the error message in Chrome and FireFox.

Here is a sample of the project file settings.

```<code><Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <SrcTreeRoot>$(MSBuildProjectDirectory)\..\..\..</SrcTreeRoot>
    <!--ClickOnceDeployFolder>$(WebOutputDir)\AnalyzerPC</ClickOnceDeployFolder-->
    <ProjectGuid>{8205E593-F400-41AE-8D6F-DEA290B2DCF9}</ProjectGuid>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ApplicationIcon>Graphics\EDA Icon.ico</ApplicationIcon>
    <AssemblyName>DASHQueryBuilder</AssemblyName>
    <OutputType>WinExe</OutputType>
    <RootNamespace>TetraData.Analyzer</RootNamespace>
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <OldToolsVersion>2.0</OldToolsVersion>
    <IsWebBootstrapper>false</IsWebBootstrapper>
    <ManifestCertificateThumbprint>...</ManifestCertificateThumbprint>
    <GenerateManifests>true</GenerateManifests>
    <SignManifests>true</SignManifests>
    <SignAssembly>true</SignAssembly>
    <ManifestKeyFile>$(BuildDir)\Certificates\TetraDataCode.pfx</ManifestKeyFile>
    <ProductVersion>9.0.21022</ProductVersion>
    <PublishUrl>http://localhost/DASHQueryBuilder/</PublishUrl>
    <Install>false</Install>
    <!--InstallFrom>Web</InstallFrom-->
    <UpdateEnabled>false</UpdateEnabled>
    <MapFileExtensions>true</MapFileExtensions>
    <PublisherName>Follett Software Company</PublisherName>
    <TrustUrlParameters>true</TrustUrlParameters>
    <ApplicationRevision>0</ApplicationRevision>
    <UseApplicationTrust>false</UseApplicationTrust>
    <PublishWizardCompleted>true</PublishWizardCompleted>
    <BootstrapperEnabled>false</BootstrapperEnabled>
  </PropertyGroup>
  <Import Project="$(SrcTreeRoot)\Build\TaskInit.Tasks" />
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(SrcTreeRoot)\Build\TaskOverrides.Tasks" />
  <Import Project="$(MSBuildProjectDirectory)\Analyzer.csproj" />
  <PropertyGroup>
    <PublishDir>$(WebOutputDir)\DASH Query Builder\</PublishDir>
    <ApplicationVersion>$(MajorMinorVersion).0.0</ApplicationVersion>
  </PropertyGroup>
  <Target Name="BeforeResolveReferences">
    <Copy SourceFiles="$(MSBuildProjectDirectory)\DASHQueryBuilder.config" DestinationFiles="$(MSBuildProjectDirectory)\app.config" />
  </Target>
</Project>
</code>```

答:
Below  is Microsoft's answer to the thread I posted on their forum.  Basically they did support chrome back then, but now there is a plugin for Chrome here that works great.

Hi fbanderson,

I found an article talking about ClickOnce in Firefox.

http://windowsclient.net/wpf/wpf35/wpf-deploying-clickonce-ie-firefox.aspx

.NET Framework 3.5 SP1 offers a component called .NET Framework
  Assistant 1.0 which handles ClickOnce .applications. If you have
  installed that component, the dialog appear to you in FireFox should
  contain a “Run ClickOnce application” button. Do you see that button
  when you trying to launch the app?

For Google Chrome, we don’t have experience for it. It is a new
  browser and we lack test on it.

Sincerely,

Kira Qian

MSDN Subscriber Support in Forum

If you have any feedback on our support, please contact
  msdnmg@microsoft.com Please remember to mark the replies as answers if
  they help and unmark them if they provide no help. Welcome to the

Body:
We're trying to publish a ClickOnce application through MSBuild. We've got it working fine for an installed version of the Windows application.

However, when we set install to false, so that it just runs the application from the web, we get the following error when we try to run the application from the URL: "Deployment and application do not have matching security zones" This works fine in Internet Explorer. We only get the error message in Chrome and FireFox.

Here is a sample of the project file settings.

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <SrcTreeRoot>$(MSBuildProjectDirectory)\..\..\..</SrcTreeRoot>

    <ProjectGuid>{8205E593-F400-41AE-8D6F-DEA290B2DCF9}</ProjectGuid>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ApplicationIcon>Graphics\EDA Icon.ico</ApplicationIcon>
    <AssemblyName>DASHQueryBuilder</AssemblyName>
    <OutputType>WinExe</OutputType>
    <RootNamespace>TetraData.Analyzer</RootNamespace>
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <OldToolsVersion>2.0</OldToolsVersion>
    <IsWebBootstrapper>false</IsWebBootstrapper>
    <ManifestCertificateThumbprint>...</ManifestCertificateThumbprint>
    <GenerateManifests>true</GenerateManifests>
    <SignManifests>true</SignManifests>
    <SignAssembly>true</SignAssembly>
    <ManifestKeyFile>$(BuildDir)\Certificates\TetraDataCode.pfx</ManifestKeyFile>
    <ProductVersion>9.0.21022</ProductVersion>
    <PublishUrl>http://localhost/DASHQueryBuilder/</PublishUrl>
    <Install>false</Install>

    <UpdateEnabled>false</UpdateEnabled>
    <MapFileExtensions>true</MapFileExtensions>
    <PublisherName>Follett Software Company</PublisherName>
    <TrustUrlParameters>true</TrustUrlParameters>
    <ApplicationRevision>0</ApplicationRevision>
    <UseApplicationTrust>false</UseApplicationTrust>
    <PublishWizardCompleted>true</PublishWizardCompleted>
    <BootstrapperEnabled>false</BootstrapperEnabled>
  </PropertyGroup>
  <Import Project="$(SrcTreeRoot)\Build\TaskInit.Tasks" />
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(SrcTreeRoot)\Build\TaskOverrides.Tasks" />
  <Import Project="$(MSBuildProjectDirectory)\Analyzer.csproj" />
  <PropertyGroup>
    <PublishDir>$(WebOutputDir)\DASH Query Builder\</PublishDir>
    <ApplicationVersion>$(MajorMinorVersion).0.0</ApplicationVersion>
  </PropertyGroup>
  <Target Name="BeforeResolveReferences">
    <Copy SourceFiles="$(MSBuildProjectDirectory)\DASHQueryBuilder.config" DestinationFiles="$(MSBuildProjectDirectory)\app.config" />
  </Target>
</Project>


问:
InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified finding a href using CSSSelector and Selenium Python
I'm trying to get the property "href" i.e. "/kkanagas/status/1491996075573587994" from inside the

. I know it's long but I couldn't find another way to shortcut it. Just search for "href" and you'll see "/kkanagas/status/1491996075573587994" - it's what I'm looking for.

```

Karthik K

@kkanagas

·

                                  <time datetime="2022-02-11T04:42:39.000Z">1m</time>

                                                    <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                                       <g>
                                                          <circle cx="5" cy="12" r="2"></circle>
                                                          <circle cx="12" cy="12" r="2"></circle>
                                                          <circle cx="19" cy="12" r="2"></circle>
                                                       </g>
                                                    </svg>

#USA and #CZE are tied 0-0 at the end of the first period of this Women's Hockey QF.
                               #Beijing2022 #IceHockey

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M14.046 2.242l-4.148-.01h-.002c-4.374 0-7.8 3.427-7.8 7.802 0 4.098 3.186 7.206 7.465 7.37v3.828c0 .108.044.286.12.403.142.225.384.347.632.347.138 0 .277-.038.402-.118.264-.168 6.473-4.14 8.088-5.506 1.902-1.61 3.04-3.97 3.043-6.312v-.017c-.006-4.367-3.43-7.787-7.8-7.788zm3.787 12.972c-1.134.96-4.862 3.405-6.772 4.643V16.67c0-.414-.335-.75-.75-.75h-.396c-3.66 0-6.318-2.476-6.318-5.886 0-3.534 2.768-6.302 6.3-6.302l4.147.01h.002c3.532 0 6.3 2.766 6.302 6.296-.003 1.91-.942 3.844-2.514 5.176z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M23.77 15.67c-.292-.293-.767-.293-1.06 0l-2.22 2.22V7.65c0-2.068-1.683-3.75-3.75-3.75h-5.85c-.414 0-.75.336-.75.75s.336.75.75.75h5.85c1.24 0 2.25 1.01 2.25 2.25v10.24l-2.22-2.22c-.293-.293-.768-.293-1.06 0s-.294.768 0 1.06l3.5 3.5c.145.147.337.22.53.22s.383-.072.53-.22l3.5-3.5c.294-.292.294-.767 0-1.06zm-10.66 3.28H7.26c-1.24 0-2.25-1.01-2.25-2.25V6.46l2.22 2.22c.148.147.34.22.532.22s.384-.073.53-.22c.293-.293.293-.768 0-1.06l-3.5-3.5c-.293-.294-.768-.294-1.06 0l-3.5 3.5c-.294.292-.294.767 0 1.06s.767.293 1.06 0l2.22-2.22V16.7c0 2.068 1.683 3.75 3.75 3.75h5.85c.414 0 .75-.336.75-.75s-.337-.75-.75-.75z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M12 21.638h-.014C9.403 21.59 1.95 14.856 1.95 8.478c0-3.064 2.525-5.754 5.403-5.754 2.29 0 3.83 1.58 4.646 2.73.814-1.148 2.354-2.73 4.645-2.73 2.88 0 5.404 2.69 5.404 5.755 0 6.376-7.454 13.11-10.037 13.157H12zM7.354 4.225c-2.08 0-3.903 1.988-3.903 4.255 0 5.74 7.034 11.596 8.55 11.658 1.518-.062 8.55-5.917 8.55-11.658 0-2.267-1.823-4.255-3.903-4.255-2.528 0-3.94 2.936-3.952 2.965-.23.562-1.156.562-1.387 0-.014-.03-1.425-2.965-3.954-2.965z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M17.53 7.47l-5-5c-.293-.293-.768-.293-1.06 0l-5 5c-.294.293-.294.768 0 1.06s.767.294 1.06 0l3.72-3.72V15c0 .414.336.75.75.75s.75-.336.75-.75V4.81l3.72 3.72c.146.147.338.22.53.22s.384-.072.53-.22c.293-.293.293-.767 0-1.06z"></path>
                                                 <path d="M19.708 21.944H4.292C3.028 21.944 2 20.916 2 19.652V14c0-.414.336-.75.75-.75s.75.336.75.75v5.652c0 .437.355.792.792.792h15.416c.437 0 .792-.355.792-.792V14c0-.414.336-.75.75-.75s.75.336.75.75v5.652c0 1.264-1.028 2.292-2.292 2.292z"></path>
                                              </g>
                                           </svg>

                            **
**

```
<p>My code to try to find it:</p>
```try:
    tweets = wait.until(EC.presence_of_all_elements_located(
        (By.CSS_SELECTOR, "article[data-testid='tweet']a[href]")))
    links = [link.get_attribute('href')
             for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")
```
<p>Error:</p>
```selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=98.0.4758.82)
Stacktrace:
Backtrace:
    Ordinal0 [0x00977AC3+2587331]
    Ordinal0 [0x0090ADD1+2141649]
    Ordinal0 [0x00803BB8+1063864]
    Ordinal0 [0x008063D7+1074135]
    Ordinal0 [0x0080629E+1073822]
    Ordinal0 [0x00806510+1074448]
    Ordinal0 [0x0082FF42+1244994]
    Ordinal0 [0x008303CB+1246155]
    Ordinal0 [0x0085A64C+1418828]
    Ordinal0 [0x008486D4+1345236]
    Ordinal0 [0x00858A0A+1411594]
    Ordinal0 [0x008484A6+1344678]
    Ordinal0 [0x008253F6+1201142]
    Ordinal0 [0x008262E6+1204966]
    GetHandleVerifier [0x00B1DF22+1680738]
    GetHandleVerifier [0x00BD0DBC+2413564]
    GetHandleVerifier [0x00A0D151+563089]
    GetHandleVerifier [0x00A0BF13+558419]
    Ordinal0 [0x0091081E+2164766]
    Ordinal0 [0x00915508+2184456]
    Ordinal0 [0x00915650+2184784]
    Ordinal0 [0x0091F5BC+2225596]
    BaseThreadInitThunk [0x753FFA29+25]
    RtlGetAppContainerNamedObjectPath [0x76FE7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x76FE7A6E+238]
```

What seems to be wrong?

答:
This error message...

```<code>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
</code>```

...implies that the locator strategy you have used is not a valid locator strategy.

You nneed to insert a space between article[data-testid='tweet'] and a[href] to make it a valid locator strategy. So effectively your line of code would have been:

```<code>try:
    tweets = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "article[data-testid='tweet'] a[href]")))
    links = [link.get_attribute('href')
         for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")
</code>```

However, to extract the value of the href attribute i.e. /kkanagas/status/1491996075573587994 you can use the following locator strategy:

```<code>try:
    tweets = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "article[data-testid='tweet'] a[href*='status']")))
    links = [link.get_attribute('href')
     for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")
</code>```

Body:
I'm trying to get the property "href" i.e. "/kkanagas/status/1491996075573587994" from inside the

. I know it's long but I couldn't find another way to shortcut it. Just search for "href" and you'll see "/kkanagas/status/1491996075573587994" - it's what I'm looking for.

Karthik K

@kkanagas

·

                                  <time datetime="2022-02-11T04:42:39.000Z">1m</time>

                                                    <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                                       <g>
                                                          <circle cx="5" cy="12" r="2"></circle>
                                                          <circle cx="12" cy="12" r="2"></circle>
                                                          <circle cx="19" cy="12" r="2"></circle>
                                                       </g>
                                                    </svg>

#USA and #CZE are tied 0-0 at the end of the first period of this Women's Hockey QF.
                               #Beijing2022 #IceHockey

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M14.046 2.242l-4.148-.01h-.002c-4.374 0-7.8 3.427-7.8 7.802 0 4.098 3.186 7.206 7.465 7.37v3.828c0 .108.044.286.12.403.142.225.384.347.632.347.138 0 .277-.038.402-.118.264-.168 6.473-4.14 8.088-5.506 1.902-1.61 3.04-3.97 3.043-6.312v-.017c-.006-4.367-3.43-7.787-7.8-7.788zm3.787 12.972c-1.134.96-4.862 3.405-6.772 4.643V16.67c0-.414-.335-.75-.75-.75h-.396c-3.66 0-6.318-2.476-6.318-5.886 0-3.534 2.768-6.302 6.3-6.302l4.147.01h.002c3.532 0 6.3 2.766 6.302 6.296-.003 1.91-.942 3.844-2.514 5.176z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M23.77 15.67c-.292-.293-.767-.293-1.06 0l-2.22 2.22V7.65c0-2.068-1.683-3.75-3.75-3.75h-5.85c-.414 0-.75.336-.75.75s.336.75.75.75h5.85c1.24 0 2.25 1.01 2.25 2.25v10.24l-2.22-2.22c-.293-.293-.768-.293-1.06 0s-.294.768 0 1.06l3.5 3.5c.145.147.337.22.53.22s.383-.072.53-.22l3.5-3.5c.294-.292.294-.767 0-1.06zm-10.66 3.28H7.26c-1.24 0-2.25-1.01-2.25-2.25V6.46l2.22 2.22c.148.147.34.22.532.22s.384-.073.53-.22c.293-.293.293-.768 0-1.06l-3.5-3.5c-.293-.294-.768-.294-1.06 0l-3.5 3.5c-.294.292-.294.767 0 1.06s.767.293 1.06 0l2.22-2.22V16.7c0 2.068 1.683 3.75 3.75 3.75h5.85c.414 0 .75-.336.75-.75s-.337-.75-.75-.75z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M12 21.638h-.014C9.403 21.59 1.95 14.856 1.95 8.478c0-3.064 2.525-5.754 5.403-5.754 2.29 0 3.83 1.58 4.646 2.73.814-1.148 2.354-2.73 4.645-2.73 2.88 0 5.404 2.69 5.404 5.755 0 6.376-7.454 13.11-10.037 13.157H12zM7.354 4.225c-2.08 0-3.903 1.988-3.903 4.255 0 5.74 7.034 11.596 8.55 11.658 1.518-.062 8.55-5.917 8.55-11.658 0-2.267-1.823-4.255-3.903-4.255-2.528 0-3.94 2.936-3.952 2.965-.23.562-1.156.562-1.387 0-.014-.03-1.425-2.965-3.954-2.965z"></path>
                                              </g>
                                           </svg>

                                           <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi">
                                              <g>
                                                 <path d="M17.53 7.47l-5-5c-.293-.293-.768-.293-1.06 0l-5 5c-.294.293-.294.768 0 1.06s.767.294 1.06 0l3.72-3.72V15c0 .414.336.75.75.75s.75-.336.75-.75V4.81l3.72 3.72c.146.147.338.22.53.22s.384-.072.53-.22c.293-.293.293-.767 0-1.06z"></path>
                                                 <path d="M19.708 21.944H4.292C3.028 21.944 2 20.916 2 19.652V14c0-.414.336-.75.75-.75s.75.336.75.75v5.652c0 .437.355.792.792.792h15.416c.437 0 .792-.355.792-.792V14c0-.414.336-.75.75-.75s.75.336.75.75v5.652c0 1.264-1.028 2.292-2.292 2.292z"></path>
                                              </g>
                                           </svg>

                            **
**

My code to try to find it:

try:
    tweets = wait.until(EC.presence_of_all_elements_located(
        (By.CSS_SELECTOR, "article[data-testid='tweet']a[href]")))
    links = [link.get_attribute('href')
             for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")

Error:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=98.0.4758.82)
Stacktrace:
Backtrace:
    Ordinal0 [0x00977AC3+2587331]
    Ordinal0 [0x0090ADD1+2141649]
    Ordinal0 [0x00803BB8+1063864]
    Ordinal0 [0x008063D7+1074135]
    Ordinal0 [0x0080629E+1073822]
    Ordinal0 [0x00806510+1074448]
    Ordinal0 [0x0082FF42+1244994]
    Ordinal0 [0x008303CB+1246155]
    Ordinal0 [0x0085A64C+1418828]
    Ordinal0 [0x008486D4+1345236]
    Ordinal0 [0x00858A0A+1411594]
    Ordinal0 [0x008484A6+1344678]
    Ordinal0 [0x008253F6+1201142]
    Ordinal0 [0x008262E6+1204966]
    GetHandleVerifier [0x00B1DF22+1680738]
    GetHandleVerifier [0x00BD0DBC+2413564]
    GetHandleVerifier [0x00A0D151+563089]
    GetHandleVerifier [0x00A0BF13+558419]
    Ordinal0 [0x0091081E+2164766]
    Ordinal0 [0x00915508+2184456]
    Ordinal0 [0x00915650+2184784]
    Ordinal0 [0x0091F5BC+2225596]
    BaseThreadInitThunk [0x753FFA29+25]
    RtlGetAppContainerNamedObjectPath [0x76FE7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x76FE7A6E+238]

What seems to be wrong?

Body:
This error message...

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified

...implies that the locator strategy you have used is not a valid locator strategy.

You nneed to insert a space between article[data-testid='tweet'] and a[href] to make it a valid locator strategy. So effectively your line of code would have been:

try:
    tweets = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "article[data-testid='tweet'] a[href]")))
    links = [link.get_attribute('href')
         for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")

However, to extract the value of the href attribute i.e. /kkanagas/status/1491996075573587994 you can use the following locator strategy:

try:
    tweets = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "article[data-testid='tweet'] a[href*='status']")))
    links = [link.get_attribute('href')
     for link in tweets]
    print(links)
except TimeoutException:
    print("Couldn't detect any tweets")


问:
How to check typescript type before commit?
I want to check typescript type before commit, So i use tsc --noEmit $(changedFile). However, This command can not specify config file.

I found --project option, But this option will check entire project and i just want to check changedFile, Because some old files has type error but do not need to handle.

So how can i only check changedFile type before commit ?

答:
I had the same problem and this package helped me for checking types in the lint-staged:

```<code>"**/*.ts?(x)": [
  "tsc-files --noEmit"
]
</code>```

you can install tsc-files package with npm i tsc-files

Body:
I had the same problem and this package helped me for checking types in the lint-staged:

"**/*.ts?(x)": [
  "tsc-files --noEmit"
]

you can install tsc-files package with npm i tsc-files


问:
Passing multiple parameters as one to a function
I have the following two functions

```<code>def single(x, param_a, param_b):
    return param_a + param_b*x

def multi(x, parameters):
    param_a_multi, param_b_multi = parameters[0], parameters[1]
    multi_result = 0
    for i in range(len(param_a_multi)):
        multi_result += single(x, param_a_multi[i], param_b_multi[i])
    return multi_result
</code>```

I know that the original data is built using 2*5 parameters. My guesses are:

```<code>guesses_a = numpy.linspace(1,5,5)
guesses_b = [1]*5
</code>```

I am trying to pass them in this form

```<code>guesses = [guesses_a, guesses_b]
</code>```

to curve_fit (using made up data in this example):

```<code>from scipy import optimize
optimize.curve_fit(f = multi, xdata = numpy.linspace(0,1,100), ydata = numpy.linspace(0,1,100), p0 = guesses)
</code>```

However, I get

```<code>TypeError: multi() takes 2 positional arguments but 11 were given
</code>```

How do I pass guesses as 1 argument and not as 10?

答:
From the curve_fit docs:

```<code>Parameters
f
callable
    The model function, f(x, …). It must take the independent variable as the first argument
    and the parameters to fit as separate remaining arguments.

p0
array_like, optional
    Initial guess for the parameters (length N).....
</code>```

Note it says length N.  I can double check the code, but if given 2d array, or list of arrays, it will flatten it.

```<code>In [16]: guesses_a = numpy.linspace(1,5,5)
    ...: guesses_b = [1]*5
    ...: guesses = [guesses_a, guesses_b]
    ...:
In [17]: guesses
Out[17]: [array([1., 2., 3., 4., 5.]), [1, 1, 1, 1, 1]]
In [18]: np.array(guesses).ravel()
Out[18]: array([1., 2., 3., 4., 5., 1., 1., 1., 1., 1.])
</code>```

That's 10 parameters, plus x that makes the 11 in the error message.

Don't forget that curve_fit has to vary those guesses to make the fit.  Therefore your function has to accept the parameters as it generates them.

If you define

```<code>def multi(x, *parameters):

</code>```

parameters will still be a flat array of 10 values; not two, or 2d array.

curve_fit does

```<code>   p0 = np.atleast_1d(p0)
    n = p0.size
</code>```

and passes the task to:

```<code>res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
</code>```

where that p0 gets:

```<code>x0 = asarray(x0).flatten()
n = len(x0)
</code>```

Body:
I have the following two functions

def single(x, param_a, param_b):
    return param_a + param_b*x

def multi(x, parameters):
    param_a_multi, param_b_multi = parameters[0], parameters[1]
    multi_result = 0
    for i in range(len(param_a_multi)):
        multi_result += single(x, param_a_multi[i], param_b_multi[i])
    return multi_result

I know that the original data is built using 2*5 parameters. My guesses are:

guesses_a = numpy.linspace(1,5,5)
guesses_b = [1]*5

I am trying to pass them in this form

guesses = [guesses_a, guesses_b]

to curve_fit (using made up data in this example):

from scipy import optimize
optimize.curve_fit(f = multi, xdata = numpy.linspace(0,1,100), ydata = numpy.linspace(0,1,100), p0 = guesses)

However, I get

TypeError: multi() takes 2 positional arguments but 11 were given

How do I pass guesses as 1 argument and not as 10?

Body:
From the curve_fit docs:

Parameters
f
callable
    The model function, f(x, …). It must take the independent variable as the first argument
    and the parameters to fit as separate remaining arguments.

p0
array_like, optional
    Initial guess for the parameters (length N).....

Note it says length N.  I can double check the code, but if given 2d array, or list of arrays, it will flatten it.

In [16]: guesses_a = numpy.linspace(1,5,5)
    ...: guesses_b = [1]*5
    ...: guesses = [guesses_a, guesses_b]
    ...:
In [17]: guesses
Out[17]: [array([1., 2., 3., 4., 5.]), [1, 1, 1, 1, 1]]
In [18]: np.array(guesses).ravel()
Out[18]: array([1., 2., 3., 4., 5., 1., 1., 1., 1., 1.])

That's 10 parameters, plus x that makes the 11 in the error message.

Don't forget that curve_fit has to vary those guesses to make the fit.  Therefore your function has to accept the parameters as it generates them.

If you define

def multi(x, *parameters):

parameters will still be a flat array of 10 values; not two, or 2d array.

curve_fit does

   p0 = np.atleast_1d(p0)
    n = p0.size

and passes the task to:

res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)

where that p0 gets:

x0 = asarray(x0).flatten()
n = len(x0)


问:
Changing value based on another value in pandas
I have two DataFrames

df1:

```<code>col1_a col2_a
MAR1 R1
MAR2 R2
MAR3 R3
</code>```

df2:

```<code>col1_b col2_b
MAR1 R1
MAR2 R20
MAR3
MAR4 R4
MAR5 R5
</code>```

and I want

```<code>col1_b col2_b
MAR1 R1
MAR2 R2
MAR3 R3
MAR4 R4
MAR5 R5
</code>```

So in the case col1_a == col1_b, I want to replace col2_b with col2_a

Unfortunately, I do not have a solution that works. Can anyone help?

答:
Assuming

```<code>df1 = pd.DataFrame({'col1_a':['MAR1','MAR2','MAR3'], 'col2_a':['R1', 'R2', 'R3']})

df2 = pd.DataFrame({'col1_b':['MAR1','MAR2','MAR3', 'MAR4', 'MAR5'], 'col2_b':['R1', 'R20', None, 'R4', 'R5']})
</code>```

Then you can achieve this with:

```<code>df3 = df2.merge(df1, how='left', left_on='col1_b', right_on='col1_a')
selection_condition = pd.isna(df3["col2_a"])
df3["col2_a"].iloc[selection_condition] = df3[selection_condition]["col2_b"]
</code>```

And

```<code>df3[["col1_b", "col2_a"]]
</code>```

will have your desired columns.

Body:
I have two DataFrames

df1:

col1_a col2_a
MAR1 R1
MAR2 R2
MAR3 R3

df2:

col1_b col2_b
MAR1 R1
MAR2 R20
MAR3
MAR4 R4
MAR5 R5

and I want

col1_b col2_b
MAR1 R1
MAR2 R2
MAR3 R3
MAR4 R4
MAR5 R5

So in the case col1_a == col1_b, I want to replace col2_b with col2_a

Unfortunately, I do not have a solution that works. Can anyone help?

Body:
Assuming

df1 = pd.DataFrame({'col1_a':['MAR1','MAR2','MAR3'], 'col2_a':['R1', 'R2', 'R3']})

df2 = pd.DataFrame({'col1_b':['MAR1','MAR2','MAR3', 'MAR4', 'MAR5'], 'col2_b':['R1', 'R20', None, 'R4', 'R5']})

Then you can achieve this with:

df3 = df2.merge(df1, how='left', left_on='col1_b', right_on='col1_a')
selection_condition = pd.isna(df3["col2_a"])
df3["col2_a"].iloc[selection_condition] = df3[selection_condition]["col2_b"]

And

df3[["col1_b", "col2_a"]]

will have your desired columns.


问:
Compose creating new ViewModel instance
I work in a project that's slowly adopting Jetpack Compose. It's mostly a single Activity multiple Fragments app where we use the Android's navigation component to handle transitions to each screen (Fragment). Whenever we can, we are only replacing the Fragments' XML layout with Composables.

The cases up until now were handling like the following:

A. Fragments show composables and handle navigation:

```<code>class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                AppTheme {
                    Screen(onBackPressed = { findNavController().navigateUp() })
                }
            }
        }
    }
    ...

}
</code>```

B. Composable that handles everything else UI related:

```<code>@Composable
fun CreatePassword(
    onBackPressed: () -> Unit,
) {

    // For observing UI states and events
    val viewModel: CreatePasswordViewModel = viewModel()
    ...
}

</code>```

As you can see, we have a reference for the screen's ViewModel in both our Fragments and our Composables. Up until now, this has been working fine, the composable viewModel() function was always returning the same existing instance of the Fragment's ViewModel.

The problems came when we needed the reference of a ViewModel scoped to an Activity on the composable:

We create the ViewModel on the Activity:

```<code>class MainActivity : AppCompatActivity() {

    private val viewModel by lazyViewModel { MainViewModel() }
    ...
}
</code>```

Get a reference for the MainActivity's ViewModel on the Fragment like

```<code>class MainFragment : Fragment() {

    private val viewModel: MainViewModel by viewModels(::requireActivity)
    ...
}
</code>```

We get the reference of the ViewModel for composables as shown above (item B)

By doing so the Fragment has the same instance of the Activity's but the composable doesn't.

My questions is,
would it be possible to get the reference of the Activity's ViewModel inside the composable? For now I'm simply passing down the Fragment's ViewModel as a parameter to my main composable screen.

答:
I managed to pass down the Activity's ViewModel by providing a ViewModelStoreOwner to my composable as following:

```<code>class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                val viewModelStoreOwner =
                    compositionLocalOf<ViewModelStoreOwner> { requireActivity() }

                AppTheme {
                    CompositionLocalProvider(
                        LocalViewModelStoreOwner provides viewModelStoreOwner.current
                    ) {
                        Screen(onBackPressed = { findNavController().navigateUp() })
                    }
                }
            }
        }
    }
    ...

}
</code>```

Title: Compose creating new ViewModel instance

Body:
I work in a project that's slowly adopting Jetpack Compose. It's mostly a single Activity multiple Fragments app where we use the Android's navigation component to handle transitions to each screen (Fragment). Whenever we can, we are only replacing the Fragments' XML layout with Composables.

The cases up until now were handling like the following:

A. Fragments show composables and handle navigation:

class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                AppTheme {
                    Screen(onBackPressed = { findNavController().navigateUp() })
                }
            }
        }
    }
    ...

}

B. Composable that handles everything else UI related:

@Composable
fun CreatePassword(
    onBackPressed: () -> Unit,
) {

    // For observing UI states and events
    val viewModel: CreatePasswordViewModel = viewModel()
    ...
}

As you can see, we have a reference for the screen's ViewModel in both our Fragments and our Composables. Up until now, this has been working fine, the composable viewModel() function was always returning the same existing instance of the Fragment's ViewModel.

The problems came when we needed the reference of a ViewModel scoped to an Activity on the composable:

We create the ViewModel on the Activity:

class MainActivity : AppCompatActivity() {

    private val viewModel by lazyViewModel { MainViewModel() }
    ...
}

Get a reference for the MainActivity's ViewModel on the Fragment like

class MainFragment : Fragment() {

    private val viewModel: MainViewModel by viewModels(::requireActivity)
    ...
}

We get the reference of the ViewModel for composables as shown above (item B)

By doing so the Fragment has the same instance of the Activity's but the composable doesn't.

My questions is,
would it be possible to get the reference of the Activity's ViewModel inside the composable? For now I'm simply passing down the Fragment's ViewModel as a parameter to my main composable screen.

Body:
I managed to pass down the Activity's ViewModel by providing a ViewModelStoreOwner to my composable as following:

class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                val viewModelStoreOwner =
                    compositionLocalOf<ViewModelStoreOwner> { requireActivity() }

                AppTheme {
                    CompositionLocalProvider(
                        LocalViewModelStoreOwner provides viewModelStoreOwner.current
                    ) {
                        Screen(onBackPressed = { findNavController().navigateUp() })
                    }
                }
            }
        }
    }
    ...

}


问:
Append an input's value in included form..PHP
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

```<code><?php include("includes/lp_form.php");?>
</code>```

In the included form:

```<code><input type="hidden" name="referred_by_text" value="" />
</code>```

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

答:
You can use PHP to echo out the value you want. You could try something like:

```<code><input type="hidden" name="referred_by_text" value="<?php echo $_SERVER['HTTP_REFERER'] ?>" />
</code>```

That will appear blank if there was no referer.

Body:
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

<?php include("includes/lp_form.php");?>

In the included form:

<input type="hidden" name="referred_by_text" value="" />

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

Body:
You can use PHP to echo out the value you want. You could try something like:

<input type="hidden" name="referred_by_text" value="<?php echo $_SERVER['HTTP_REFERER'] ?>" />

That will appear blank if there was no referer.


问:
How to resolve Error in tagAssert error for Shiny?
I am getting the error below when I try to run my Shiny Dashboard script, but I've no idea what's causing it. Does anyone have any suggestions?

Error: Error in tagAssert(body, type = "div", class = "content-wrapper") :
Expected an object with class 'shiny.tag'.

I am not receiving any errors when I run the UI or Server components, its only when I run the shinyApp function in the final step.

Here is an subset of the data I am using:

```<code>structure(list(FACTOR_NAME = c("ABI", "ABI",
"ABI", "ABI", "ABI_VEH",
"ABI_VEH", "ABI_VEH", "ABI_VEH",
"ABI_VEH", "ABI_VEH"), LEVEL_NAME = c("AEB1",
"AEB2", "AEB3", "N", "1", "10", "11", "12", "13", "14"), EXPOSURE = c(381785,
616864, 690655, 3447237, 27, 2410, 5779, 8451, 10850, 16383),
    EXPOSURE_PERC = c(0.03, 0.05, 0.06, 0.28, 0, 0, 0, 0, 0,
    0), ACT = c(269.12, 373.94, 302.69, 248.71, 6.87, 239.6,
    162.02, 210.18, 228.18, 187.76), PRED = c(258.55, 345.05,
    300.93, 255.41, 203.7, 211.58, 199.49, 253.01, 227.99, 239.33
    )), row.names = c(NA, 10L), class = "data.frame")
</code>```

Here is my current script

```<code>library(shiny)
library(shinydashboard)
library(plotly)

# UI

sidebar <-    dashboardSidebar(width = 350,
                               sidebarMenu(id = "sidebarname",
                                           menuItem("HOME", tabName = "home", icon = icon("home")),
                                           convertMenuItem(menuItem("DASHBOARD", tabName = "dashboard", "dashboard",

                                                                    box(width = NULL,
                                                                        uiOutput("factor_select")
                                                                    )
                                           ),
                                           tabName = "dashboard"))
                               )

# Body: !! Change the comments here !!
body <- dashboardBody(

  #useShinyjs(),

  tabItems(
    tabItem("dashboard",

            tags$style(type="text/css",
                       ".shiny-output-error { visibility: hidden; }",
                       ".shiny-output-error:before { visibility: hidden; }"),

            tabsetPanel(id="dashboard_tabs", type="tabs",
                        tabPanel("Overall AvP", value = "overall",
                                 br(),
                                 plotlyOutput("sample_graph"),
                                 br(),
                                 DT::dataTableOutput("output_table")
                        )
            )
    )
  )
)

##################################################################################################################
# Server
##################################################################################################################

server <- function(input, output, session) {

  # Display factor dropdown - different depending on input dataset
  output$factor_select <- renderUI({
    message("render selected_factor   \n")
    query_str = paste0("select distinct factor_name from ", oracle_dataset, " order by factor_name")
    cat(query_str)
    factor_list <- as.list(dbGetQuery(con, query_str))
    selectInput("selected_factor", "Factor:", factor_list[["FACTOR_NAME"]])
  })

  select_data <- function(){
    query_str <- paste0(
      "select factor_name, level_name, exposure_perc, act, pred ",
      " from ",
      oracle_dataset,
      " where factor_name = '",
      input$selected_factor,
      "'",
      "order by level_name")

    cat(query_str)

    select_data <- dbGetQuery(con, query_str)
  }

  # This outputs the summary graph (groups all months together)
  output$sample_graph <- renderPlotly({

    data_to_plot <- select_data()

    plot_ly(data_to_plot, x=~LEVEL_NAME) %>%
    add_lines(.,y = data_to_plot$ACT, name = "Actual")  %>%
    add_lines(.,y = data_to_plot$PRED, name = "Pred Cal") %>%
      add_bars(type = "mesh2d", y = data_to_plot$EXPOSURE_PERC, name = "exposure", yaxis = "y2", opacity = 0.5) %>%
      layout(
        title = "Overall",
        yaxis = list(title = "Total burning cost", side = "left", rangemode = "tozero"),
        yaxis2 = list(title = "exposure", side = "right", overlaying = "y")
      )

  })

}

shinyApp(
  dashboardPage(header, sidebar, body),
  server = server
)
</code>```

答:
As stated by @bretauv, you need header to be defined with a title.  You could define

```<code>header <- dashboardHeader(title="Test App")
</code>```

Also, your convertMenuItem is not defined.  How are you getting it?

Body:
I am getting the error below when I try to run my Shiny Dashboard script, but I've no idea what's causing it. Does anyone have any suggestions?

Error: Error in tagAssert(body, type = "div", class = "content-wrapper") :
Expected an object with class 'shiny.tag'.

I am not receiving any errors when I run the UI or Server components, its only when I run the shinyApp function in the final step.

Here is an subset of the data I am using:

structure(list(FACTOR_NAME = c("ABI", "ABI",
"ABI", "ABI", "ABI_VEH",
"ABI_VEH", "ABI_VEH", "ABI_VEH",
"ABI_VEH", "ABI_VEH"), LEVEL_NAME = c("AEB1",
"AEB2", "AEB3", "N", "1", "10", "11", "12", "13", "14"), EXPOSURE = c(381785,
616864, 690655, 3447237, 27, 2410, 5779, 8451, 10850, 16383),
    EXPOSURE_PERC = c(0.03, 0.05, 0.06, 0.28, 0, 0, 0, 0, 0,
    0), ACT = c(269.12, 373.94, 302.69, 248.71, 6.87, 239.6,
    162.02, 210.18, 228.18, 187.76), PRED = c(258.55, 345.05,
    300.93, 255.41, 203.7, 211.58, 199.49, 253.01, 227.99, 239.33
    )), row.names = c(NA, 10L), class = "data.frame")

Here is my current script

library(shiny)
library(shinydashboard)
library(plotly)

# UI

sidebar <-    dashboardSidebar(width = 350,
                               sidebarMenu(id = "sidebarname",
                                           menuItem("HOME", tabName = "home", icon = icon("home")),
                                           convertMenuItem(menuItem("DASHBOARD", tabName = "dashboard", "dashboard",

                                                                    box(width = NULL,
                                                                        uiOutput("factor_select")
                                                                    )
                                           ),
                                           tabName = "dashboard"))
                               )

# Body: !! Change the comments here !!
body <- dashboardBody(

  #useShinyjs(),

  tabItems(
    tabItem("dashboard",

            tags$style(type="text/css",
                       ".shiny-output-error { visibility: hidden; }",
                       ".shiny-output-error:before { visibility: hidden; }"),

            tabsetPanel(id="dashboard_tabs", type="tabs",
                        tabPanel("Overall AvP", value = "overall",
                                 br(),
                                 plotlyOutput("sample_graph"),
                                 br(),
                                 DT::dataTableOutput("output_table")
                        )
            )
    )
  )
)

##################################################################################################################
# Server
##################################################################################################################

server <- function(input, output, session) {

  # Display factor dropdown - different depending on input dataset
  output$factor_select <- renderUI({
    message("render selected_factor   \n")
    query_str = paste0("select distinct factor_name from ", oracle_dataset, " order by factor_name")
    cat(query_str)
    factor_list <- as.list(dbGetQuery(con, query_str))
    selectInput("selected_factor", "Factor:", factor_list[["FACTOR_NAME"]])
  })

  select_data <- function(){
    query_str <- paste0(
      "select factor_name, level_name, exposure_perc, act, pred ",
      " from ",
      oracle_dataset,
      " where factor_name = '",
      input$selected_factor,
      "'",
      "order by level_name")

    cat(query_str)

    select_data <- dbGetQuery(con, query_str)
  }

  # This outputs the summary graph (groups all months together)
  output$sample_graph <- renderPlotly({

    data_to_plot <- select_data()

    plot_ly(data_to_plot, x=~LEVEL_NAME) %>%
    add_lines(.,y = data_to_plot$ACT, name = "Actual")  %>%
    add_lines(.,y = data_to_plot$PRED, name = "Pred Cal") %>%
      add_bars(type = "mesh2d", y = data_to_plot$EXPOSURE_PERC, name = "exposure", yaxis = "y2", opacity = 0.5) %>%
      layout(
        title = "Overall",
        yaxis = list(title = "Total burning cost", side = "left", rangemode = "tozero"),
        yaxis2 = list(title = "exposure", side = "right", overlaying = "y")
      )

  })

}

shinyApp(
  dashboardPage(header, sidebar, body),
  server = server
)

Body:
As stated by @bretauv, you need header to be defined with a title.  You could define

header <- dashboardHeader(title="Test App")

Also, your convertMenuItem is not defined.  How are you getting it?


问:
formGroup property of FormGroupDirective is not working if bind in normal way
I know how Reactive Forms works in Angular.
We first need to create a FormGroup Object in our TS File and then sync it with our HTML code with help of FormGroupDirective.

Below is the working code :

Sample Typescript Code and HTML Code:

```<code>export class CarComponent {
  // property that holds object
  myForm:FormGroup = new FormGroup({
    first: new FormControl('Nancy')
  });

  logOurForm(){
    console.log(this.myForm);
  }
}
<form [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type = "text" [formControlName]="'first'">
    <button type = "submit">Submit Data</button>
</form>
</code>```

Now if we click the button, the form will be logged in to console of browser as expected.

PROBLEM

The problem occurs, if we use normal syntax to bind to formGroup property of FormGroupDirective.
If we use below code, we get error.

```<code><form formGroup [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type = "text" [formControlName]="'first'">
    <button type = "submit">Submit Data</button>
</form>
</code>```

ERROR: Type string is not assignable to type FormGroup.

Que 1 : Why do we get this error?

Que 2 : Why does it work with <form [formGroup]="myForm"> but not with <form formGroup [formGroup]="myForm">?

Que 3: Why do we see this weird behavior with this directive only? If we try to do same with any other directive, it works perfectly.

答:
Your error is with the '' in formControlName and the []. Try this.</p>
```<code><form formGroup [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type="text" formControlName="first">
    <button type="submit">Submit Data</button>
</form>
</code>```

Body:
I know how Reactive Forms works in Angular.
We first need to create a FormGroup Object in our TS File and then sync it with our HTML code with help of FormGroupDirective.

Below is the working code :

Sample Typescript Code and HTML Code:

export class CarComponent {
  // property that holds object
  myForm:FormGroup = new FormGroup({
    first: new FormControl('Nancy')
  });

  logOurForm(){
    console.log(this.myForm);
  }
}
<form [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type = "text" [formControlName]="'first'">
    <button type = "submit">Submit Data</button>
</form>

Now if we click the button, the form will be logged in to console of browser as expected.

PROBLEM

The problem occurs, if we use normal syntax to bind to formGroup property of FormGroupDirective.
If we use below code, we get error.

<form formGroup [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type = "text" [formControlName]="'first'">
    <button type = "submit">Submit Data</button>
</form>

ERROR: Type string is not assignable to type FormGroup.

Que 1 : Why do we get this error?

Que 2 : Why does it work with <form [formGroup]="myForm"> but not with <form formGroup [formGroup]="myForm">?

Que 3: Why do we see this weird behavior with this directive only? If we try to do same with any other directive, it works perfectly.

Body:
Your error is with the '' in formControlName and the []. Try this.

<form formGroup [formGroup]="myForm" (ngSubmit)="logOurForm()">
    <input type="text" formControlName="first">
    <button type="submit">Submit Data</button>
</form>


问:
IN clause with jooq and kotlin
I have the following code which works fine:

```<code>fun <T> createComparisonOperator(field: Field<T>, value: T, op: String): Condition {
    return when(op) {
        "eq" -> field.eq(DSL.inline(value))
        else -> throw Exception("No Op)
      }
}
</code>```

Now what I want to do is test for membership in an array and I do something like:

```<code>fun<T> createMembershipOperator(field: Field<T>, value: Collection<T>, op: String): Condition {
      return when(op) {
        "in" -> field.`in`(DSL.inline(value))
        else -> throw Exception("No op")
      }
    }
</code>```

The membership test is called as:

```<code>val wrappedValue = listOf("100")
val sqlField = DSL.field(column, SQLDataType.VARCHAR)
return createMembershipOperator<String>(sqlField, wrappedValue, op)
</code>```

It does not fail but does not return any data.

答:
Write this:

"in" -> field.`in`(value.map(DSL::inline))
```

Title: IN clause with jooq and kotlin

Body:
I have the following code which works fine:

fun <T> createComparisonOperator(field: Field<T>, value: T, op: String): Condition {
    return when(op) {
        "eq" -> field.eq(DSL.inline(value))
        else -> throw Exception("No Op)
      }
}

Now what I want to do is test for membership in an array and I do something like:

fun<T> createMembershipOperator(field: Field<T>, value: Collection<T>, op: String): Condition {
      return when(op) {
        "in" -> field.`in`(DSL.inline(value))
        else -> throw Exception("No op")
      }
    }

The membership test is called as:

val wrappedValue = listOf("100")
val sqlField = DSL.field(column, SQLDataType.VARCHAR)
return createMembershipOperator<String>(sqlField, wrappedValue, op)

It does not fail but does not return any data.


问:
How to solve flask sqlalchemy connection time out error (queue pool overflow limit)?
I have made one POST API named as "/get_report" which takes some input from user and return data according to inputs by doing some search queries on database. If I keep hitting the same API multiple times like for 7-8 times, on 9th hit it throws error "sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00 (Background on this error at: https://sqlalche.me/e/14/3o7r)".

Here is my main.py:

```<code>from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
from helper import *
from models.tx import *

app = Flask(__name__)

db = SQLAlchemy()

DB_URL = 'postgresql://postgres:postgres@localhost/test_db'

engine = create_engine(DB_URL)
Session = sessionmaker(engine)

app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

@contextmanager
def session_manager():
    s = Session()
    try:
        yield s
    except:
        s.rollback()
        raise
    finally:
        s.close()

@app.route('/get_report', methods=['POST'])
def get_report():
    try:
        vendor = request.form['vendor']
        circle = request.form['circle']
        c_name = request.form['c_name']
        c_port = request.form['c_port']
        all_ssr = request.form['all_ssr']
        data_list = []
        table_name = get_table_by_vendor(vendor, circle)
        if table_name != None:
            with session_manager() as s:
                if all_ssr == 'SSR':
                    result = s.query(table_name).distinct(table_name.label, table_name.c_node, \
                             table_name.c_port, table_name.z_port, table_name.z_node) \
                            .filter(and_((or_( and_(table_name.c_node == c_name, table_name.c_port == c_port), \
                             and_(table_name.z_node == c_name, table_name.z_port == c_port ))), \
                            (table_name.__table__.c[field_name].like('SSR%')))).all()
                elif all_ssr == 'ALL':
                    # Get all the records
                    result = s.query(table_name).distinct(table_name.label, table_name.c_node, \
                            table_name.c_port, table_name.z_port, table_name.z_node) \
                            .filter(or_( and_(table_name.c_node ==c_name, table_name.c_port == c_port), \
                            and_(table_name.z_node == c_name, table_name.z_port == c_port ))).all()
                else:
                    result = []
                # Preparing JSON data to send
                for item in result:
                    port = c_port if c_port != '' else (item.c_port if item.c_node == c_name else item.z_port)
                    data_dict = {'user': item.user, 'port': item.port, 'rate':item.rate, 'down': item.down}
                    data_list.append(data_dict)
                response = {"status": "Success", "message": "Successfully Fetched", "data": data_list}
                return jsonify(response)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 5000,debug = True)
</code>```

Here is my models/tx.py:

```<code>class C_Segment(db.Model):
    __tablename__ = 'c_segment'

    id = db.Column(db.Integer, primary_key=True)
    c_node = db.Column(db.String(350), nullable=False)
    c_port = db.Column(db.String(200), nullable=False)
    label = db.Column(db.String(350), nullable=False)
    z_port = db.Column(db.String(200), nullable=False)
    z_node = db.Column(db.String(200), nullable=False)
    user = db.Column(db.String(200), nullable=False)
    down = db.Column(db.String(200), nullable=False)
    port = db.Column(db.String(200), nullable=False)
    rate = db.Column(db.String(200), nullable=FaI
        return '<id {}>'.format(self.id)
</code>```

I have searched a lot and found so many related content on google but none of them worked for me. I have tried to increase pool size and overflow size also but nothing happened.
I am not able to understand where is the exact issue. I have been stuck into this from last two days and has gone through many stack overflow contents and flask sqlalchemy session documents.

答:
You have a set of connections in the pool, e.g. 15 (5 in the pool and 10 from possible overflow). If a request processing is longer than connection checkout timeout (how long you will wait on available connection, default 30s) you will get this error (all 15 connections are busy and your request must wait for available connection - and waits but only for 30s, after that you get an error).
Have you thought about a query optimization? How many records do you have in the table? How long a request last? You can profile your SQL query using:

EXPLAIN ANALYZE <query>
```
<p>You can of course increase the pool timeout by setting e.g 300s (5min):</p>
```app.config['SQLALCHEMY_POOL_TIMEOUT'] = 300
```

or make the pool size bigger but it would not solve your problem genuinely. Such a long response time in a request is really bad UX and limit concurrent access to you application from clients.
So I recommend you to make your query faster.

Body:
I have made one POST API named as "/get_report" which takes some input from user and return data according to inputs by doing some search queries on database. If I keep hitting the same API multiple times like for 7-8 times, on 9th hit it throws error "sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00 (Background on this error at: https://sqlalche.me/e/14/3o7r)".

Here is my main.py:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
from helper import *
from models.tx import *

app = Flask(__name__)

db = SQLAlchemy()

DB_URL = 'postgresql://postgres:postgres@localhost/test_db'

engine = create_engine(DB_URL)
Session = sessionmaker(engine)

app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

@contextmanager
def session_manager():
    s = Session()
    try:
        yield s
    except:
        s.rollback()
        raise
    finally:
        s.close()

@app.route('/get_report', methods=['POST'])
def get_report():
    try:
        vendor = request.form['vendor']
        circle = request.form['circle']
        c_name = request.form['c_name']
        c_port = request.form['c_port']
        all_ssr = request.form['all_ssr']
        data_list = []
        table_name = get_table_by_vendor(vendor, circle)
        if table_name != None:
            with session_manager() as s:
                if all_ssr == 'SSR':
                    result = s.query(table_name).distinct(table_name.label, table_name.c_node, \
                             table_name.c_port, table_name.z_port, table_name.z_node) \
                            .filter(and_((or_( and_(table_name.c_node == c_name, table_name.c_port == c_port), \
                             and_(table_name.z_node == c_name, table_name.z_port == c_port ))), \
                            (table_name.__table__.c[field_name].like('SSR%')))).all()
                elif all_ssr == 'ALL':
                    # Get all the records
                    result = s.query(table_name).distinct(table_name.label, table_name.c_node, \
                            table_name.c_port, table_name.z_port, table_name.z_node) \
                            .filter(or_( and_(table_name.c_node ==c_name, table_name.c_port == c_port), \
                            and_(table_name.z_node == c_name, table_name.z_port == c_port ))).all()
                else:
                    result = []
                # Preparing JSON data to send
                for item in result:
                    port = c_port if c_port != '' else (item.c_port if item.c_node == c_name else item.z_port)
                    data_dict = {'user': item.user, 'port': item.port, 'rate':item.rate, 'down': item.down}
                    data_list.append(data_dict)
                response = {"status": "Success", "message": "Successfully Fetched", "data": data_list}
                return jsonify(response)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 5000,debug = True)

Here is my models/tx.py:

class C_Segment(db.Model):
    __tablename__ = 'c_segment'

    id = db.Column(db.Integer, primary_key=True)
    c_node = db.Column(db.String(350), nullable=False)
    c_port = db.Column(db.String(200), nullable=False)
    label = db.Column(db.String(350), nullable=False)
    z_port = db.Column(db.String(200), nullable=False)
    z_node = db.Column(db.String(200), nullable=False)
    user = db.Column(db.String(200), nullable=False)
    down = db.Column(db.String(200), nullable=False)
    port = db.Column(db.String(200), nullable=False)
    rate = db.Column(db.String(200), nullable=FaI
        return '<id {}>'.format(self.id)

I have searched a lot and found so many related content on google but none of them worked for me. I have tried to increase pool size and overflow size also but nothing happened.
I am not able to understand where is the exact issue. I have been stuck into this from last two days and has gone through many stack overflow contents and flask sqlalchemy session documents.

Body:
You have a set of connections in the pool, e.g. 15 (5 in the pool and 10 from possible overflow). If a request processing is longer than connection checkout timeout (how long you will wait on available connection, default 30s) you will get this error (all 15 connections are busy and your request must wait for available connection - and waits but only for 30s, after that you get an error).
Have you thought about a query optimization? How many records do you have in the table? How long a request last? You can profile your SQL query using:

EXPLAIN ANALYZE <query>

You can of course increase the pool timeout by setting e.g 300s (5min):

app.config['SQLALCHEMY_POOL_TIMEOUT'] = 300

or make the pool size bigger but it would not solve your problem genuinely. Such a long response time in a request is really bad UX and limit concurrent access to you application from clients.
So I recommend you to make your query faster.


问:
Set IAM role to run AWS CLI Python subprocess in AWS Lambda
I created a Lambda layer that contains the AWS CLI because the aws sync command is not available in boto3 and the copy function was too slow to complete the s3 to s3 transfer prior to hitting the maximum Lambda time out.

I can run AWS CLI commands (ls, sync, etc) as the execution role for the Lambda. I need to run aws sync from Lambda to sync two s3 buckets as a different IAM user that has access to the source and destination buckets.

How do I configure the CLI to run as a particular user?

The commands below configure the user successfully locally but when run using the subprocess function in Lambda, the output of get-caller-identity is still the ARN of the Lambda role.

```<code>/opt/aws configure set aws_access_key_id <id>
/opt/aws configure set aws_secret_access_key <key>
/opt/aws sts get-caller-identity
</code>```

In order to run the configure set id and key commands, I had to set an environmental variable to bypass the read only Lambda file system to write the credentials to the /temp directory.

Environmental Variable:

```<code>key: HOME
value: /tmp
</code>```

Note: There is a populated credentials file written to: /temp/.aws/credentials

Lambda:

```<code>import logging
import subprocess

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def run_command(command):
    command_list = command.split(' ')
    try:
        logger.info("Running shell command: \"{}\"".format(command))
        result = subprocess.run(command_list, stdout=subprocess.PIPE);
        logger.info("Command output:\n---\n{}\n---".format(result.stdout.decode('UTF-8')))
    except Exception as e:
        logger.error("Exception: {}".format(e))
        return False

    return True

def lambda_handler(event, context):
    run_command('/opt/aws configure set aws_access_key_id <id>')
    run_command('/opt/aws configure set aws_secret_access_key <key>')
    # not set to new IAM user
    run_command('/opt/aws sts get-caller-identity')
</code>```

Thanks for reading!

答:
Pass the IAM access credentials as environment variables to the subprocess, instead of trying to run aws configure:

```<code>result = subprocess.run(command_list, stdout=subprocess.PIPE, env={
  'AWS_ACCESS_KEY_ID': <id>,
  'AWS_SECRET_ACCESS_KEY': <id>,
});
</code>```

Explanation:

The Lambda runtime environment has the environment variables set for the role it is using, documented here, and those environment variables are taking precedence over anything you are trying to do via the aws configure command. So the easiest way to fix that is to just override the environment variables that are passed to the subprocess via the env argument.

I don't think your calls to aws configure are working anyway, since all that does is write to a ~/.aws/credentials file, and that file isn't writeable inside the AWS Lambda environment, only /tmp is writeable.

Body:
I created a Lambda layer that contains the AWS CLI because the aws sync command is not available in boto3 and the copy function was too slow to complete the s3 to s3 transfer prior to hitting the maximum Lambda time out.

I can run AWS CLI commands (ls, sync, etc) as the execution role for the Lambda. I need to run aws sync from Lambda to sync two s3 buckets as a different IAM user that has access to the source and destination buckets.

How do I configure the CLI to run as a particular user?

The commands below configure the user successfully locally but when run using the subprocess function in Lambda, the output of get-caller-identity is still the ARN of the Lambda role.

/opt/aws configure set aws_access_key_id <id>
/opt/aws configure set aws_secret_access_key <key>
/opt/aws sts get-caller-identity

In order to run the configure set id and key commands, I had to set an environmental variable to bypass the read only Lambda file system to write the credentials to the /temp directory.

Environmental Variable:

key: HOME
value: /tmp

Note: There is a populated credentials file written to: /temp/.aws/credentials

Lambda:

import logging
import subprocess

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def run_command(command):
    command_list = command.split(' ')
    try:
        logger.info("Running shell command: \"{}\"".format(command))
        result = subprocess.run(command_list, stdout=subprocess.PIPE);
        logger.info("Command output:\n---\n{}\n---".format(result.stdout.decode('UTF-8')))
    except Exception as e:
        logger.error("Exception: {}".format(e))
        return False

    return True

def lambda_handler(event, context):
    run_command('/opt/aws configure set aws_access_key_id <id>')
    run_command('/opt/aws configure set aws_secret_access_key <key>')
    # not set to new IAM user
    run_command('/opt/aws sts get-caller-identity')

Thanks for reading!

Body:
Pass the IAM access credentials as environment variables to the subprocess, instead of trying to run aws configure:

result = subprocess.run(command_list, stdout=subprocess.PIPE, env={
  'AWS_ACCESS_KEY_ID': <id>,
  'AWS_SECRET_ACCESS_KEY': <id>,
});

Explanation:

The Lambda runtime environment has the environment variables set for the role it is using, documented here, and those environment variables are taking precedence over anything you are trying to do via the aws configure command. So the easiest way to fix that is to just override the environment variables that are passed to the subprocess via the env argument.

I don't think your calls to aws configure are working anyway, since all that does is write to a ~/.aws/credentials file, and that file isn't writeable inside the AWS Lambda environment, only /tmp is writeable.