问:
boxes and loop for finding big shadows
Help me with the script.
This script finds long shadows on the chart and draws boxes there. As soon as the high overlaps the middle line of the box, it disappears, when I make such a condition "if high >= (top + bottom) / 2", then nothing is displayed for me. But if I do "if close >= (top + bottom) / 2" , then everything works, how can I fix the script so that the boxes are displayed on the chart and disappear as soon as the high overlaps the middle line?</p>
```<code>//@version=5
indicator("My script", overlay = true)

imb_percent = input.float(1)

var box[] imbalancedDownBoxes = array.new_box()
var box[] imbalancedUpBoxes = array.new_box()
var line[] imbalancedDownMidLines = array.new_line()
var line[] imbalancedUpMidLines = array.new_line()

extension = extend.right

if close + ((close / 100) * imb_percent) <= high and close > open
    array.push(imbalancedUpBoxes, box.new(left=bar_index, top=high, right=bar_index + 40, bottom=close, bgcolor=color.new(color.green, 50), border_color=color.yellow, extend=extension,
 text = str.tostring(high) + '\n' + str.tostring((high + close) / 2) + '\n' + str.tostring(close), text_color = color.white
 ))

midPoint = (high + close) / 2
array.push(imbalancedUpMidLines, line.new(bar_index - 2, midPoint, bar_index + 20, midPoint, style=line.style_solid, extend=extension, color=color.yellow))

if array.size(imbalancedUpBoxes) > 0
    for i = array.size(imbalancedUpBoxes) - 1 to 0 by 1
        imbalancedBox = array.get(imbalancedUpBoxes, i)
        top = box.get_top(imbalancedBox)
        bottom = box.get_bottom(imbalancedBox)
        box.set_right(imbalancedBox, bar_index + 40)

        midLine = array.get(imbalancedUpMidLines, i)
        line.set_x2(midLine, bar_index + 40)

        if high >= (top + bottom) / 2
            box.delete(imbalancedBox)
            array.remove(imbalancedUpBoxes, i)
            line.delete(midLine)
            array.remove(imbalancedUpMidLines, i)
</code>```

Title: boxes and loop for finding big shadows

Body:
Help me with the script.
This script finds long shadows on the chart and draws boxes there. As soon as the high overlaps the middle line of the box, it disappears, when I make such a condition "if high >= (top + bottom) / 2", then nothing is displayed for me. But if I do "if close >= (top + bottom) / 2" , then everything works, how can I fix the script so that the boxes are displayed on the chart and disappear as soon as the high overlaps the middle line?

//@version=5
indicator("My script", overlay = true)

imb_percent = input.float(1)

var box[] imbalancedDownBoxes = array.new_box()
var box[] imbalancedUpBoxes = array.new_box()
var line[] imbalancedDownMidLines = array.new_line()
var line[] imbalancedUpMidLines = array.new_line()

extension = extend.right

if close + ((close / 100) * imb_percent) <= high and close > open
    array.push(imbalancedUpBoxes, box.new(left=bar_index, top=high, right=bar_index + 40, bottom=close, bgcolor=color.new(color.green, 50), border_color=color.yellow, extend=extension,
 text = str.tostring(high) + '\n' + str.tostring((high + close) / 2) + '\n' + str.tostring(close), text_color = color.white
 ))

midPoint = (high + close) / 2
array.push(imbalancedUpMidLines, line.new(bar_index - 2, midPoint, bar_index + 20, midPoint, style=line.style_solid, extend=extension, color=color.yellow))

if array.size(imbalancedUpBoxes) > 0
    for i = array.size(imbalancedUpBoxes) - 1 to 0 by 1
        imbalancedBox = array.get(imbalancedUpBoxes, i)
        top = box.get_top(imbalancedBox)
        bottom = box.get_bottom(imbalancedBox)
        box.set_right(imbalancedBox, bar_index + 40)

        midLine = array.get(imbalancedUpMidLines, i)
        line.set_x2(midLine, bar_index + 40)

        if high >= (top + bottom) / 2
            box.delete(imbalancedBox)
            array.remove(imbalancedUpBoxes, i)
            line.delete(midLine)
            array.remove(imbalancedUpMidLines, i)


来源: stackexchange

问:
search by one by one character in Live search Html
when i search ( product ) Found all product , but when i type ( product sample one ) that show all product have same text like ( product --or-- sample --or --one )

Like that -> (searching : Product red ribbon )

that show other texts same
-product ribbon
-product red
-red ribbon

i want show only same search query ( product red ribbon ) and hide others

my code

 <input type="text" class="live-search-box" placeholder="search here">
 ```

ContentLicense: CC BY-SA 4.0


问:
Query average call length for calls in task router queues
Is there an API call that returns the average call length of calls in each of the task router queues or the average call length for all queues in the workspace? I see data for durations until accepted or canceled, but none to show average call length. The closest I can see is using the worker statistics time in busy activity, but I'd have to query all workers and calculate the average.</p>


问:
How can I respond to a browser POST request in a way that does not cause navigation?
tl;dr -- Is there a kind of response I can send to a browser's POST request (from my web server running Node.js/Express.js) that will prevent the browser from navigating to a new page and breaking any open WebSocket connections?

I am implementing the new Sign In With Google OAuth flow from a pure client-sided React app that uses WebSocket for bi-directional communication.

The new Sign in With Google flow uses either a pre-loaded HTML or JavaScript component to render a button for logging in. Clicking the button opens a new window where the user can consent to sharing data and either log in with a Google account or select an existing logged-in account.

Once complete, the Sign-In With Google flow will provide an identity token either via a callback function or a POST request to specified URL. I want to use the second approach to POST the token to a https://my-server/googleLoginComplete endpoint. The endpoint will perform some internal login and session operations, and then communicate to the browser/client via an open WebSocket connection that the login operation is complete.

I have everything working, except for one issue. Google's API is performing a form POST to send the identity token to the developer supplied endpoint, and any response that I return from that endpoint will cause a navigation change in the browser which breaks the web socket connection.

If I had control over the Sign In With Google API, I could do the equivalent of a form.submit.preventDefault() and instead just use a fecth or xmlHttpRequest to perform the POST without navigating to a new page. Unfortunately, Google does not provide this or a similar option, nor do they even have the source code for their new client publicly available.

I've tried sending a 204 and 304 response, an empty object, a generic 200, sending a redirect back to the same URL the browser is already on, not sending anything back at all, destroying the resp completely, and some other variations. But I can't find anything that will simply result in the browser doing nothing. And the web socket connection remains open.

Here is some skeleton code:

// React: '/login.js'

export default function Login() {
  // ...

  return (
    <Row>

    </Row>
  )
}
```
<pre class="lang-js prettyprint-override"><code>// Node.js/Express.js: 'app.js'

//...
app.post('/googleLoginComplete', (req, res) => {
  const googleIdentToken = req.body.credential;

  const sessionId = doSomeInternalSessionStuff(googleIdentToken);
  socket.emit('login.success', {sessionId});

  // Something here to just cause the browser to do nothing
  res.send('ignore this and dont do any navigation');
});
</code>```

(I know that I can change the Sign In With Goole method to use a callback instead, but to keep this consistent with other federated auth providers, I want to use the URL redirect option).

Body:
tl;dr -- Is there a kind of response I can send to a browser's POST request (from my web server running Node.js/Express.js) that will prevent the browser from navigating to a new page and breaking any open WebSocket connections?

I am implementing the new Sign In With Google OAuth flow from a pure client-sided React app that uses WebSocket for bi-directional communication.

The new Sign in With Google flow uses either a pre-loaded HTML or JavaScript component to render a button for logging in. Clicking the button opens a new window where the user can consent to sharing data and either log in with a Google account or select an existing logged-in account.

Once complete, the Sign-In With Google flow will provide an identity token either via a callback function or a POST request to specified URL. I want to use the second approach to POST the token to a https://my-server/googleLoginComplete endpoint. The endpoint will perform some internal login and session operations, and then communicate to the browser/client via an open WebSocket connection that the login operation is complete.

I have everything working, except for one issue. Google's API is performing a form POST to send the identity token to the developer supplied endpoint, and any response that I return from that endpoint will cause a navigation change in the browser which breaks the web socket connection.

If I had control over the Sign In With Google API, I could do the equivalent of a form.submit.preventDefault() and instead just use a fecth or xmlHttpRequest to perform the POST without navigating to a new page. Unfortunately, Google does not provide this or a similar option, nor do they even have the source code for their new client publicly available.

I've tried sending a 204 and 304 response, an empty object, a generic 200, sending a redirect back to the same URL the browser is already on, not sending anything back at all, destroying the resp completely, and some other variations. But I can't find anything that will simply result in the browser doing nothing. And the web socket connection remains open.

Here is some skeleton code:

// React: '/login.js'

export default function Login() {
  // ...

  return (
    <Row>

    </Row>
  )
}

// Node.js/Express.js: 'app.js'

//...
app.post('/googleLoginComplete', (req, res) => {
  const googleIdentToken = req.body.credential;

  const sessionId = doSomeInternalSessionStuff(googleIdentToken);
  socket.emit('login.success', {sessionId});

  // Something here to just cause the browser to do nothing
  res.send('ignore this and dont do any navigation');
});

(I know that I can change the Sign In With Goole method to use a callback instead, but to keep this consistent with other federated auth providers, I want to use the URL redirect option).


问:
Godot: is there any way to stop a node that's following a path?
More specifically, is there any way to stop a node that's following a path when it comes across (overlaps) one of the points on that path?

I am trying to make a game with movement like in FTL Faster Than Light, where when you click in a certain space your crew will move to a spot in that area.

I have been using a Path2D and a PathFollow node to make the crew follow the path, and if they come across an area2d node they will stop. However, this does not really fit what I need, because the crew stop before they actually get to where they need to go.


问:
java Mongo DB update field on condition
I am using spring-boot-starter-data-mongodb and I am performing an update Many to update several records in one operation

```<code>UpdateResult result = collection.updateMany(query, update);
</code>```

The update field is defined like this

```<code>Bson update = Updates.combine(
            Updates.set(field1, 1),
            Updates.set(field2, 2);
</code>```

But now I want to define a conditional update for field3. if field3 == null then field3=3

How can I achieve this? Thanks for your help

Title: java Mongo DB update field on condition

Body:
I am using spring-boot-starter-data-mongodb and I am performing an update Many to update several records in one operation

UpdateResult result = collection.updateMany(query, update);

The update field is defined like this

Bson update = Updates.combine(
            Updates.set(field1, 1),
            Updates.set(field2, 2);

But now I want to define a conditional update for field3. if field3 == null then field3=3

How can I achieve this? Thanks for your help


问:
Is it possible to sort bracket pairs or equivalet pairs from the middle to the outside only using a index in javascript?
I am currently trying to write a templating engine in vanilla javascript. I already filtered the required start and end points for the for loops using regex using the .exec function, thus i have the match itself and the starting index. Now, for the code to 'render' everything properly, the 'pairs' need to be ordered like you would execute them using the bracket rule you use in math.

Here is a demo, where the html contains the data the server would send. It looks like everything is displayed correctly, but a part (compare with template below) is missing. I marked where the sorting should happen with a // The sorting should happen here comment. The template is base64 encoded, here is a non-encoded version:

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Demo</title>

Demo of NSSR

Nested for loop

        {for _itm in test_arr}

For item in array:

        {for itm in test_arr}

{itm}

        {-for} {-for}

For with two variables

Points:

        {for x, y in two_dimensional_array}

Point({x}, {y})

        {-for}

```
<p>Here is the full code:</p>
<pre class="lang-js prettyprint-override"><code>function render_exception(type, description, additional) {
    document.body.innerHTML = `
    <h1>An error occured while rendering the template.</h1>
    <div style="background-color:red;color:white;padding-inline:0.2rem;">
        <h2>${type}</h2>
        <h4>${description}</h4>
    </div> ${additional}
    `;
    return "RenderException";
}

function get_all_regex_matches(regex, str) {
    var res = [];
    var ptrn = RegExp(regex, "mg");
    var match;

    while ((match = ptrn.exec(str)) != null) {
        res.push(match);
    }

    return res;
}

function render_nssr(data, vars, subcall = false) {
    var html = subcall ? data : atob(data);

    /* -------------------------------------------------------------------------- */
    /*                                  For loops                                 */
    /* -------------------------------------------------------------------------- */

    while (1) {
        var start_for = get_all_regex_matches(
            /{ ?for [a-zA-Z, _]+ in [a-zA-Z-_]+ ?}/,
            html
        );
        var end_for = get_all_regex_matches(/{ ?-for ?}/, html).reverse();

        console.log({ start_for, end_for, vars });

        if (subcall) {
            console.log(html);
        }

        if (start_for.length !== end_for.length) {
            return render_exception(
                "TemplateSyntaxException",
                `For loops could not be resolved. Got ${start_for.length} start and ${end_for.length} end indicators.`,
                "Non-resolved for loop: " +
                    (start_for.length < end_for.length
                        ? `${end_for[0][0]} at position ${end_for[0]["index"]}`
                        : `${start_for[0][0]} at position ${start_for[0]["index"]}`)
            );
        }

        // The sorting should happen here

        console.log({ start_for, end_for, vars });

        if (start_for.length == 0) {
            break;
        }

        var loop_line = start_for[0][0]
            .replaceAll(/[\{\}]/g, "")
            .replaceAll(/ ?, ?/g, ",")
            .trim()
            .split(/[ ,]/g);

        var start = start_for[0]["index"] + start_for[0][0].length;
        var end = end_for[0]["index"];

        if (!subcall) {
            start_for.forEach(function (it, indx) {
                var s = it["index"] + it[0].length;
                var e = end_for[indx]["index"];
                console.log(s, e, html.substring(s, e));
            });
        }

        var computed_loop_res = "";

        vars[loop_line[loop_line.length - 1]].forEach(function (ele) {
            var var_clone = structuredClone(vars);
            var loop_var_names = loop_line.slice(1, loop_line.length - 2);

            for (var ni = 0; ni < loop_var_names.length; ni++) {
                if (ele.length >= ni + 1) {
                    try {
                        if (loop_var_names.length > 1) {
                            var_clone[loop_var_names[ni]] = ele[ni];
                        } else {
                            var_clone[loop_var_names[ni]] = ele;
                        }
                    } catch (e) {}
                } else {
                    var_clone[loop_var_names[ni]] = undefined;
                }
            }

            console.log(html.substring(start, end));

            computed_loop_res += render_nssr(
                html.substring(start, end),
                var_clone,
                true
            );
        });

        html =
            html.substring(0, start_for[0]["index"]) +
            computed_loop_res +
            html.substring(end_for[0]["index"] + end_for[0][0].length);
    }

    /* -------------------------------------------------------------------------- */
    /*                              Normal variables                              */
    /* -------------------------------------------------------------------------- */

    for (const [key, value] of Object.entries(vars)) {
        html = html.replaceAll(new RegExp(`{ ?${key} ?}`, "mg"), value);
    }

    /* -------------------------------------------------------------------------- */
    /*                            Returning/Displaying                            */
    /* -------------------------------------------------------------------------- */

    if (subcall) {
        return html;
    }

    document.documentElement.innerHTML = html;
}
</code>```

```
<p>Here is a python flask server I use for testing and developing:</p>
<pre class="lang-py prettyprint-override"><code>from flask import Flask, send_file, Response

import os
import base64

app = Flask("NSSR-Example")

def render_nssr_template(file: str, **vars):
    json_var_data = json.dumps(vars)

    with open(os.path.join("./templates", file), "r", encoding="UTF-8") as f:
        template_data = base64.b64encode(f.read().encode("ascii")).decode("ascii")

    return Response(
        f"<script src='nssr.js'></script><script>document.addEventListener('DOMContentLoaded',function(){{render_nssr('{template_data}',{json_var_data})}})</script>"
    )

@app.route("/")
def index():
    return render_nssr_template(
        "example.html",
        test_arr=["Item 1", "Item 2", "Item 3"],
        two_dimensional_array=[[1, 0], [1, 1], [0, 1], [0, 0]],
    )

@app.route("/<path:path>")
def get_file(path):
    return send_file(path)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

I tried to come up with an algorithm, but I couldn't come up with one.
Here is what should happen:

This is a model for our 'bracket pairs' with a sample index:

```<code>( 1
    ( 2

    ) 3
) 4

( 5

) 6
</code>```

The regex parses them like this:

open = [["(", index: 1], ["(", index: 2], ["(", index: 5]]
close = [[")", index: 3], [")", index: 4], [")", index: 6]]
```
<p>I want these lists sorted in a order, that the first result from 'open' corresponds to the first result from 'open', and inner pairs should be listed in front of there corresponding parents. In my code, these lists are called <code>start_for</code> and <code>end_for</code>.</p>
<p>The results therefor should look something like this:</p>
<pre class="lang-js prettyprint-override"><code>open = [["(", index: 2], ["(", index: 1], ["(", index: 5]]
close = [[")", index: 3], [")", index: 4], [")", index: 6]]

or

open = [["(", index: 5], ["(", index: 2], ["(", index: 1]]
close = [[")", index: 6], [")", index: 3], [")", index: 4]]
</code>```

So basically these must be ordered from the inside out, with just the index as 'locational information'.

Is this possible, or has anyone a recommendation on a better approach?

Body:
I am currently trying to write a templating engine in vanilla javascript. I already filtered the required start and end points for the for loops using regex using the .exec function, thus i have the match itself and the starting index. Now, for the code to 'render' everything properly, the 'pairs' need to be ordered like you would execute them using the bracket rule you use in math.

Here is a demo, where the html contains the data the server would send. It looks like everything is displayed correctly, but a part (compare with template below) is missing. I marked where the sorting should happen with a // The sorting should happen here comment. The template is base64 encoded, here is a non-encoded version:

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Demo</title>

Demo of NSSR

Nested for loop

        {for _itm in test_arr}

For item in array:

        {for itm in test_arr}

{itm}

        {-for} {-for}

For with two variables

Points:

        {for x, y in two_dimensional_array}

Point({x}, {y})

        {-for}

Here is the full code:

function render_exception(type, description, additional) {
    document.body.innerHTML = `

An error occured while rendering the template.

${type}

${description}

 ${additional}
    `;
    return "RenderException";
}

function get_all_regex_matches(regex, str) {
    var res = [];
    var ptrn = RegExp(regex, "mg");
    var match;

    while ((match = ptrn.exec(str)) != null) {
        res.push(match);
    }

    return res;
}

function render_nssr(data, vars, subcall = false) {
    var html = subcall ? data : atob(data);

    /* -------------------------------------------------------------------------- */
    /*                                  For loops                                 */
    /* -------------------------------------------------------------------------- */

    while (1) {
        var start_for = get_all_regex_matches(
            /{ ?for [a-zA-Z, _]+ in [a-zA-Z-_]+ ?}/,
            html
        );
        var end_for = get_all_regex_matches(/{ ?-for ?}/, html).reverse();

        console.log({ start_for, end_for, vars });

        if (subcall) {
            console.log(html);
        }

        if (start_for.length !== end_for.length) {
            return render_exception(
                "TemplateSyntaxException",
                `For loops could not be resolved. Got ${start_for.length} start and ${end_for.length} end indicators.`,
                "Non-resolved for loop: " +
                    (start_for.length < end_for.length
                        ? `${end_for[0][0]} at position ${end_for[0]["index"]}`
                        : `${start_for[0][0]} at position ${start_for[0]["index"]}`)
            );
        }

        // The sorting should happen here

        console.log({ start_for, end_for, vars });

        if (start_for.length == 0) {
            break;
        }

        var loop_line = start_for[0][0]
            .replaceAll(/[\{\}]/g, "")
            .replaceAll(/ ?, ?/g, ",")
            .trim()
            .split(/[ ,]/g);

        var start = start_for[0]["index"] + start_for[0][0].length;
        var end = end_for[0]["index"];

        if (!subcall) {
            start_for.forEach(function (it, indx) {
                var s = it["index"] + it[0].length;
                var e = end_for[indx]["index"];
                console.log(s, e, html.substring(s, e));
            });
        }

        var computed_loop_res = "";

        vars[loop_line[loop_line.length - 1]].forEach(function (ele) {
            var var_clone = structuredClone(vars);
            var loop_var_names = loop_line.slice(1, loop_line.length - 2);

            for (var ni = 0; ni < loop_var_names.length; ni++) {
                if (ele.length >= ni + 1) {
                    try {
                        if (loop_var_names.length > 1) {
                            var_clone[loop_var_names[ni]] = ele[ni];
                        } else {
                            var_clone[loop_var_names[ni]] = ele;
                        }
                    } catch (e) {}
                } else {
                    var_clone[loop_var_names[ni]] = undefined;
                }
            }

            console.log(html.substring(start, end));

            computed_loop_res += render_nssr(
                html.substring(start, end),
                var_clone,
                true
            );
        });

        html =
            html.substring(0, start_for[0]["index"]) +
            computed_loop_res +
            html.substring(end_for[0]["index"] + end_for[0][0].length);
    }

    /* -------------------------------------------------------------------------- */
    /*                              Normal variables                              */
    /* -------------------------------------------------------------------------- */

    for (const [key, value] of Object.entries(vars)) {
        html = html.replaceAll(new RegExp(`{ ?${key} ?}`, "mg"), value);
    }

    /* -------------------------------------------------------------------------- */
    /*                            Returning/Displaying                            */
    /* -------------------------------------------------------------------------- */

    if (subcall) {
        return html;
    }

    document.documentElement.innerHTML = html;
}

Here is a python flask server I use for testing and developing:

from flask import Flask, send_file, Response

import os
import base64

app = Flask("NSSR-Example")

def render_nssr_template(file: str, **vars):
    json_var_data = json.dumps(vars)

    with open(os.path.join("./templates", file), "r", encoding="UTF-8") as f:
        template_data = base64.b64encode(f.read().encode("ascii")).decode("ascii")

    return Response(
        f""
    )

@app.route("/")
def index():
    return render_nssr_template(
        "example.html",
        test_arr=["Item 1", "Item 2", "Item 3"],
        two_dimensional_array=[[1, 0], [1, 1], [0, 1], [0, 0]],
    )

@app.route("/<path:path>")
def get_file(path):
    return send_file(path)

if __name__ == "__main__":
    app.run(debug=True)

I tried to come up with an algorithm, but I couldn't come up with one.
Here is what should happen:

This is a model for our 'bracket pairs' with a sample index:

( 1
    ( 2

    ) 3
) 4

( 5

) 6

The regex parses them like this:

open = [["(", index: 1], ["(", index: 2], ["(", index: 5]]
close = [[")", index: 3], [")", index: 4], [")", index: 6]]

I want these lists sorted in a order, that the first result from 'open' corresponds to the first result from 'open', and inner pairs should be listed in front of there corresponding parents. In my code, these lists are called start_for and end_for.

The results therefor should look something like this:

open = [["(", index: 2], ["(", index: 1], ["(", index: 5]]
close = [[")", index: 3], [")", index: 4], [")", index: 6]]

or

open = [["(", index: 5], ["(", index: 2], ["(", index: 1]]
close = [[")", index: 6], [")", index: 3], [")", index: 4]]

So basically these must be ordered from the inside out, with just the index as 'locational information'.

Is this possible, or has anyone a recommendation on a better approach?


问:
R Package Data Files: Data Downloaded From Cloud is Inaccessible
There is an R data package I would like to submit to CRAN, but the data is too large. Therefore, I want to design the package so it comes with samples of the full data and users can choose to replace the sample data with the full data.

I wrote a function that lets users download the full data from the cloud. However, once the full data is downloaded, it is inaccessible.

I would be grateful for your help making it so that the full data replaces the sample data.

Example:

```<code># install and load the package
library(devtools)
install_github("stephbuon/hansardr")
library(hansardr)

# Read the sample data
data(hansard_1800)
</code>```

Then you can download the full Hansard corpus from the cloud:

```<code>download_hansard()
</code>```

The full data will be downloaded to the package's data folder (see: list.files(paste0(.libPaths(), "/hansardr/data")))

However, when I use data(hansard_1800) I still only see the sample data. My hope is that data(hansard_1800) would now allow the user to access the full data.

Thanks so much for your help.

Body:
There is an R data package I would like to submit to CRAN, but the data is too large. Therefore, I want to design the package so it comes with samples of the full data and users can choose to replace the sample data with the full data.

I wrote a function that lets users download the full data from the cloud. However, once the full data is downloaded, it is inaccessible.

I would be grateful for your help making it so that the full data replaces the sample data.

Example:

# install and load the package
library(devtools)
install_github("stephbuon/hansardr")
library(hansardr)

# Read the sample data
data(hansard_1800)

Then you can download the full Hansard corpus from the cloud:

download_hansard()

The full data will be downloaded to the package's data folder (see: list.files(paste0(.libPaths(), "/hansardr/data")))

However, when I use data(hansard_1800) I still only see the sample data. My hope is that data(hansard_1800) would now allow the user to access the full data.

Thanks so much for your help.


问:
How to change the content of grid items without using 'vw' units?
I'm quite new to building grid layouts. I'm trying to change the dimensions of the content in the grid elements via pixels, percentages, but they remain the same, only viewport units work. There are grid-template-columns and grid-template-rows allow to increase the size of the content. I'm trying to make the top two elements: logo and menu hamburger, get bigger and almost adjacent to each other. And, I noticed that if reduce the height of the visible area of the screen, then the elements increase. Why can't I "simply" increase these two elements without doing this is beyond me? Below is a piece of code and one screenshot of what the mobile version looks like now, and how it should. Please check what is wrong.

    * {
            padding:0;
            margin:0;
            box-sizing: border-box;
}
body {
            font-family: "Segoe UI", sans-serif;
            height: 100vh;
}
        .container {
            display: grid;
            grid-template-columns: repeat(10, 10%);
            grid-template-rows: repeat(20, 5%);
            height: 100%;
            box-sizing: border-box;
        }
        .logo {
            grid-column: 1 / 10;
            grid-row: 1 / 4;
            background-color: #f8f8f8;
            display: flex;
            align-items: center;
            padding-left: 3%;
        }
        .logo img {
            max-width: 100%;
            height: auto;
        }
        .header {
            grid-column: 10 / 11;
            grid-row: 1 / 4;
            background-color: #f8f8f8;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .gsi {
            background-color: #1b8183;
            grid-column: 1 / 6;
            grid-row: 8 / 17;
            z-index: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-evenly;
            align-items: start;
            padding-left: 7%;
        }
        /* Text */
        .gsi h1 {
        font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
        font-weight: normal;
        font-style: normal;
        font-size: 3vw;
        color: #ffffff;
        white-space: nowrap;
}
        .gsi h1::after {
         display: inline-block;
         vertical-align: middle;
         content: "";
         height: 1px;
         position: relative;
         background-color: #ffffff;
         width: 4vw;
         right: -0.5em;
}
        .gsi p {
         font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
         font-weight: normal;
         font-style: normal;
         font-size: 2vw;
         color: #ffffff;
         margin: 0;
         white-space: nowrap;
}
        .button {
        font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
        font-size: 1.5vw;
        background-color: rgba(28, 28, 28, 0);
        border: 2px solid #fff;
        border-radius: 3em / 3em;
        color: white;
        padding: 1% 7.5%;
        text-align: center;
        text-decoration: none;
        margin: 4px 2px;
        cursor: pointer;
}
        .pillar {
         grid-column: 5 / 11;
         grid-row: 4 / 21;
}
        .pillar img {
         width: 100%;
         height: 100%;
         object-fit: cover;
}
/* Anything related to hamburger */
        .logo-text a:active,
        .logo-text a:hover,
        .logo-text a {
        text-decoration: none;
        color: #1b8183;
        font-size: 2vw;
        font-weight: bold;
        }
        .menu-btn {
            height: 70px;
            position: relative;
            z-index: 3;
            overflow: hidden;
            padding-right: 50px;
            cursor: pointer;
        }

        .menu-btn span {
            width: 50px;
            height: 4px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #538b99;
            border: 1px solid #538b99;
            border-radius: 10px;
            transition: all 0.5s;
        }

        .menu-btn span:nth-of-type(2) {
            top: calc(40% - 5px);
        }
        .menu-btn span:nth-of-type(3) {
            top: calc(60% + 5px);
        }
        .menu-btn.active span:nth-of-type(1) {
            display: none;
        }
        .menu-btn.active span:nth-of-type(2) {
            top: 50%;
            transform: translate(-50%, 0%) rotate(45deg);
        }
        .menu-btn.active span:nth-of-type(3) {
            top: 50%;
            transform: translate(-50%, 0%) rotate(-45deg);
        }
        .menu {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            padding: 15px;
            background: #f8f8f8;
            transform: translateX(-100%);
            transition: transform 0.5s;
        }

        .menu.active {
            transform: translateX(0);
            z-index: 2; /* > gsi =1  & < menu.active = 3 */
        }
        .menu li {
            list-style-type: none;
            font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
            font-weight: normal;
            font-style: normal;
            font-size: 2vw;
            padding-top: 2%;
        }
        .menu.active nav {
            margin: 0 auto;
            text-align: center;
        }
        .menu.active nav a {
            position: relative;
            color: black;
            cursor: pointer;
            line-height: 1;
            text-decoration: none;
        }
        .menu.active nav a:after {
            display: block;
            position: absolute;
            left: 0;
            width: 0;
            height: 3.5px;
            background-color: black;
            content: "";
            transition: width 0.4s ease-out;
}
        .menu.active nav a:hover:after,
        .menu.active nav a:focus:after {
            width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=0">
        <title>Web-site</title>
    </head>
    <body>
    <div class="container">
        <div class="logo"><img src="https://i.postimg.cc/bYD24JGb/logo.png" alt="логотип"></div>
        <div class="header">
            <div class="menu-btn">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
        <div class="menu">
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Services</li>
                    <li>Contacts</li>
                </ul>
            </nav>
        </div>
        <div class="gsi"><h1>NAME</h1><p>Lorem Ipsum</p><input type="button" class="button" value="Compose"></div>
        <div class="pillar"><img src="https://i.postimg.cc/7hxMnrVX/pillar.png" alt="Pillar"></div>
    </div>
    </body>
    </html></code>```

Body:
I'm quite new to building grid layouts. I'm trying to change the dimensions of the content in the grid elements via pixels, percentages, but they remain the same, only viewport units work. There are grid-template-columns and grid-template-rows allow to increase the size of the content. I'm trying to make the top two elements: logo and menu hamburger, get bigger and almost adjacent to each other. And, I noticed that if reduce the height of the visible area of the screen, then the elements increase. Why can't I "simply" increase these two elements without doing this is beyond me? Below is a piece of code and one screenshot of what the mobile version looks like now, and how it should. Please check what is wrong.

    * {
            padding:0;
            margin:0;
            box-sizing: border-box;
}
body {
            font-family: "Segoe UI", sans-serif;
            height: 100vh;
}
        .container {
            display: grid;
            grid-template-columns: repeat(10, 10%);
            grid-template-rows: repeat(20, 5%);
            height: 100%;
            box-sizing: border-box;
        }
        .logo {
            grid-column: 1 / 10;
            grid-row: 1 / 4;
            background-color: #f8f8f8;
            display: flex;
            align-items: center;
            padding-left: 3%;
        }
        .logo img {
            max-width: 100%;
            height: auto;
        }
        .header {
            grid-column: 10 / 11;
            grid-row: 1 / 4;
            background-color: #f8f8f8;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .gsi {
            background-color: #1b8183;
            grid-column: 1 / 6;
            grid-row: 8 / 17;
            z-index: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-evenly;
            align-items: start;
            padding-left: 7%;
        }
        /* Text */
        .gsi h1 {
        font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
        font-weight: normal;
        font-style: normal;
        font-size: 3vw;
        color: #ffffff;
        white-space: nowrap;
}
        .gsi h1::after {
         display: inline-block;
         vertical-align: middle;
         content: "";
         height: 1px;
         position: relative;
         background-color: #ffffff;
         width: 4vw;
         right: -0.5em;
}
        .gsi p {
         font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
         font-weight: normal;
         font-style: normal;
         font-size: 2vw;
         color: #ffffff;
         margin: 0;
         white-space: nowrap;
}
        .button {
        font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
        font-size: 1.5vw;
        background-color: rgba(28, 28, 28, 0);
        border: 2px solid #fff;
        border-radius: 3em / 3em;
        color: white;
        padding: 1% 7.5%;
        text-align: center;
        text-decoration: none;
        margin: 4px 2px;
        cursor: pointer;
}
        .pillar {
         grid-column: 5 / 11;
         grid-row: 4 / 21;
}
        .pillar img {
         width: 100%;
         height: 100%;
         object-fit: cover;
}
/* Anything related to hamburger */
        .logo-text a:active,
        .logo-text a:hover,
        .logo-text a {
        text-decoration: none;
        color: #1b8183;
        font-size: 2vw;
        font-weight: bold;
        }
        .menu-btn {
            height: 70px;
            position: relative;
            z-index: 3;
            overflow: hidden;
            padding-right: 50px;
            cursor: pointer;
        }

        .menu-btn span {
            width: 50px;
            height: 4px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #538b99;
            border: 1px solid #538b99;
            border-radius: 10px;
            transition: all 0.5s;
        }

        .menu-btn span:nth-of-type(2) {
            top: calc(40% - 5px);
        }
        .menu-btn span:nth-of-type(3) {
            top: calc(60% + 5px);
        }
        .menu-btn.active span:nth-of-type(1) {
            display: none;
        }
        .menu-btn.active span:nth-of-type(2) {
            top: 50%;
            transform: translate(-50%, 0%) rotate(45deg);
        }
        .menu-btn.active span:nth-of-type(3) {
            top: 50%;
            transform: translate(-50%, 0%) rotate(-45deg);
        }
        .menu {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            padding: 15px;
            background: #f8f8f8;
            transform: translateX(-100%);
            transition: transform 0.5s;
        }

        .menu.active {
            transform: translateX(0);
            z-index: 2; /* > gsi =1  & < menu.active = 3 */
        }
        .menu li {
            list-style-type: none;
            font-family: 'TT Norms', Helvetica Now, Helvetica, Arial, sans-serif;
            font-weight: normal;
            font-style: normal;
            font-size: 2vw;
            padding-top: 2%;
        }
        .menu.active nav {
            margin: 0 auto;
            text-align: center;
        }
        .menu.active nav a {
            position: relative;
            color: black;
            cursor: pointer;
            line-height: 1;
            text-decoration: none;
        }
        .menu.active nav a:after {
            display: block;
            position: absolute;
            left: 0;
            width: 0;
            height: 3.5px;
            background-color: black;
            content: "";
            transition: width 0.4s ease-out;
}
        .menu.active nav a:hover:after,
        .menu.active nav a:focus:after {
            width: 100%;
}

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=0">
        <title>Web-site</title>

Home

About

Services

Contacts

NAME

Lorem Ipsum
<input type="button" class="button" value="Compose">


问:
How to access pre-compiled JSP's classes present in WEB-INF/classes folder, when App is bundeled in ear format and deployed in WildFly server?
Explanation:

We are using WildFly 18.0.1 in domain mode with one master and multiple slaves with jdk1.8.0_261.
Application is deployed on WildFly Master in zipped .ear format.
Application Ear Structure

```<code>  application.ear
  -> abc.war
     -> file1.html
     -> file2.js
     -> ...
     ->  WEB-INF
         -> classes
             -> org
               -> apache
                 -> jsp
                    -> com
                       ->test
                          -> test_005_login.class
         ->  web.xml
         ->  jboss-web.xml
 -> pqr.jar
 -> lib
 -> xyz.war
 -> META-INF
     -> application.xml
     -> jboss-deployment-structure.xml
</code>```

We want to access test_login.jsp from pqr.jar and other wars, which has code to call test_login.jsp present in com/test folder.

In domain.xml we use following configuration for JSPs.

Note:
We want to avoid JSP servlet entries in web.xml as we have more than 100 JSPs

Body:
Explanation:

We are using WildFly 18.0.1 in domain mode with one master and multiple slaves with jdk1.8.0_261.
Application is deployed on WildFly Master in zipped .ear format.
Application Ear Structure

  application.ear
  -> abc.war
     -> file1.html
     -> file2.js
     -> ...
     ->  WEB-INF
         -> classes
             -> org
               -> apache
                 -> jsp
                    -> com
                       ->test
                          -> test_005_login.class
         ->  web.xml
         ->  jboss-web.xml
 -> pqr.jar
 -> lib
 -> xyz.war
 -> META-INF
     -> application.xml
     -> jboss-deployment-structure.xml

We want to access test_login.jsp from pqr.jar and other wars, which has code to call test_login.jsp present in com/test folder.

In domain.xml we use following configuration for JSPs.

Note:
We want to avoid JSP servlet entries in web.xml as we have more than 100 JSPs


问:
Is it possible to extract the vendor chunk for an angular library?
I would like a vendor.js to accompany my angular library JavaScript. (This excludes the ts-js transpilation and enables analysis of domain only code). When I add "vendorChunk": true to the architect/builder/options or architect/builder/configurations/{env}, ng build complains:

```<code>Schema validation failed with the following errors:
  Data path "" must NOT have additional properties(vendorChunk).
</code>```

The builder schema appears to agree. The schema for the standard application 'browser' builder supports many customizations including vendorChunk, nameChunks, optimization, etc. The current schema, which doesn't appear to have changed even since angular 10 schema, for the builder for libraries called ng-packagr has none of these options. It seems to be fixed to named chunks, no optimization or compression but does not chunk out the vendor stuff.

Is there another way to signal to the library build to extract the vendor javascript?

Body:
I would like a vendor.js to accompany my angular library JavaScript. (This excludes the ts-js transpilation and enables analysis of domain only code). When I add "vendorChunk": true to the architect/builder/options or architect/builder/configurations/{env}, ng build complains:

Schema validation failed with the following errors:
  Data path "" must NOT have additional properties(vendorChunk).

The builder schema appears to agree. The schema for the standard application 'browser' builder supports many customizations including vendorChunk, nameChunks, optimization, etc. The current schema, which doesn't appear to have changed even since angular 10 schema, for the builder for libraries called ng-packagr has none of these options. It seems to be fixed to named chunks, no optimization or compression but does not chunk out the vendor stuff.

Is there another way to signal to the library build to extract the vendor javascript?


问:
how to use findNavController properly in fragment? android studio(kotlin)
when i tried that code in main activity it worked perfectly without any errors. But when i moved code from main activity to mine fragment kt file got some errors. Any solutions?

Here is my kt files:

```<code>class MainFragment : Fragment(R.layout.fragment_main) {
    private lateinit var bottomNavigationView: BottomNavigationView
    private lateinit var navController: NavController

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        bottomNavigationView = view.findViewById(R.id.bottomNavView)
        navController = findNavController(R.id.nav_host_fragment)
    }
}
</code>```
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".fragments.MainFragment">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
when i tried that code in main activity it worked perfectly without any errors. But when i moved code from main activity to mine fragment kt file got some errors. Any solutions?

Here is my kt files:

class MainFragment : Fragment(R.layout.fragment_main) {
    private lateinit var bottomNavigationView: BottomNavigationView
    private lateinit var navController: NavController

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        bottomNavigationView = view.findViewById(R.id.bottomNavView)
        navController = findNavController(R.id.nav_host_fragment)
    }
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".fragments.MainFragment">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Detect start and end of an exe launched by another exe from java
I am building a standalone program in java that launches 'exe' or 'lnk' and gets the execution time.

It has worked perfectly for me but with one of the programs launches a second exe and the first one closes giving me only the time of the first when I need both.

The first option that occurred to me is to launch the second directly but this gives an error if it is not launched from the first

My code is

```<code>String ruta = "C:\\folder\\launch.exe";
long inicio = System.currentTimeMillis();
Process p;
try {
    p = new ProcessBuilder("cmd", "/c", "\"" + ruta + "\"").redirectError(Redirect.INHERIT).redirectInput(Redirect.INHERIT).redirectOutput(Redirect.INHERIT).start();

    p.waitFor();

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

long fin = System.currentTimeMillis();
long total = fin - inicio;
</code>```

Is there any way to do what I need?

Many Thanks

Body:
I am building a standalone program in java that launches 'exe' or 'lnk' and gets the execution time.

It has worked perfectly for me but with one of the programs launches a second exe and the first one closes giving me only the time of the first when I need both.

The first option that occurred to me is to launch the second directly but this gives an error if it is not launched from the first

My code is

String ruta = "C:\\folder\\launch.exe";
long inicio = System.currentTimeMillis();
Process p;
try {
    p = new ProcessBuilder("cmd", "/c", "\"" + ruta + "\"").redirectError(Redirect.INHERIT).redirectInput(Redirect.INHERIT).redirectOutput(Redirect.INHERIT).start();

    p.waitFor();

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

long fin = System.currentTimeMillis();
long total = fin - inicio;

Is there any way to do what I need?

Many Thanks


问:
Removing a filereader video makes the player remain. How do I remove the player as well?
I have a file upload that I use to upload video files. Once uploaded I preview the videos in a HTML 5 video element

```<code><video
    id="video-preview"
    width="400"
    height="240"
    controls
    src=""
></video>
</code>```

Here is the code to handle the video preview:

```<code>function handleVideo(event) {
    fields.value.previews = [];
    hasVideo.value = true;
    let video = document.getElementById("video-preview");
    var file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.addEventListener("load", function () {
        video.src = reader.result;
    });
}
</code>```

As soon as I have uploaded a file the preview shows the video and the controls and I can play the video. Now I would like to remove the player in case I don't want to upload a video anymore. Clearing the source simply removes the video but the player remains.

How can I remove the player and the video (src) so there is nothing except an empty video element?

video.remove() removes the entire video element and I cannot upload a video again (in case I change my mind)

Body:
I have a file upload that I use to upload video files. Once uploaded I preview the videos in a HTML 5 video element

<video
    id="video-preview"
    width="400"
    height="240"
    controls
    src=""
></video>

Here is the code to handle the video preview:

function handleVideo(event) {
    fields.value.previews = [];
    hasVideo.value = true;
    let video = document.getElementById("video-preview");
    var file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.addEventListener("load", function () {
        video.src = reader.result;
    });
}

As soon as I have uploaded a file the preview shows the video and the controls and I can play the video. Now I would like to remove the player in case I don't want to upload a video anymore. Clearing the source simply removes the video but the player remains.

How can I remove the player and the video (src) so there is nothing except an empty video element?

video.remove() removes the entire video element and I cannot upload a video again (in case I change my mind)


问:
Mockery\Exception\BadMethodCallException: Method Mockery_0__does not exist on this mock object
When running phpunit I get the following error:

Mockery\Exception\BadMethodCallException: Method Mockery_0__Tests_Unit_App_Utils_Blueprints_BlueprintRuleUtil::executeActiveBlueprintRules() does not exist on this mock object

The test method that is failing is:

```<code>public function testExecuteActiveBlueprintRulesShouldExecuteDefaultOutsourceCostRule()
{
    Strategy::fake();

    Strategy::create(['id' => 1]);
    $createdStrategy = Strategy::getCreatedModel();

    /**
     * We can use a partial mock for BlueprintRuleUtil so we can mock specific methods
     * later on using shouldReceive while still being able to call regular methods on the class
     * including the one we are testing in this test case.
     */
    $blueprint_rule_util_partial_mock = \Mockery::mock(App\Utils\Blueprints\BlueprintRuleUtil::class)->makePartial();

    /**
     * For method chaining with the DB facade
     * we want to use mockery to mock each chained method
     * and use andReturnSelf() to return an instance of the
     * returned value until we reach the last method call in the chain.
     *
     * Then we can return the final result that we should be expecting
     * which is likely a stdClass object as a query result.
     */
    $active_blueprint_rule = new stdClass();
    $active_blueprint_rule->id = 1001;

    DB::shouldReceive("table")
        ->with('blueprint_rules')
        ->once()->andReturnSelf();

    DB::shouldReceive("where")
        ->with('is_active', true)
        ->andReturnSelf();

    DB::shouldReceive("get")
        ->andReturn([$active_blueprint_rule]);

    $blueprint_rule_util_partial_mock->shouldReceive('addDefaultOutsourceCostToStrategy')
        ->withAnyArgs();
    $blueprint_rule_util_partial_mock->shouldReceive('shouldAddDefaultOutsourceCost')->withAnyArgs()->andReturn(true);

    $blueprint_rule_util_partial_mock->executeActiveBlueprintRules($createdStrategy);

    Strategy::stopFaking();
}
</code>```

Here is the full test class I am using:

namespace Tests\Unit;

/**
 * Need to use built in laravel testcase instead of PHPUnit testcase to have access to instance variables like app for mocking
 */

use Tests\TestCase;
use App\Strategy;
use App\Pillar;
use App\Utils\Blueprints\BlueprintRuleUtil;
use DB;
use stdClass;

class BlueprintRuleUtilTest extends TestCase
{
    /**
     * Test to make sure outsource cost will not be added
     * with a certain blueprint type and pillars.
     */
    public function testShouldAddDefaultSnowflakeOutsourceCostWillReturnFalse()
    {
        Strategy::fake();
        Pillar::fake();

        Strategy::create(['id' => 1]);

        // test core business first
        Pillar::create(['id' => 1, 'slug' => 'core-new-business']);

        $createdStrategy = Strategy::getCreatedModel();
        // set the pillar to be the created model so it can grab it's pillar property later on using a relation
        $createdStrategy->pillar = Pillar::getCreatedModel();

        $blueprint_rule_util = new BlueprintRuleUtil();

        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        // test service expansion by updating the pillar
        $createdStrategy->pillar->slug = 'service-expansion';
        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        // test with blueprint type set to project and valid pillar slug
        $createdStrategy->pillar->slug = 'resign';
        $createdStrategy->type = 'project';
        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        Strategy::stopFaking();
        Pillar::stopFaking();
    }

    /**
     * Test given a valid slug and project type that the
     * Snowflake default outsource cost is added
     */
    public function testShouldAddDefaultSnowflakeOutsourceCostWillReturnTrue()
    {
        Strategy::fake();
        Pillar::fake();

        Strategy::create(['id' => 1]);

        $blueprint_rule_util = new BlueprintRuleUtil();

        // test resign which is a valid pillar
        Pillar::create(['id' => 1, 'slug' => 'resign']);

        $createdStrategy = Strategy::getCreatedModel();
        // test with valid type retainer
        $createdStrategy->type = 'retainer';
        // set the pillar to be the created model so it can grab it's pillar property later on using a relation
        $createdStrategy->pillar = Pillar::getCreatedModel();
        $this->assertTrue($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        Strategy::stopFaking();
        Pillar::stopFaking();
    }

    public function testExecuteActiveBlueprintRulesShouldExecuteDefaultOutsourceCostRule()
    {
        Strategy::fake();

        Strategy::create(['id' => 1]);
        $createdStrategy = Strategy::getCreatedModel();

        /**
         * We can use a partial mock for BlueprintRuleUtil so we can mock specific methods
         * later on using shouldReceive while still being able to call regular methods on the class
         * including the one we are testing in this test case.
         */
        $blueprint_rule_util_partial_mock = \Mockery::mock(App\Utils\Blueprints\BlueprintRuleUtil::class)->makePartial();

        /**
         * For method chaining with the DB facade
         * we want to use mockery to mock each chained method
         * and use andReturnSelf() to return an instance of the
         * returned value until we reach the last method call in the chain.
         *
         * Then we can return the final result that we should be expecting
         * which is likely a stdClass object as a query result.
         */
        $active_blueprint_rule = new stdClass();
        $active_blueprint_rule->id = 1001;

        DB::shouldReceive("table")
            ->with('blueprint_rules')
            ->once()->andReturnSelf();

        DB::shouldReceive("where")
            ->with('is_active', true)
            ->andReturnSelf();

        DB::shouldReceive("get")
            ->andReturn([$active_blueprint_rule]);

        $blueprint_rule_util_partial_mock->shouldReceive('addDefaultOutsourceCostToStrategy')
            ->withAnyArgs();
        $blueprint_rule_util_partial_mock->shouldReceive('shouldAddDefaultOutsourceCost')->withAnyArgs()->andReturn(true);

        $blueprint_rule_util_partial_mock->executeActiveBlueprintRules($createdStrategy);

        Strategy::stopFaking();
    }
}
```
<p>Here is the class I am testing against:</p>
<pre class="lang-php prettyprint-override"><code>namespace App\Utils\Blueprints;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Strategy;
use App\StrategyCost;

class BlueprintRuleUtil
{
    const DEFAULT_OUTSOURCE_COST_RULE_ID = 1001;

    /**
     * Iterate through the active blueprint rules and execute them based on their name
     *
     * @param Strategy $strategy
     *
     */
    public function executeActiveBlueprintRules(Strategy $strategy)
    {
        if (!is_null($strategy)) {
            $active_blueprint_rules = DB::table('blueprint_rules')
                ->where('is_active', true)
                ->get();

            foreach ($active_blueprint_rules as $active_blueprint_rule) {
                if (!is_null($active_blueprint_rule) && $active_blueprint_rule->id === self::DEFAULT_OUTSOURCE_COST_RULE_ID) {
                    BlueprintRuleUtil::addDefaultOutsourceCostToStrategy($strategy, $active_blueprint_rule);
                }
            }
        }
    }

    /**
     * Given a strategy (blueprint)
     *
     * Return true if we should add the default outsource cost to it
     * false if not based on the blueprint type and pillar
     *
     * @param Strategy $strategy
     *
     * @return bool
     */
    public function shouldAddDefaultOutsourceCost(Strategy $strategy)
    {
        $pillar_slugs_to_exclude_for_outsource_costs = [
            'core-new-business',
            'service-expansion'
        ];
        if (
            in_array($strategy->pillar->slug, $pillar_slugs_to_exclude_for_outsource_costs)
            || $strategy->type === 'project'
        ) {
            return false;
        }
        return true;
    }

    /**
     * Create a StrategyCost entry in the db for the provided strategy
     * using the amount from the active blueprint rule to add the default outsource cost.
     *
     * @param Strategy $strategy
     * @param object $active_blueprint_rule
     */
    public function addDefaultOutsourceCostToStrategy(Strategy $strategy, object $active_blueprint_rule)
    {
        if (self::shouldAddDefaultOutsourceCost($strategy)) {
            $department_slug = 'data-intelligence';
            $department = DB::table('departments')
                ->where('slug', $department_slug)
                ->first();

            if (!is_null($department)) {
                $strategy_cost = new StrategyCost;
                $strategy_cost->name = 'Snowflake';
                $strategy_cost->department_id = $department->id;
                $strategy_cost->strategy_id = $strategy->id;
                // set first month to outsource cost
                $strategy_cost->month_1 = $active_blueprint_rule->amount;
                $strategy_cost->save();
                $strategy_cost->strategy->recalculate();
            } else {
                Log::debug("BlueprintRuleUtil: department $department_slug not found, did not add default outsource cost");
            }
        }
    }
}
</code>```

I have tried using the full class name path with the namespace as the argument when creating the partial mock. I thought that might fix it because it may not be loading the right object. However that didn't work.

The method name is in the class that I am mocking. I'm not sure why I continue to get this error.

Body:
When running phpunit I get the following error:

Mockery\Exception\BadMethodCallException: Method Mockery_0__Tests_Unit_App_Utils_Blueprints_BlueprintRuleUtil::executeActiveBlueprintRules() does not exist on this mock object

The test method that is failing is:

public function testExecuteActiveBlueprintRulesShouldExecuteDefaultOutsourceCostRule()
{
    Strategy::fake();

    Strategy::create(['id' => 1]);
    $createdStrategy = Strategy::getCreatedModel();

    /**
     * We can use a partial mock for BlueprintRuleUtil so we can mock specific methods
     * later on using shouldReceive while still being able to call regular methods on the class
     * including the one we are testing in this test case.
     */
    $blueprint_rule_util_partial_mock = \Mockery::mock(App\Utils\Blueprints\BlueprintRuleUtil::class)->makePartial();

    /**
     * For method chaining with the DB facade
     * we want to use mockery to mock each chained method
     * and use andReturnSelf() to return an instance of the
     * returned value until we reach the last method call in the chain.
     *
     * Then we can return the final result that we should be expecting
     * which is likely a stdClass object as a query result.
     */
    $active_blueprint_rule = new stdClass();
    $active_blueprint_rule->id = 1001;

    DB::shouldReceive("table")
        ->with('blueprint_rules')
        ->once()->andReturnSelf();

    DB::shouldReceive("where")
        ->with('is_active', true)
        ->andReturnSelf();

    DB::shouldReceive("get")
        ->andReturn([$active_blueprint_rule]);

    $blueprint_rule_util_partial_mock->shouldReceive('addDefaultOutsourceCostToStrategy')
        ->withAnyArgs();
    $blueprint_rule_util_partial_mock->shouldReceive('shouldAddDefaultOutsourceCost')->withAnyArgs()->andReturn(true);

    $blueprint_rule_util_partial_mock->executeActiveBlueprintRules($createdStrategy);

    Strategy::stopFaking();
}

Here is the full test class I am using:

namespace Tests\Unit;

/**
 * Need to use built in laravel testcase instead of PHPUnit testcase to have access to instance variables like app for mocking
 */

use Tests\TestCase;
use App\Strategy;
use App\Pillar;
use App\Utils\Blueprints\BlueprintRuleUtil;
use DB;
use stdClass;

class BlueprintRuleUtilTest extends TestCase
{
    /**
     * Test to make sure outsource cost will not be added
     * with a certain blueprint type and pillars.
     */
    public function testShouldAddDefaultSnowflakeOutsourceCostWillReturnFalse()
    {
        Strategy::fake();
        Pillar::fake();

        Strategy::create(['id' => 1]);

        // test core business first
        Pillar::create(['id' => 1, 'slug' => 'core-new-business']);

        $createdStrategy = Strategy::getCreatedModel();
        // set the pillar to be the created model so it can grab it's pillar property later on using a relation
        $createdStrategy->pillar = Pillar::getCreatedModel();

        $blueprint_rule_util = new BlueprintRuleUtil();

        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        // test service expansion by updating the pillar
        $createdStrategy->pillar->slug = 'service-expansion';
        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        // test with blueprint type set to project and valid pillar slug
        $createdStrategy->pillar->slug = 'resign';
        $createdStrategy->type = 'project';
        $this->assertFalse($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        Strategy::stopFaking();
        Pillar::stopFaking();
    }

    /**
     * Test given a valid slug and project type that the
     * Snowflake default outsource cost is added
     */
    public function testShouldAddDefaultSnowflakeOutsourceCostWillReturnTrue()
    {
        Strategy::fake();
        Pillar::fake();

        Strategy::create(['id' => 1]);

        $blueprint_rule_util = new BlueprintRuleUtil();

        // test resign which is a valid pillar
        Pillar::create(['id' => 1, 'slug' => 'resign']);

        $createdStrategy = Strategy::getCreatedModel();
        // test with valid type retainer
        $createdStrategy->type = 'retainer';
        // set the pillar to be the created model so it can grab it's pillar property later on using a relation
        $createdStrategy->pillar = Pillar::getCreatedModel();
        $this->assertTrue($blueprint_rule_util->shouldAddDefaultOutsourceCost($createdStrategy));

        Strategy::stopFaking();
        Pillar::stopFaking();
    }

    public function testExecuteActiveBlueprintRulesShouldExecuteDefaultOutsourceCostRule()
    {
        Strategy::fake();

        Strategy::create(['id' => 1]);
        $createdStrategy = Strategy::getCreatedModel();

        /**
         * We can use a partial mock for BlueprintRuleUtil so we can mock specific methods
         * later on using shouldReceive while still being able to call regular methods on the class
         * including the one we are testing in this test case.
         */
        $blueprint_rule_util_partial_mock = \Mockery::mock(App\Utils\Blueprints\BlueprintRuleUtil::class)->makePartial();

        /**
         * For method chaining with the DB facade
         * we want to use mockery to mock each chained method
         * and use andReturnSelf() to return an instance of the
         * returned value until we reach the last method call in the chain.
         *
         * Then we can return the final result that we should be expecting
         * which is likely a stdClass object as a query result.
         */
        $active_blueprint_rule = new stdClass();
        $active_blueprint_rule->id = 1001;

        DB::shouldReceive("table")
            ->with('blueprint_rules')
            ->once()->andReturnSelf();

        DB::shouldReceive("where")
            ->with('is_active', true)
            ->andReturnSelf();

        DB::shouldReceive("get")
            ->andReturn([$active_blueprint_rule]);

        $blueprint_rule_util_partial_mock->shouldReceive('addDefaultOutsourceCostToStrategy')
            ->withAnyArgs();
        $blueprint_rule_util_partial_mock->shouldReceive('shouldAddDefaultOutsourceCost')->withAnyArgs()->andReturn(true);

        $blueprint_rule_util_partial_mock->executeActiveBlueprintRules($createdStrategy);

        Strategy::stopFaking();
    }
}

Here is the class I am testing against:

namespace App\Utils\Blueprints;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Strategy;
use App\StrategyCost;

class BlueprintRuleUtil
{
    const DEFAULT_OUTSOURCE_COST_RULE_ID = 1001;

    /**
     * Iterate through the active blueprint rules and execute them based on their name
     *
     * @param Strategy $strategy
     *
     */
    public function executeActiveBlueprintRules(Strategy $strategy)
    {
        if (!is_null($strategy)) {
            $active_blueprint_rules = DB::table('blueprint_rules')
                ->where('is_active', true)
                ->get();

            foreach ($active_blueprint_rules as $active_blueprint_rule) {
                if (!is_null($active_blueprint_rule) && $active_blueprint_rule->id === self::DEFAULT_OUTSOURCE_COST_RULE_ID) {
                    BlueprintRuleUtil::addDefaultOutsourceCostToStrategy($strategy, $active_blueprint_rule);
                }
            }
        }
    }

    /**
     * Given a strategy (blueprint)
     *
     * Return true if we should add the default outsource cost to it
     * false if not based on the blueprint type and pillar
     *
     * @param Strategy $strategy
     *
     * @return bool
     */
    public function shouldAddDefaultOutsourceCost(Strategy $strategy)
    {
        $pillar_slugs_to_exclude_for_outsource_costs = [
            'core-new-business',
            'service-expansion'
        ];
        if (
            in_array($strategy->pillar->slug, $pillar_slugs_to_exclude_for_outsource_costs)
            || $strategy->type === 'project'
        ) {
            return false;
        }
        return true;
    }

    /**
     * Create a StrategyCost entry in the db for the provided strategy
     * using the amount from the active blueprint rule to add the default outsource cost.
     *
     * @param Strategy $strategy
     * @param object $active_blueprint_rule
     */
    public function addDefaultOutsourceCostToStrategy(Strategy $strategy, object $active_blueprint_rule)
    {
        if (self::shouldAddDefaultOutsourceCost($strategy)) {
            $department_slug = 'data-intelligence';
            $department = DB::table('departments')
                ->where('slug', $department_slug)
                ->first();

            if (!is_null($department)) {
                $strategy_cost = new StrategyCost;
                $strategy_cost->name = 'Snowflake';
                $strategy_cost->department_id = $department->id;
                $strategy_cost->strategy_id = $strategy->id;
                // set first month to outsource cost
                $strategy_cost->month_1 = $active_blueprint_rule->amount;
                $strategy_cost->save();
                $strategy_cost->strategy->recalculate();
            } else {
                Log::debug("BlueprintRuleUtil: department $department_slug not found, did not add default outsource cost");
            }
        }
    }
}

I have tried using the full class name path with the namespace as the argument when creating the partial mock. I thought that might fix it because it may not be loading the right object. However that didn't work.

The method name is in the class that I am mocking. I'm not sure why I continue to get this error.


问:
Question about bitmasks and how i can extract 7 bits from a 16bit sequence in C
i came across bitmasks to a code that i am making , but since i am a newbie and its the first time practising with bitmasks i want to understand them better.

So i have an example, that i want to get the first 7 bits of a 16 bit number that is unsigned short int type ,store them into a new integer and print them in decimal. I have tried the code below but i get random results. I would appreciate any help.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main(int argc, char *argv[]) {
unsigned short int num,mask1=127,final1;

scanf("%hx",&num);
printf("%hx\n",num);

final1=num&(mask1>>9);

printf("Final is %hu\n",final1);

    return 0;
}
</code>```

So for example when i put a random hex value like 0x3f23
the bit sequnce is 0011111100100011 . So i want to get the 7 first bits extracted which is my case is 0011111 . My initial thought was to use bit shift to the right to move the first 7 bits to the end of the sequence like this (which means 9 bits to the right)  0000000000011111 but since i am a newbie i have trouble getting a proper result from the above thought

Body:
i came across bitmasks to a code that i am making , but since i am a newbie and its the first time practising with bitmasks i want to understand them better.

So i have an example, that i want to get the first 7 bits of a 16 bit number that is unsigned short int type ,store them into a new integer and print them in decimal. I have tried the code below but i get random results. I would appreciate any help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main(int argc, char *argv[]) {
unsigned short int num,mask1=127,final1;

scanf("%hx",&num);
printf("%hx\n",num);

final1=num&(mask1>>9);

printf("Final is %hu\n",final1);

    return 0;
}

So for example when i put a random hex value like 0x3f23
the bit sequnce is 0011111100100011 . So i want to get the 7 first bits extracted which is my case is 0011111 . My initial thought was to use bit shift to the right to move the first 7 bits to the end of the sequence like this (which means 9 bits to the right)  0000000000011111 but since i am a newbie i have trouble getting a proper result from the above thought


问:
GitHub Action Error : Process completed with exit code 1

Workflow file for this run

.github/workflows/profile-3d.yml

```<code>name: GitHub-Profile-3D-Contrib

on:
  schedule: # 03:00 JST == 18:00 UTC
    - cron: "0 0/3 * * *"
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    name: generate-github-profile-3d-contrib
    steps:
      - uses: actions/checkout@v2
      - uses: yoshi389111/github-profile-3d-contrib@0.7.0
        env:
          GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
          USERNAME: ${{ github.repository_owner }}
      - name: Commit & Push
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git add -A .
          git commit -m "generated"
          git push
</code>```

Got Error when I create a yml of the file.

Error Like this -

Run git config user.name github-actions
On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean
Error: Process completed with exit code 1.

Just Wanna to add this kind of graph in my profile README file

https://github.com/yoshi389111/github-profile-3d-contrib

Body:
Workflow file for this run

.github/workflows/profile-3d.yml

name: GitHub-Profile-3D-Contrib

on:
  schedule: # 03:00 JST == 18:00 UTC
    - cron: "0 0/3 * * *"
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    name: generate-github-profile-3d-contrib
    steps:
      - uses: actions/checkout@v2
      - uses: yoshi389111/github-profile-3d-contrib@0.7.0
        env:
          GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
          USERNAME: ${{ github.repository_owner }}
      - name: Commit & Push
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git add -A .
          git commit -m "generated"
          git push

Got Error when I create a yml of the file.

Error Like this -

Run git config user.name github-actions
On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean
Error: Process completed with exit code 1.

Just Wanna to add this kind of graph in my profile README file

https://github.com/yoshi389111/github-profile-3d-contrib


问:
Flutter just_audio seek issue when target is "Designed for iPad"
I am trying to enable "Designed for iPad" as a target for my functioning Flutter based iOS app.  My understanding is that the app runs the iPad version in a VM when the user is on an M1 (or Apple Silicon) mac.

The app uses just_audio, all features work fine and I can load a file and play (I am using a StreamAudioSource derived from an encrypted file downloaded on disk).  When I try to seek in the file I get this error from the iOS side and the audio does not seek but continues playing from where it was (I see a buffering and ready state).

```<code>AQMEIO_HAL.cpp:736   kAudioDevicePropertyMute returned err 2003332927
</code>```

There is very little info on this error apart from this pretty old Apple developer post

https://developer.apple.com/forums/thread/672311

If I play a file as a stream (encrypted HLS) then seek works exactly as expected.

Has anyone had any experience with just_audio targeted this way?

Thanks!

Body:
I am trying to enable "Designed for iPad" as a target for my functioning Flutter based iOS app.  My understanding is that the app runs the iPad version in a VM when the user is on an M1 (or Apple Silicon) mac.

The app uses just_audio, all features work fine and I can load a file and play (I am using a StreamAudioSource derived from an encrypted file downloaded on disk).  When I try to seek in the file I get this error from the iOS side and the audio does not seek but continues playing from where it was (I see a buffering and ready state).

AQMEIO_HAL.cpp:736   kAudioDevicePropertyMute returned err 2003332927

There is very little info on this error apart from this pretty old Apple developer post

https://developer.apple.com/forums/thread/672311

If I play a file as a stream (encrypted HLS) then seek works exactly as expected.

Has anyone had any experience with just_audio targeted this way?

Thanks!


问:
Swagger Docs multipart/form-data array format (NestJs)
I've the following dto:

```<code>export class CreatePersonDto {
  @IsString()
  @ApiProperty({
    description: 'Person name',
    example: 'Jhon Doe',
  })
  readonly name: string;

  @ValidateIf((object, value) => value)
  @IsString({ each: true })
  @ApiProperty({
    description: 'Clothes ids',
    isArray: true,
    type: String,
  })
  readonly clothes: string[];
}
</code>```

This is the cURL generated by Swagger Ui:
(Unable to parse this in NestJs to a string array)

```<code>curl -X 'POST' \
  'http://localhost:3000/person' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'name=Jhon Doe' \
  -F 'clothes=id1,id2'
</code>```

(Clothes are sent as a string)

The array form in the UI looks like this:

This is the expected cURL (Generated by postman, or manually):
(Nestjs automatically parse this to an array)

```<code>curl -X 'POST' \
  'http://localhost:3000/person' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'name=Jhon Doe' \
  -F 'clothes[0]=id1' \
  -F 'clothes[1]=id2'
</code>```

(Clothes are correctly send as an array)

How can i solve this problem with swagger?

Body:
I've the following dto:

export class CreatePersonDto {
  @IsString()
  @ApiProperty({
    description: 'Person name',
    example: 'Jhon Doe',
  })
  readonly name: string;

  @ValidateIf((object, value) => value)
  @IsString({ each: true })
  @ApiProperty({
    description: 'Clothes ids',
    isArray: true,
    type: String,
  })
  readonly clothes: string[];
}

This is the cURL generated by Swagger Ui:
(Unable to parse this in NestJs to a string array)

curl -X 'POST' \
  'http://localhost:3000/person' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'name=Jhon Doe' \
  -F 'clothes=id1,id2'

(Clothes are sent as a string)

The array form in the UI looks like this:

This is the expected cURL (Generated by postman, or manually):
(Nestjs automatically parse this to an array)

curl -X 'POST' \
  'http://localhost:3000/person' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'name=Jhon Doe' \
  -F 'clothes[0]=id1' \
  -F 'clothes[1]=id2'

(Clothes are correctly send as an array)

How can i solve this problem with swagger?


问:
Cannot initialize a third PWM function on Seeeduino XIAO using Circuit Python
I have a Seeed Studio XIAO SAMD21(Seeeduino XIAO) - Arduino Microcontroller.  I want to have three pins put out a frequency using PWM.  I am trying to use the below code.  If I comment out one of DOut2, Dout3, or Dout4; the code runs and the two pins output the correct signal.  However, when I have all three DOuts, I get the following error: RuntimeError: All timers in use.  Any advice is appreciated.

```<code>#Seeeduino XIAO Program (to run on microcontroller)
import supervisor
import time
import board
import digitalio
import pwmio
import analogio

if __name__ == "__main__":
    frequency = 25
    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
</code>```
```<code>    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    #DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
</code>```

Works

```<code>    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    #DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
</code>```

Works

```<code>    #DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
</code>```

Works

```<code>    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
</code>```

Gives 'RuntimeError: All timers in use'

Body:
I have a Seeed Studio XIAO SAMD21(Seeeduino XIAO) - Arduino Microcontroller.  I want to have three pins put out a frequency using PWM.  I am trying to use the below code.  If I comment out one of DOut2, Dout3, or Dout4; the code runs and the two pins output the correct signal.  However, when I have all three DOuts, I get the following error: RuntimeError: All timers in use.  Any advice is appreciated.

#Seeeduino XIAO Program (to run on microcontroller)
import supervisor
import time
import board
import digitalio
import pwmio
import analogio

if __name__ == "__main__":
    frequency = 25
    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)

    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    #DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)

Works

    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    #DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)

Works

    #DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)

Works

    DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
    DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)

Gives 'RuntimeError: All timers in use'


问:
How can I show code while documenting an API using Flasgger
I'm documenting an API and I'd like to show some code examples in order to show how does my api works, I'm using Flasgger and I didn't find any information about this topic, I read from x-codeSamples doc to show pieces of code by writing something like this but it's not working for me

```<code>  x-code-samples:
        lang: JavaScript
        source: console.log('Hello World');
</code>```

so, how can I show pieces of code using flasgger?

Body:
I'm documenting an API and I'd like to show some code examples in order to show how does my api works, I'm using Flasgger and I didn't find any information about this topic, I read from x-codeSamples doc to show pieces of code by writing something like this but it's not working for me

  x-code-samples:
        lang: JavaScript
        source: console.log('Hello World');

so, how can I show pieces of code using flasgger?


问:
Why is my Selenium move_to_element function 100x slower when running on a minimized or background browser?
I'm scraping some surf forecast data, and when I run the scrape with the window maximized it's very fast. But when I run it on a minimized window it takes several hundred times longer.

Below is a quick and dirty example that demos the problem.

```<code>import time
import undetected_chromedriver as uc
from selenium.webdriver.common.action_chains import ActionChains

class SurfScraper:
    def __init__(self, maxOrMin):
        # CSS Targeters ------------------------------------------
        self._windColumnCSS = ".quiver-forecast-graphs__wind__day .quiver-graph-container__column"
        # Setting up Selenium
        self._driver = uc.Chrome()
        if maxOrMin == "max":
            self._driver.maximize_window()
        else:
            self._driver.minimize_window()
        self._action = ActionChains(self._driver)
        self._action.w3c_actions.pointer_action._duration = 10

    def ScrapePage(self, url):
        self._driver.get(url)
        time.sleep(5)
        listOfColumns = self._driver.find_elements("css selector", self._windColumnCSS)
        listOfColumns = listOfColumns[0:1]
        for column in listOfColumns:
            self._action.move_to_element(column)
            start_time = time.time()
            self._action.perform()
            print("Took "+str(time.time() - start_time)+" seconds to move the mouse")
            self._action.reset_actions()
        self._driver.close()

if __name__ == "__main__":
    # Run with window open
    forecastInfo = SurfScraper("max")
    print("Scraping maximized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    listOfNewForecastDicts = forecastInfo.ScrapePage("https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    print("-----------------------------------------")
    # Run with window minimized
    forecastInfo = SurfScraper("min")
    print("Scraping minimized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    listOfNewForecastDicts = forecastInfo.ScrapePage("https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
</code>```

Output:

```<code>Scraping, maximized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013
Took 0.06020545959472656 seconds to move the mouse
Scraping, minimized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013
Took 5.1093339920043945 seconds to move the mouse
</code>```

As you can see I fiddled with the movement duration on the Selenium action, and that improved the speed of the maximized run but had no effect on the minimized run.

I took a look at my CPU usage and it's much higher when the window is maximized so it could be that the computer is throttling the process when it doesn't have focus.

Body:
I'm scraping some surf forecast data, and when I run the scrape with the window maximized it's very fast. But when I run it on a minimized window it takes several hundred times longer.

Below is a quick and dirty example that demos the problem.

import time
import undetected_chromedriver as uc
from selenium.webdriver.common.action_chains import ActionChains

class SurfScraper:
    def __init__(self, maxOrMin):
        # CSS Targeters ------------------------------------------
        self._windColumnCSS = ".quiver-forecast-graphs__wind__day .quiver-graph-container__column"
        # Setting up Selenium
        self._driver = uc.Chrome()
        if maxOrMin == "max":
            self._driver.maximize_window()
        else:
            self._driver.minimize_window()
        self._action = ActionChains(self._driver)
        self._action.w3c_actions.pointer_action._duration = 10

    def ScrapePage(self, url):
        self._driver.get(url)
        time.sleep(5)
        listOfColumns = self._driver.find_elements("css selector", self._windColumnCSS)
        listOfColumns = listOfColumns[0:1]
        for column in listOfColumns:
            self._action.move_to_element(column)
            start_time = time.time()
            self._action.perform()
            print("Took "+str(time.time() - start_time)+" seconds to move the mouse")
            self._action.reset_actions()
        self._driver.close()

if __name__ == "__main__":
    # Run with window open
    forecastInfo = SurfScraper("max")
    print("Scraping maximized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    listOfNewForecastDicts = forecastInfo.ScrapePage("https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    print("-----------------------------------------")
    # Run with window minimized
    forecastInfo = SurfScraper("min")
    print("Scraping minimized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")
    listOfNewForecastDicts = forecastInfo.ScrapePage("https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013")

Output:

Scraping, maximized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013
Took 0.06020545959472656 seconds to move the mouse
Scraping, minimized: https://www.surfline.com/surf-forecasts/big-sur/58581a836630e24c44879013
Took 5.1093339920043945 seconds to move the mouse

As you can see I fiddled with the movement duration on the Selenium action, and that improved the speed of the maximized run but had no effect on the minimized run.

I took a look at my CPU usage and it's much higher when the window is maximized so it could be that the computer is throttling the process when it doesn't have focus.