问:
Add an entry to requirements.txt that has hash values in it
I am accustomed to seeing requirements.txt that has libraries optionally with an associated [minimum] version.

```<code>pandas==1.0.4
</code>```

In an existing project I am now working on instead we have library entries like this:

```<code>argcomplete==1.12.3 \
    --hash=sha256:291f0beca7fd49ce285d2f10e4c1c77e9460cf823eef2de54df0c0fec88b0d81 \
    --hash=sha256:2c7dbffd8c045ea534921e63b0be6fe65e88599990d8dc408ac8c542b72a5445
asgiref==3.4.1; python_version >= "3.6" \
    --hash=sha256:ffc141aa908e6f175673e7b1b3b7af4fdb0ecb738fc5c8b88f69f055c2415214 \
    --hash=sha256:4ef1ab46b484e3c706329cedeff284a5d40824200638503f5768edb6de7d58e9
certifi==2021.5.30; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \
    --hash=sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8 \
    --hash=sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee
cffi==1.14.6; python_version >= "3.6" \
    --hash=sha256:22b9c3c320171c108e903d61a3723b51e37aaa8c81255b5e7ce102775bd01e2c \
    --hash=sha256:f0c5d1acbfca6ebdd6b1e3eded8d261affb6ddcf2186205518f1428b8569bb99 \
    --hash=sha256:99f27fefe34c37ba9875f224a8f36e31d744d8083e00f520f133cab79ad5e819 \
    --hash=sha256:55af55e32ae468e9946f741a5d51f9896da6b9bf0bbdd326843fec05c730eb20 \
</code>```

The project does use poetry - which might have been the generator of the file?  How did it generate this file and how can I add my new dependency - which is pytest 7.0.0 ?

答:
First add the library with with Poetry CLI's add command:

poetry add 'pandas==1.0.4'
```
<p>or any other <em>version constraints</em> than <code>==1.0.4</code> that you might want.</p>
<p>Then generate the requirements file with its <em><code>export</code></em> command:</p>
<pre class="lang-none prettyprint-override"><code>poetry export --format requirements.txt --output requirements.txt
</code>```

Body:
I am accustomed to seeing requirements.txt that has libraries optionally with an associated [minimum] version.

pandas==1.0.4

In an existing project I am now working on instead we have library entries like this:

argcomplete==1.12.3 \
    --hash=sha256:291f0beca7fd49ce285d2f10e4c1c77e9460cf823eef2de54df0c0fec88b0d81 \
    --hash=sha256:2c7dbffd8c045ea534921e63b0be6fe65e88599990d8dc408ac8c542b72a5445
asgiref==3.4.1; python_version >= "3.6" \
    --hash=sha256:ffc141aa908e6f175673e7b1b3b7af4fdb0ecb738fc5c8b88f69f055c2415214 \
    --hash=sha256:4ef1ab46b484e3c706329cedeff284a5d40824200638503f5768edb6de7d58e9
certifi==2021.5.30; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \
    --hash=sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8 \
    --hash=sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee
cffi==1.14.6; python_version >= "3.6" \
    --hash=sha256:22b9c3c320171c108e903d61a3723b51e37aaa8c81255b5e7ce102775bd01e2c \
    --hash=sha256:f0c5d1acbfca6ebdd6b1e3eded8d261affb6ddcf2186205518f1428b8569bb99 \
    --hash=sha256:99f27fefe34c37ba9875f224a8f36e31d744d8083e00f520f133cab79ad5e819 \
    --hash=sha256:55af55e32ae468e9946f741a5d51f9896da6b9bf0bbdd326843fec05c730eb20 \

The project does use poetry - which might have been the generator of the file?  How did it generate this file and how can I add my new dependency - which is pytest 7.0.0 ?

Body:
First add the library with with Poetry CLI's add command:

poetry add 'pandas==1.0.4'

or any other version constraints than ==1.0.4 that you might want.

Then generate the requirements file with its export command:

poetry export --format requirements.txt --output requirements.txt


来源: stackexchange

问:
Parsing an array of string to MVC method
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

```<code>$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });
</code>```

and looks alright.
then i try to convert it to JSON

```<code>$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});
</code>```

My controller method looks as following:

```<code>public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)
</code>```

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

```<code>{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}
</code>```

}

答:
You don't need to stringify the json nor do you need to add the dual SelectedQuantities

```<code>$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (var i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        //json = JSON.stringify(json);
        $.post("/Home/QuantitySummaryView/@Model.TopID", json, true);
    });
});
</code>```

However, based on your code you'll only get the number of items checked (all of them equal to "on") You don't have any code to pass the name of the item that was checked, nor do you pass the ones that are not checked. So you might have to change your code anyway to handle name/value pairs.

ContentLicense: CC BY-SA 3.0

Body:
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

and looks alright.
then i try to convert it to JSON

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});

My controller method looks as following:

public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}

}

Body:
You don't need to stringify the json nor do you need to add the dual SelectedQuantities

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (var i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        //json = JSON.stringify(json);
        $.post("/Home/QuantitySummaryView/@Model.TopID", json, true);
    });
});

However, based on your code you'll only get the number of items checked (all of them equal to "on") You don't have any code to pass the name of the item that was checked, nor do you pass the ones that are not checked. So you might have to change your code anyway to handle name/value pairs.


问:
How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion
I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)

Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.

My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.

What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.

I do this as a hobby, am self-taught and am not sure if it’s even possible (or  good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.

Here's the code I'm putting together:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>

<script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "/components/promocodecomponent.cfc?method=validateUserName"
                }
            }
        });
    });
</script>

<div class="row justify-content-center">
    <div class="col-10">
        <form id="signupform" autocomplete="off" method="get" action="">
            <table>
                <tr>
                    <td class="label">
                        <label id="lfirstname" for="firstname">First Name</label>
                    </td>
                    <td class="field">
                        <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="llastname" for="lastname">Last Name</label>
                    </td>
                    <td class="field">
                        <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="lusername" for="username">Username</label>
                    </td>
                    <td class="field">
                        <input id="username" name="username" type="text" value="" maxlength="50">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="field" colspan="2">
                        <input id="signupsubmit" name="signup" type="submit" value="Signup">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>
</code>```

Here's the component code:

```<code>component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return "Username already in use";
    }

}
</code>```

答:
I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet @AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:

validate() - a function that initializes the plugin for a specific form

rules - options that tells the plugin which form fields should be validated and how

remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";

1. Build Sample Form

Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.

JQuery and Validate libraries

```<code>   <!-- modify js paths as needed -->
   <script src="scripts/jquery-3.1.1.js"></script>
   <script src="scripts/jquery.validate.min.js"></script>
</code>```

Javascript initialization (so plugin validates the form)

```<code>    <script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "users.action"
                }
            }
        });
    });
    </script>

</code>```

HTML form (only the fields in code snippet)

```<code>    <form id="signupform" autocomplete="off" method="get" action="">
        <table>
            <tr>
                <td class="label">
                    <label id="lfirstname" for="firstname">First Name</label>
                </td>
                <td class="field">
                    <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="llastname" for="lastname">Last Name</label>
                </td>
                <td class="field">
                    <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lusername" for="username">Username</label>
                </td>
                <td class="field">
                    <input id="username" name="username" type="text" value="" maxlength="50">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lsignupsubmit" for="signupsubmit">Signup</label>
                </td>
                <td class="field" colspan="2">
                    <input id="signupsubmit" name="signup" type="submit" value="Signup">
                </td>
            </tr>
            </table>
    </form>
</code>```

2. Test (Sample Form)

Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit

3. Create Remote URL

The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.

Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.

YourComponentName.cfc

```<code>component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return false;
    }

}
</code>```

4. Test (Remote URL)

To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.

Example url:

```<code>https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john
</code>```

Valid:  UserName=John:

InValid:  UserName=Bob:

5. Fix Remote URL

With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.

For example, if the component location on disk is:

```<code>c:\path\webroot\path\YourComponentName.cfc
</code>```

Use the url:

```<code>/path/YourComponentName.cfc
</code>```

JS Snippet:

```<code>...,
username: {
   ...,
   remote: "/path/YourComponentName.cfc?method=validateUserName"
}
</code>```

6. Test Form (.. are you sensing a theme?)

Test the final form again with both a valid and invalid usernames to confirm it works as expected.

Invalid usernames "Mike" or "Bob" should trigger an error

Valid username "John" should not trigger an error

Next Steps ...

Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...

Replace hard coded test logic in the cfc with a database lookup

Replace default error message "Please fix this field" with a more user friendly message

Change the appearance of valid and invalid fields using CSS

ContentLicense: CC BY-SA 4.0

Body:
I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)

Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.

My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.

What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.

I do this as a hobby, am self-taught and am not sure if it’s even possible (or  good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.

Here's the code I'm putting together:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <form id="signupform" autocomplete="off" method="get" action="">

                        First Name

                        <input id="firstname" name="firstname" type="text" value="" maxlength="100">

                        Last Name

                        <input id="lastname" name="lastname" type="text" value="" maxlength="100">

                        Username

                        <input id="username" name="username" type="text" value="" maxlength="50">

                        <input id="signupsubmit" name="signup" type="submit" value="Signup">

        </form>

Here's the component code:

component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return "Username already in use";
    }

}

Body:
I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet @AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:

validate() - a function that initializes the plugin for a specific form

rules - options that tells the plugin which form fields should be validated and how

remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";

1. Build Sample Form

Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.

JQuery and Validate libraries

   <!-- modify js paths as needed -->
   <script src="scripts/jquery-3.1.1.js"></script>
   <script src="scripts/jquery.validate.min.js"></script>

Javascript initialization (so plugin validates the form)

    <script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "users.action"
                }
            }
        });
    });
    </script>

HTML form (only the fields in code snippet)

    <form id="signupform" autocomplete="off" method="get" action="">
        <table>
            <tr>
                <td class="label">
                    <label id="lfirstname" for="firstname">First Name</label>
                </td>
                <td class="field">
                    <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="llastname" for="lastname">Last Name</label>
                </td>
                <td class="field">
                    <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lusername" for="username">Username</label>
                </td>
                <td class="field">
                    <input id="username" name="username" type="text" value="" maxlength="50">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lsignupsubmit" for="signupsubmit">Signup</label>
                </td>
                <td class="field" colspan="2">
                    <input id="signupsubmit" name="signup" type="submit" value="Signup">
                </td>
            </tr>
            </table>
    </form>

2. Test (Sample Form)

Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit

3. Create Remote URL

The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.

Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.

YourComponentName.cfc

component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return false;
    }

}

4. Test (Remote URL)

To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.

Example url:

https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john

Valid:  UserName=John:

InValid:  UserName=Bob:

5. Fix Remote URL

With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.

For example, if the component location on disk is:

c:\path\webroot\path\YourComponentName.cfc

Use the url:

/path/YourComponentName.cfc

JS Snippet:

...,
username: {
   ...,
   remote: "/path/YourComponentName.cfc?method=validateUserName"
}

6. Test Form (.. are you sensing a theme?)

Test the final form again with both a valid and invalid usernames to confirm it works as expected.

Invalid usernames "Mike" or "Bob" should trigger an error

Valid username "John" should not trigger an error

Next Steps ...

Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...

Replace hard coded test logic in the cfc with a database lookup

Replace default error message "Please fix this field" with a more user friendly message

Change the appearance of valid and invalid fields using CSS


问:
Create transition effect over psuedo element in css
I am trying to create a manila folder like set of tabs in HTMl. I have achieved the desired look by using psuedo elements. My only issue is, when the user hovers their cursor over the actual "tab" element I want a color to come in from the right to show them that they are hovering over something clickable. My only problem with this approach is my lack of knowledge of psuedo elements.

I have a linear gradient as the background image, and have upped the background-size to only show one half of the linear gradient. As the user hover, the hover css changes the background position to the other color. This effect looks weird with my psuedo element, as it has to have its own rules. How can I achieve the desired effect in one fluid on and off animation??

Here is my code:

const $allTabs = document.body.querySelectorAll('.tab');

for (let i = 0; i < $allTabs.length; i += 1) {
  const $tab = $allTabs[i];

  $tab.style.zIndex = $allTabs.length - i;

  $tab.addEventListener('click', () => {
   removeActive();
    $tab.classList.toggle('active')
  })
}

function removeActive() {
  const arrOfTabs = Array.from($allTabs);

   const $activeTab = arrOfTabs.find(tab => tab.classList.contains('active'));
  $activeTab.classList.toggle('active');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation-tab {
    display: flex;
    height: 50px;
    width: 100%;
    justify-content: space-around;
    align-items: center;
    overflow: hidden;
    padding-top: 10px;
    background-color: white;
}

.tab.active {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab.active::before {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}
.tab.active::after {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab {
    height: 100%;
    width: 100%;
    display: grid;
    place-items: center;
    background-color: white;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 220%;
    position: relative;
    z-index: 0;
    cursor: pointer;
    filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 0.5));
    transition: all 0.2s;
    transition-delay: 0.2s;
}

.tab:not(.active):hover {
    background-position: 100%;
    color: white;
    font-weight: bold;
}

.tab::before {
    width: 30px;
    height: 100%;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    left: -20px;
    top: 0px;
    -webkit-transform: skewX(-20deg);
    transform: skewX(-20deg);
    z-index: -1;
    transition: all 0.2s;
    transition-delay: 0.4s;
}

.tab:not(.active):hover::before {
    background-position: 100%;
}

.tab::after {
    height: 100%;
    width: 30px;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    right: -20px;
    top: 0px;
    -webkit-transform: skewX(20deg);
    transform: skewX(20deg);
    z-index: -1;
    transition: all 0.2s;
}

.tab:not(.active):hover::after {
    background-position: 100%;
}</code>```

Overview

New buys

Budget

Renewals

Procs

Work for me

```

答:
The problem is the size of your psuedo element.

First, you only need the ::after pseudo element to achieve this effect. You can remove the gradient backgrounds on the ::before pseudo element and the main element. Next, set the size of that ::after pseudo element so it can actually cover the whole tab. I used a width of 110%. The result will be that the after pseudo element will come in from the right and make it all the way to the left side

Note: this is a lot of code and I don't understand all of it, so I left as much as I could untouched and just removed some of the hover style rules and edited the ::after:hover style rule. I will leave it to you to cut whatever else need to be cut.

Note #2. You have done some messy z-index stuff on the first tab. This meant the text rendered under the ::after element. I have removed the messy z-indexing.

const $allTabs = document.body.querySelectorAll('.tab');

for (let i = 0; i < $allTabs.length; i += 1) {
  const $tab = $allTabs[i];

  $tab.style.zIndex = $allTabs.length - i;

  $tab.addEventListener('click', () => {
   removeActive();
    $tab.classList.toggle('active')
  })
}

function removeActive() {
  const arrOfTabs = Array.from($allTabs);

   const $activeTab = arrOfTabs.find(tab => tab.classList.contains('active'));
  $activeTab.classList.toggle('active');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation-tab {
    display: flex;
    height: 50px;
    width: 100%;
    justify-content: space-around;
    align-items: center;
    overflow: hidden;
    padding-top: 10px;
    background-color: white;
}

.tab.active {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab.active::before {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}
.tab.active::after {
    background-color: #f8f8f8;
    background-image: none;
}

.tab {
    height: 100%;
    width: 100%;
    display: grid;
    place-items: center;
    background-color: white;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 220%;
    position: relative;
    z-index: 0;
    cursor: pointer;
    filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 0.5));
    transition: all 0.2s;
    transition-delay: 0.2s;
}

.tab:not(.active):hover {
    background-position: 100%;
    color: white;
    font-weight: bold;
}

.tab::before {
    width: 30px;
    height: 100%;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    left: -20px;
    top: 0px;
    -webkit-transform: skewX(-20deg);
    transform: skewX(-20deg);
    z-index: -1;
    transition: all 0.2s;
    transition-delay: 0.4s;
}

.tab::after {
    height: 100%;
    width: 30px;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    right: -20px;
    top: 0px;
    -webkit-transform: skewX(20deg);
    transform: skewX(20deg);
    z-index: -1;
    transition: all 0.2s;
    width: 110%;
}

.tab:not(.active):hover::after {
    background-position: 100%;
}</code>```

Overview

New buys

Budget

Renewals

Procs

Work for me

```

Body:
I am trying to create a manila folder like set of tabs in HTMl. I have achieved the desired look by using psuedo elements. My only issue is, when the user hovers their cursor over the actual "tab" element I want a color to come in from the right to show them that they are hovering over something clickable. My only problem with this approach is my lack of knowledge of psuedo elements.

I have a linear gradient as the background image, and have upped the background-size to only show one half of the linear gradient. As the user hover, the hover css changes the background position to the other color. This effect looks weird with my psuedo element, as it has to have its own rules. How can I achieve the desired effect in one fluid on and off animation??

Here is my code:

const $allTabs = document.body.querySelectorAll('.tab');

for (let i = 0; i < $allTabs.length; i += 1) {
  const $tab = $allTabs[i];

  $tab.style.zIndex = $allTabs.length - i;

  $tab.addEventListener('click', () => {
   removeActive();
    $tab.classList.toggle('active')
  })
}

function removeActive() {
  const arrOfTabs = Array.from($allTabs);

   const $activeTab = arrOfTabs.find(tab => tab.classList.contains('active'));
  $activeTab.classList.toggle('active');
}

.navigation-tab {
    display: flex;
    height: 50px;
    width: 100%;
    justify-content: space-around;
    align-items: center;
    overflow: hidden;
    padding-top: 10px;
    background-color: white;
}

.tab.active {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab.active::before {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}
.tab.active::after {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab {
    height: 100%;
    width: 100%;
    display: grid;
    place-items: center;
    background-color: white;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 220%;
    position: relative;
    z-index: 0;
    cursor: pointer;
    filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 0.5));
    transition: all 0.2s;
    transition-delay: 0.2s;
}

.tab:not(.active):hover {
    background-position: 100%;
    color: white;
    font-weight: bold;
}

.tab::before {
    width: 30px;
    height: 100%;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    left: -20px;
    top: 0px;
    -webkit-transform: skewX(-20deg);
    transform: skewX(-20deg);
    z-index: -1;
    transition: all 0.2s;
    transition-delay: 0.4s;
}

.tab:not(.active):hover::before {
    background-position: 100%;
}

.tab::after {
    height: 100%;
    width: 30px;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    right: -20px;
    top: 0px;
    -webkit-transform: skewX(20deg);
    transform: skewX(20deg);
    z-index: -1;
    transition: all 0.2s;
}

.tab:not(.active):hover::after {
    background-position: 100%;
}

Overview

New buys

Budget

Renewals

Procs

Work for me

Body:
The problem is the size of your psuedo element.

First, you only need the ::after pseudo element to achieve this effect. You can remove the gradient backgrounds on the ::before pseudo element and the main element. Next, set the size of that ::after pseudo element so it can actually cover the whole tab. I used a width of 110%. The result will be that the after pseudo element will come in from the right and make it all the way to the left side

Note: this is a lot of code and I don't understand all of it, so I left as much as I could untouched and just removed some of the hover style rules and edited the ::after:hover style rule. I will leave it to you to cut whatever else need to be cut.

Note #2. You have done some messy z-index stuff on the first tab. This meant the text rendered under the ::after element. I have removed the messy z-indexing.

const $allTabs = document.body.querySelectorAll('.tab');

for (let i = 0; i < $allTabs.length; i += 1) {
  const $tab = $allTabs[i];

  $tab.style.zIndex = $allTabs.length - i;

  $tab.addEventListener('click', () => {
   removeActive();
    $tab.classList.toggle('active')
  })
}

function removeActive() {
  const arrOfTabs = Array.from($allTabs);

   const $activeTab = arrOfTabs.find(tab => tab.classList.contains('active'));
  $activeTab.classList.toggle('active');
}

.navigation-tab {
    display: flex;
    height: 50px;
    width: 100%;
    justify-content: space-around;
    align-items: center;
    overflow: hidden;
    padding-top: 10px;
    background-color: white;
}

.tab.active {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}

.tab.active::before {
    background-color: #f8f8f8;
    z-index: 90 !important;
    background-image: none;
}
.tab.active::after {
    background-color: #f8f8f8;
    background-image: none;
}

.tab {
    height: 100%;
    width: 100%;
    display: grid;
    place-items: center;
    background-color: white;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 220%;
    position: relative;
    z-index: 0;
    cursor: pointer;
    filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 0.5));
    transition: all 0.2s;
    transition-delay: 0.2s;
}

.tab:not(.active):hover {
    background-position: 100%;
    color: white;
    font-weight: bold;
}

.tab::before {
    width: 30px;
    height: 100%;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    left: -20px;
    top: 0px;
    -webkit-transform: skewX(-20deg);
    transform: skewX(-20deg);
    z-index: -1;
    transition: all 0.2s;
    transition-delay: 0.4s;
}

.tab::after {
    height: 100%;
    width: 30px;
    border-radius: 10px 10px 0px 0px;
    background-image: linear-gradient(120deg, white 0%, white 50%, #005289 50%);
    background-size: 280%;
    content: '';
    position: absolute;
    right: -20px;
    top: 0px;
    -webkit-transform: skewX(20deg);
    transform: skewX(20deg);
    z-index: -1;
    transition: all 0.2s;
    width: 110%;
}

.tab:not(.active):hover::after {
    background-position: 100%;
}

<div class="holder">
  <nav class="navigation-tab">
  <div class="tab active">Overview</div>
  <div class="tab">New buys</div>
  <div class="tab">Budget</div>
  <div class="tab">Renewals</div>
  <div class="tab">Procs</div>
  <div class="tab">Work for me</div>
  </nav>
</div>


问:
How to combine the elements of two lists using zip function in python?
I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop for which I will require parallel iteration.

I therefore attempted the following but the output is as shown below.

```<code>lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

for last, first in zip(lasts, firsts):
    print (last, first, "\n")
</code>```

Output:

```<code>x a
y b
z c
</code>```

Expected Output:

```<code>x a
x b
x c
y a
y b
y c
z a
z b
z c
</code>```

答:
I believe the function you are looking for is itertools.product:

```<code>lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

from itertools import product
for last, first in product(lasts, firsts):
    print (last, first)

x a
x b
x c
y a
y b
y c
z a
z b
z c
</code>```

Another alternative, that also produces an iterator is to use a nested comprehension:

```<code>iPairs=( (l,f) for l in lasts for f in firsts)
for last, first in iPairs:
    print (last, first)
</code>```

Body:
I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop for which I will require parallel iteration.

I therefore attempted the following but the output is as shown below.

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

for last, first in zip(lasts, firsts):
    print (last, first, "\n")

Output:

x a
y b
z c

Expected Output:

x a
x b
x c
y a
y b
y c
z a
z b
z c

Body:
I believe the function you are looking for is itertools.product:

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

from itertools import product
for last, first in product(lasts, firsts):
    print (last, first)

x a
x b
x c
y a
y b
y c
z a
z b
z c

Another alternative, that also produces an iterator is to use a nested comprehension:

iPairs=( (l,f) for l in lasts for f in firsts)
for last, first in iPairs:
    print (last, first)


问:
What replaces the now removed Kotest arrow matcher shouldBeSome function variant?
In prior versions of kotest-assertions-arrow, it was possible to write:

```<code>someOption.shouldBeSome {
  it.foo shouldBe "x"
  it.bar shouldBe "y"
}
</code>```

I just upgraded to v1.2.1 and this variant has been removed. Only the literal value variant remains

```<code>someOption.shouldBeSome(t: T)
</code>```

What replaces the older style?

答:
One possible answer is</p>
```<code>someOption.shouldBeSome().let {
  it.foo shouldBe "x"
  it.bar shouldBe "y"
}
</code>```

Body:
In prior versions of kotest-assertions-arrow, it was possible to write:

someOption.shouldBeSome {
  it.foo shouldBe "x"
  it.bar shouldBe "y"
}

I just upgraded to v1.2.1 and this variant has been removed. Only the literal value variant remains

someOption.shouldBeSome(t: T)

What replaces the older style?

Body:
One possible answer is

someOption.shouldBeSome().let {
  it.foo shouldBe "x"
  it.bar shouldBe "y"
}


问:
how to capture mouseclick in actionscript 3.0
How do I capture the position of a mouseclick from the user in my Flash window using Actionscript 3.0?</p>

答: You may query any DisplayObject's mouseX and mouseY whenever you like.</p>

OwnerDisplayName: yannick

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jedierikb


问:
Issues with threading in c#
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

```<code>private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}
</code>```

I tried threading it out like this:

```<code>System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));
</code>```

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

答:
Answering to your question "What am I doing wrong?" - you trying to pass method with signature which is not supported by ParameterizedThreadStart delegate (see here)

signature should be

```<code> void ParameterizedThreadStart(Object obj)
</code>```

and not the

```<code>void ParameterizedThreadStart(
                    ValueEngineService.Contracts.ValueEngServiceParams param)
</code>```

Title: Issues with threading in c#

Body:
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}

I tried threading it out like this:

System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

Body:
Answering to your question "What am I doing wrong?" - you trying to pass method with signature which is not supported by ParameterizedThreadStart delegate (see here)

signature should be

 void ParameterizedThreadStart(Object obj)

and not the

void ParameterizedThreadStart(
                    ValueEngineService.Contracts.ValueEngServiceParams param)


问:
ReactJS: Child component re-rendering on OnChange event from parent
I have a parent component with two children: Child1 that displays the information and Child2 that changes the information through input. My goal is to keep the Child1 information from re-rendering until a save trigger would be passed from the Child2 to parent meaning the data was saved. For that I've used memo in Child1 to memoize the data and keep it from re-rendering but it won't work as the  child is still re-rendered every time the onChange event is triggered. How can I make Child1 to keep the data unchanged until it is saved? This is what I have so far:

Child1:

```<code>import React,{memo} from 'react'

const UserDetails = ({values,onOpen})=>{

console.log("child1 rendering")
    return(
          <Center>
            <Box d="flex" justifyContent='space-between' w="xs">
              <Heading name="username">{values.username}</Heading>
              <IconButton size="md" icon={<FiPenTool />} onClick={onOpen} />
            </Box>
          </Center>
          <Stack mt={10} direction={['column', 'column']}>
            <Heading fontSize="20px">Location:{values.location}</Heading>

            <Box mt={5} px={20}>
              <Heading fontSize="20px">Description</Heading>
              <Text fontSize="md">{values.description}</Text>
            </Box>
          </Stack>
    )
}

export default memo(UserDetails)
</code>```

Child2:

```<code>      function PopUpDetails({ values, handleDetails })

 {
    console.log("child2 render")
  return (
        <Box>
        <Input name="username" w="md" mt={5} mr={5} fontWeight="bold" textAlign="center"
          value={values.username} onChange={handleDetails} />
        <Input name="location" mt={5} fontWeight="bold" onChange={handleDetails}
          textAlign="center"
          w="md" mr={5}
           onFocus={() => onOpen()} value={values.location} />

        <Input name="description" w="md" h="20vh" mt={5} mr={5} textAlign="center"
        fontWeight="bold" value={values.description} onChange={handleDetails} />

    </Box>
  )

}

export default PopUpDetails
</code>```

Parent:

```<code>const userValues= {
  username: '',
  location:'',
  description:''
}

function User() {
  const { Moralis, user, setUserData, isUserUpdating } = useMoralis()
  const currentUserId = user.id
  const { isOpen, onOpen, onClose } = useDisclosure()
  const params = { "userId": currentUserId }
  const [details, setDetails] = useState(()=>()=>userHook())

 const userHook = useCallback(()=>{ //callback function to retrieve initial values each  time
                                        user closes child2 in case data was not saved
   setDetails({...details,
    username:Moralis.User.current().attributes.username,
    description: Moralis.User.current().attributes.description,
    location: Moralis.User.current().attributes.location,
  })
  },[])

  useEffect(()=>{
    userHook()
  },[])

  const saveDetails = () =>{
    setUserData({
      location: details.location,
      username: details.username,
      description: details.description,
    })
  }

 const handleInputChange = (e) => {
    const { name, value } = e.target
    setDetails({
      ...details,
      [name]: value
    })
  }

return(
  <Container>
   <UserDetails values={details}/>
    <Modal isOpen={isOpen} size="3xl" closeOnOverlayClick isCentered onClose={() => { onClose();userHook()}}>
        <ModalOverlay />
        <ModalContent >
          <ModalHeader>Edit details</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <PopUpDetails values={details} handleDetails={(e) => handleInputChange(e)}/>
          </ModalBody>
          <ModalFooter>
            <Button onClick={() => saveDetails()} variant='ghost'>Save</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
   </Container>
)

export default User
</code>```

Can someone help me undestand why Child1 re-renders every time even if I use memo and how can I cache the data so when handleChange is triggered it will not  reflect on Child1?Any help would be appreciated!

答:
```<code><UserDetails values={details}/>
</code>```

your user details is receiving the state in "values" prop, is the state that you are changing in the modal, so why would you expect to not rerendering?

try get your initial values aside, then set it into default state and pass that througth your   component to remain the same.

function User() {
  const { Moralis, user, setUserData, isUserUpdating } = useMoralis()
  const { isOpen, onOpen, onClose } = useDisclosure()
  const params = { "userId": user.id }
  const initValues = useMemo(() => {
    const {
      username,
      description,
      location
    } = Moralis.User.current().attributes;
    return { username, description, location };
  }, []);
  const [details, setDetails] = useState(initValues)

  ...

    <UserDetails value={initValues}  />

  ...```

Body:
I have a parent component with two children: Child1 that displays the information and Child2 that changes the information through input. My goal is to keep the Child1 information from re-rendering until a save trigger would be passed from the Child2 to parent meaning the data was saved. For that I've used memo in Child1 to memoize the data and keep it from re-rendering but it won't work as the  child is still re-rendered every time the onChange event is triggered. How can I make Child1 to keep the data unchanged until it is saved? This is what I have so far:

Child1:

import React,{memo} from 'react'

const UserDetails = ({values,onOpen})=>{

console.log("child1 rendering")
    return(

            <Box d="flex" justifyContent='space-between' w="xs">
              <Heading name="username">{values.username}</Heading>
              <IconButton size="md" icon={<FiPenTool />} onClick={onOpen} />
            </Box>

          <Stack mt={10} direction={['column', 'column']}>
            <Heading fontSize="20px">Location:{values.location}</Heading>

            <Box mt={5} px={20}>
              <Heading fontSize="20px">Description</Heading>
              <Text fontSize="md">{values.description}</Text>
            </Box>
          </Stack>
    )
}

export default memo(UserDetails)

Child2:

      function PopUpDetails({ values, handleDetails })

 {
    console.log("child2 render")
  return (
        <Box>
        <Input name="username" w="md" mt={5} mr={5} fontWeight="bold" textAlign="center"
          value={values.username} onChange={handleDetails} />
        <Input name="location" mt={5} fontWeight="bold" onChange={handleDetails}
          textAlign="center"
          w="md" mr={5}
           onFocus={() => onOpen()} value={values.location} />

        <Input name="description" w="md" h="20vh" mt={5} mr={5} textAlign="center"
        fontWeight="bold" value={values.description} onChange={handleDetails} />

    </Box>
  )

}

export default PopUpDetails

Parent:

const userValues= {
  username: '',
  location:'',
  description:''
}

function User() {
  const { Moralis, user, setUserData, isUserUpdating } = useMoralis()
  const currentUserId = user.id
  const { isOpen, onOpen, onClose } = useDisclosure()
  const params = { "userId": currentUserId }
  const [details, setDetails] = useState(()=>()=>userHook())

 const userHook = useCallback(()=>{ //callback function to retrieve initial values each  time
                                        user closes child2 in case data was not saved
   setDetails({...details,
    username:Moralis.User.current().attributes.username,
    description: Moralis.User.current().attributes.description,
    location: Moralis.User.current().attributes.location,
  })
  },[])

  useEffect(()=>{
    userHook()
  },[])

  const saveDetails = () =>{
    setUserData({
      location: details.location,
      username: details.username,
      description: details.description,
    })
  }

 const handleInputChange = (e) => {
    const { name, value } = e.target
    setDetails({
      ...details,
      [name]: value
    })
  }

return(
  <Container>
   <UserDetails values={details}/>
    <Modal isOpen={isOpen} size="3xl" closeOnOverlayClick isCentered onClose={() => { onClose();userHook()}}>
        <ModalOverlay />
        <ModalContent >
          <ModalHeader>Edit details</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <PopUpDetails values={details} handleDetails={(e) => handleInputChange(e)}/>
          </ModalBody>
          <ModalFooter>
            <Button onClick={() => saveDetails()} variant='ghost'>Save</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
   </Container>
)

export default User

Can someone help me undestand why Child1 re-renders every time even if I use memo and how can I cache the data so when handleChange is triggered it will not  reflect on Child1?Any help would be appreciated!

Body:
<UserDetails values={details}/>

your user details is receiving the state in "values" prop, is the state that you are changing in the modal, so why would you expect to not rerendering?

try get your initial values aside, then set it into default state and pass that througth your   component to remain the same.

function User() {
  const { Moralis, user, setUserData, isUserUpdating } = useMoralis()
  const { isOpen, onOpen, onClose } = useDisclosure()
  const params = { "userId": user.id }
  const initValues = useMemo(() => {
    const {
      username,
      description,
      location
    } = Moralis.User.current().attributes;
    return { username, description, location };
  }, []);
  const [details, setDetails] = useState(initValues)

  ...

    <UserDetails value={initValues}  />

  ...


问:
Reactjs Module not found: Error: Can't resolve 'fs' in '-/project/reactapp/node_modules/sass'
I'm working on my reactapp on localhost.

I received this error message during the compilation of my app on localhost.
'Module not found: Error: Can't resolve 'fs' in '-/project/reactapp/node_modules/sass'.'

My webpack version is >5.

答:
I succeed to manage this error by opening the package.json file inside of the 'sass' folder that is in 'node_modules' folder that is in the root user folder (and not in the app folder)
for Mac copy paste the following path with your own username file:///Users//node_modules/sass/package.json

and add the following code:

```<code>"browser": {
   "fs": false
}
</code>```

And do the same in the 'node_modules/sass' that is inside of your reactapp folder : /Users/username/projectname/reactappname/node_modules/sass/package.json

And that's it.

Body:
I succeed to manage this error by opening the package.json file inside of the 'sass' folder that is in 'node_modules' folder that is in the root user folder (and not in the app folder)
for Mac copy paste the following path with your own username file:///Users//node_modules/sass/package.json

and add the following code:

"browser": {
   "fs": false
}

And do the same in the 'node_modules/sass' that is inside of your reactapp folder : /Users/username/projectname/reactappname/node_modules/sass/package.json

And that's it.


问:
Parallel processing of large dataframes
I have a large Pandas DataFrame with columns a and b (kind of coordinates in floats) and column c (values), which has to be binned and summarized over a certain interval of steps in the columns a and b. The order of the result is relevant, since a and b simulate coordinates where samples have been taken with the value c. In the next step, the results would be reshaped to an image and processed further.

This can be solved using nested loops (see below), however, it obviously does not scale well with larger datasets or smaller step sizes.

Example:

```<code>import pandas as pd
import time
import numpy as np

a = np.random.random(int(10E7))
b = np.random.random(int(10E7))
c = np.random.random(int(10E7))

df = pd.DataFrame({'a':a, 'b':b, 'values': c})

stepsize = 0.1

means = []

T1 = time.time()
for j in np.arange(0,1,stepsize):
    for i in np.arange(0,1,stepsize):
        selection = df[ (df.a > i) & (df.a <= i+stepsize) &  (df.b > j) & (df.b <= j+stepsize) ]
        means.append(selection['values'].mean())
T2 = time.time()
</code>```

I have been wondering, how this can be resolved using multiprocessing (or multithreading?).
Therefore, I have set up the following code, though I am stuck: I am not sure, if the meanAB code is setup correctly and if the multiprocessing has been initiated correctly.

```<code>stepsize = 0.01 # smaller stepsize
A_vals = list(np.arange(0,1,stepsize))
B_vals = list(np.arange(0,1,stepsize))

def meanByAB(A,B):
    # loaded df and stepsize globally. Does it make sense?!
    selection = df[ (df.a > A) & (df.a <= A+stepsize) &  (df.b > B) & (df.b <= B+stepsize)  ]
    mean = np.mean(selection['values'])

if __name__ == '__main__':
    T1 = time.time()
    p = mp.Process(target=meanByAB,args=(A_values,B_values,) # tried many things here. yields ValueError
    p.start()
    p.join()
    T2 = time.time()

</code>```

答:
This is my solution. The results are not ordered, because I don't understand which is the right sorting to apply. However, each element of the list of results is a tuple composed of: (mean, A, B) where A and B are the values you specify. A posteriori, you can sort the values based on A and B, or by mean if you need it:

import pandas as pd
import numpy as np
# from multiprocessing import Process, Manager, Array, Queue
# import multiprocessing as mp
from threading import Thread
import threading as th
from queue import Queue
import time

def worker(df, q_input, q_output, stepsize):
  while True:
    A = q_input.get()
    if A == 'DONE':
      break
    for i, B in enumerate(np.arange(0,1,stepsize)):
      selection = df[ (df.a > A) & (df.a <= A+stepsize) &  (df.b > B) & (df.b <= B+stepsize)  ]
      mean = np.mean(selection.values)
      q_output.put((mean, A, B))

def dump_queue(queue):
    result = []
    while not queue.empty():
      result.append(queue.get(timeout=0.01))
    return result

if __name__ == '__main__':
  start_time = time.time()
  start_initialization = time.time()
  NUM_THREADS = 4
  a = np.random.random(int(10E7))
  b = np.random.random(int(10E7))
  c = np.random.random(int(10E7))
  df = pd.DataFrame({'a':a, 'b':b, 'values': c})
  stepsize = 0.1
  means = []

  q_input = Queue()
  for j in np.arange(0,1,stepsize):
    q_input.put(j)

  for _ in range(NUM_PROCESSES):
    q_input.put('DONE')

  q_output = Queue()

  print(f"Initialization terminates in {time.time() - start_initialization}")
  processes = [Thread(target=worker, args=(df, q_input, q_output, stepsize), name=f"Worker-{i}") for i in range(NUM_THREADS)]
  for p in processes:
    p.start()

  for p in processes:
    p.join()

  print(f"Finished in  {time.time() - start_time}")
  result = dump_queue(q_output)
  print(result)
  print(len(result))
```

EDIT

The edited version uses multi-threading instead of multiprocessing: multi-threading is lighter than multiprocessing, so I think it should be the best choice in this problem

Title: Parallel processing of large dataframes

Body:
I have a large Pandas DataFrame with columns a and b (kind of coordinates in floats) and column c (values), which has to be binned and summarized over a certain interval of steps in the columns a and b. The order of the result is relevant, since a and b simulate coordinates where samples have been taken with the value c. In the next step, the results would be reshaped to an image and processed further.

This can be solved using nested loops (see below), however, it obviously does not scale well with larger datasets or smaller step sizes.

Example:

import pandas as pd
import time
import numpy as np

a = np.random.random(int(10E7))
b = np.random.random(int(10E7))
c = np.random.random(int(10E7))

df = pd.DataFrame({'a':a, 'b':b, 'values': c})

stepsize = 0.1

means = []

T1 = time.time()
for j in np.arange(0,1,stepsize):
    for i in np.arange(0,1,stepsize):
        selection = df[ (df.a > i) & (df.a <= i+stepsize) &  (df.b > j) & (df.b <= j+stepsize) ]
        means.append(selection['values'].mean())
T2 = time.time()

I have been wondering, how this can be resolved using multiprocessing (or multithreading?).
Therefore, I have set up the following code, though I am stuck: I am not sure, if the meanAB code is setup correctly and if the multiprocessing has been initiated correctly.

stepsize = 0.01 # smaller stepsize
A_vals = list(np.arange(0,1,stepsize))
B_vals = list(np.arange(0,1,stepsize))

def meanByAB(A,B):
    # loaded df and stepsize globally. Does it make sense?!
    selection = df[ (df.a > A) & (df.a <= A+stepsize) &  (df.b > B) & (df.b <= B+stepsize)  ]
    mean = np.mean(selection['values'])

if __name__ == '__main__':
    T1 = time.time()
    p = mp.Process(target=meanByAB,args=(A_values,B_values,) # tried many things here. yields ValueError
    p.start()
    p.join()
    T2 = time.time()

Body:
This is my solution. The results are not ordered, because I don't understand which is the right sorting to apply. However, each element of the list of results is a tuple composed of: (mean, A, B) where A and B are the values you specify. A posteriori, you can sort the values based on A and B, or by mean if you need it:

import pandas as pd
import numpy as np
# from multiprocessing import Process, Manager, Array, Queue
# import multiprocessing as mp
from threading import Thread
import threading as th
from queue import Queue
import time

def worker(df, q_input, q_output, stepsize):
  while True:
    A = q_input.get()
    if A == 'DONE':
      break
    for i, B in enumerate(np.arange(0,1,stepsize)):
      selection = df[ (df.a > A) & (df.a <= A+stepsize) &  (df.b > B) & (df.b <= B+stepsize)  ]
      mean = np.mean(selection.values)
      q_output.put((mean, A, B))

def dump_queue(queue):
    result = []
    while not queue.empty():
      result.append(queue.get(timeout=0.01))
    return result

if __name__ == '__main__':
  start_time = time.time()
  start_initialization = time.time()
  NUM_THREADS = 4
  a = np.random.random(int(10E7))
  b = np.random.random(int(10E7))
  c = np.random.random(int(10E7))
  df = pd.DataFrame({'a':a, 'b':b, 'values': c})
  stepsize = 0.1
  means = []

  q_input = Queue()
  for j in np.arange(0,1,stepsize):
    q_input.put(j)

  for _ in range(NUM_PROCESSES):
    q_input.put('DONE')

  q_output = Queue()

  print(f"Initialization terminates in {time.time() - start_initialization}")
  processes = [Thread(target=worker, args=(df, q_input, q_output, stepsize), name=f"Worker-{i}") for i in range(NUM_THREADS)]
  for p in processes:
    p.start()

  for p in processes:
    p.join()

  print(f"Finished in  {time.time() - start_time}")
  result = dump_queue(q_output)
  print(result)
  print(len(result))

EDIT

The edited version uses multi-threading instead of multiprocessing: multi-threading is lighter than multiprocessing, so I think it should be the best choice in this problem


问:
Redirecting from a HTML button to a new page with JS
This is fairly simple, I'm trying to make the login button work, and redirect to a different file (placeholder.html) if what is in the email and password match the following:

Login: Admin
Password: Password123

I have yet to get the login button to work in the first place to redirect, and id like to keep it as a button element by using, the 'onlick=' with a function in js or an id for now.

Thank you so much for the help :)
Apologies if this is a little sloppy, one of my first times asking for help here haha

Here is what I had so far, which dent work fully:

```<code><!DOCTYPE html>
<html>

  <head>
    <title>Login page</title>
    <link href="style." rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>

  <body>

    <div class="login-page">

      <div name="login" class="form">

        <div class="title login" style="font-size: 25px; font-family: Roboto; padding-bottom: 25px;">
          Login Form
        </div>

        <form class="login-form" action="login.php" method="post">

          <input type="email_" placeholder="email"/>

          <input type="password" placeholder="password"/>

          <button id="login_button">login</button>

          <p class="message" style="font-family: Roboto, sans-serif;">Not registered?
            <a href="register.html">Create an account</a>
          </p>

        </form>

      </div>

    </div>

  </body>

  <script type="text/javascript">

    document.getElementById("login_button").onclick = function () {
        location.href = "#placeholder";
    };

</script>

</html>
</code>```

答:
There are a couple of ways that you could do this, here is a simple example:</p>
```<code><!DOCTYPE html>
<html>

  <head>
    <title>Login page</title>
    <link href="style." rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>

  <body>

    <div class="login-page">

      <div name="login" class="form">

        <div class="title login" style="font-size: 25px; font-family: Roboto; padding-bottom: 25px;">
          Login Form
        </div>

        <form class="login-form" action="login.php" method="post">

          <input type="email_" placeholder="email"/>

          <input type="password" placeholder="password"/>

          <button id="login_button" onclick="login()">login</button>

          <p class="message" style="font-family: Roboto, sans-serif;">Not registered?
            <a href="register.html">Create an account</a>
          </p>

        </form>

      </div>

    </div>

  </body>

  <script type="text/javascript">

    function login() {
      // Login logic here
      if (loginSuccesful) {
        window.location.href = "/placeholder.html";
      }
    }

</script>

</html>
</code>```

Body:
This is fairly simple, I'm trying to make the login button work, and redirect to a different file (placeholder.html) if what is in the email and password match the following:

Login: Admin
Password: Password123

I have yet to get the login button to work in the first place to redirect, and id like to keep it as a button element by using, the 'onlick=' with a function in js or an id for now.

Thank you so much for the help :)
Apologies if this is a little sloppy, one of my first times asking for help here haha

Here is what I had so far, which dent work fully:

<!DOCTYPE html>

    <title>Login page</title>
    <link href="style." rel="stylesheet" type="text/css" />

          Login Form

        <form class="login-form" action="login.php" method="post">

          <input type="email_" placeholder="email"/>

          <input type="password" placeholder="password"/>

          <button id="login_button">login</button>

Not registered?
            Create an account

        </form>

Body:
There are a couple of ways that you could do this, here is a simple example:

<!DOCTYPE html>
<html>

  <head>
    <title>Login page</title>
    <link href="style." rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>

  <body>

    <div class="login-page">

      <div name="login" class="form">

        <div class="title login" style="font-size: 25px; font-family: Roboto; padding-bottom: 25px;">
          Login Form
        </div>

        <form class="login-form" action="login.php" method="post">

          <input type="email_" placeholder="email"/>

          <input type="password" placeholder="password"/>

          <button id="login_button" onclick="login()">login</button>

          <p class="message" style="font-family: Roboto, sans-serif;">Not registered?
            <a href="register.html">Create an account</a>
          </p>

        </form>

      </div>

    </div>

  </body>

  <script type="text/javascript">

    function login() {
      // Login logic here
      if (loginSuccesful) {
        window.location.href = "/placeholder.html";
      }
    }

</script>

</html>


问:
What choice of naming for this kind of units?
[EDIT]

The question was a bit over-explained.

Cumulative

Consumption

Instantaneous

Average

What would you name this kind of units?

The listed options is used to specify how to calculate values in a table.

I.e.

Cumulative = 53 (sum of all)

Consumption = 8 (gap between two values)

Instantaneous = 20 (at asked time)

Average = 13,25 (sum 53/4 values)

The question is only for me to make a clear and understandable naming convention in the system.

答: I'd call them aggregates or reductions of the data. In all cases, you're taking a bunch of data and summarizing it by computing one number. Other words that can be used are measure, statistic and digest.


问:
Invalid initializer in C when creating an array via a function
I want to create an array of type set and have all the nodes set to NULL, hence I used calloc. However, I'm getting an invalid initializer in that one line in main function. Why's that?</p>
```<code>struct set {
    int capacity;
    int size;
    char *array;
};

struct set *create_graph(int nodes)
{
  struct set *graph = calloc(nodes - 1, sizeof(struct set));

  return graph;
}
int main()
{

  struct set* graph[] = create_graph(4);
}
</code>```

答:
this line

```<code> struct set* graph[] = create_graph(4);
</code>```

declares an array of pointers. You just need

```<code> struct set* graph = create_graph(4);
</code>```

Body:
I want to create an array of type set and have all the nodes set to NULL, hence I used calloc. However, I'm getting an invalid initializer in that one line in main function. Why's that?

struct set {
    int capacity;
    int size;
    char *array;
};

struct set *create_graph(int nodes)
{
  struct set *graph = calloc(nodes - 1, sizeof(struct set));

  return graph;
}
int main()
{

  struct set* graph[] = create_graph(4);
}

Body:
this line

 struct set* graph[] = create_graph(4);

declares an array of pointers. You just need

 struct set* graph = create_graph(4);


问:
Office Add-In for Outlook not sideloading on the app
I have created an custom outlook add in. When I side load it on using the website it works with no issues. When I go into the Outlook app and try to side load, it will install but not show up on the task pane. Is there a reason for this? Thanks!</p>

答:
There are multiple reasons why your add-ins may not be displayed in Office applications/task panes. One of them is the use of http protocol instead of https.

Another point is the privacy control setting in the registry that can be distributed by group policies. Especially the key:

```<code>HKEY_CURRENT_USER\Software\Policies\Microsoft\office\16.0\common\privacy -> controllerconnectedservicesenabled
</code>```

if it is set to dword:00000002 (which is disabled).

You need to change it to dword:00000001 (enabled) and the add-in may immediately appear.The relevant information can be found in the article.

But I'd suggest starting from the Troubleshoot development errors with Office Add-ins article.

Body:
There are multiple reasons why your add-ins may not be displayed in Office applications/task panes. One of them is the use of http protocol instead of https.

Another point is the privacy control setting in the registry that can be distributed by group policies. Especially the key:

HKEY_CURRENT_USER\Software\Policies\Microsoft\office\16.0\common\privacy -> controllerconnectedservicesenabled

if it is set to dword:00000002 (which is disabled).

You need to change it to dword:00000001 (enabled) and the add-in may immediately appear.The relevant information can be found in the article.

But I'd suggest starting from the Troubleshoot development errors with Office Add-ins article.


问:
using loops to create a new array that gets its values from a different array, starting on the second element and multiplying by the previous element
I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element.
Example

```<code>input: [2,3,4,5]
output: [6,12,20]
</code>```

I am trying to use a loop to get this done and here is my code so far

```<code>def funct(array1):
     newarray = []
     for x in array1[1:]:
          newarray.append(x*array1)
     return newarray
</code>```

I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated

答:
You can use a list comprehension like so:

```<code>inp = [2,3,4,5]
out = [j * inp[i-1] for i,j in enumerate(inp) if i != 0]
</code>```

Output:

```<code>[6,12,20]
</code>```

Body:
I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element.
Example

input: [2,3,4,5]
output: [6,12,20]

I am trying to use a loop to get this done and here is my code so far

def funct(array1):
     newarray = []
     for x in array1[1:]:
          newarray.append(x*array1)
     return newarray

I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated

Body:
You can use a list comprehension like so:

inp = [2,3,4,5]
out = [j * inp[i-1] for i,j in enumerate(inp) if i != 0]

Output:

[6,12,20]


答:
Welcome to StackOverflow, there are a few things that I wanted to cover here as part of the answer.

The function is running onClick, the way you're using location.href is invalid though. You are redirecting to an anchor (it starts with a #), The way this is implemented in browsers is that it will redirect your scroll positioning to the top of the element with ID, if you had an element on your page with the ID of placeholder (and the page height was more than 100%) it would move the scroll position of the page, not redirect.

I believe you're looking for

location.href = "placeholder.html";
```
<p>You wanted the user to be redirected based on the username and password that they enter, I will provide the solution below but before that, I wanted to say that this isn't secure, the username and password are visible inside the source code and if you planned to use this to hide important information it will not work because the code is visible to anyone who accesses the webpage, you should be using a server-side language such as NodeJS or PHP to hide that information, I assume that this is just for practise/learning  though.</p>
<p>The first thing you'll want to do is get the username and password.</p>
<p>Your <code><input type="email_" placeholder="email"/></code> should be <code><input type="text" placeholder="email"/></code>. For some reason you put the type as what looks to be a typo <code>email_</code> and not <code>email</code> but since you said the username was <code>admin</code> that is just <code>text</code>.</p>
<p>I would start by giving an ID to both the username and password elements.</p>
<pre class="lang-html prettyprint-override"><code><input type="email" id="username" placeholder="email"/>
<input type="password" id="password" placeholder="password"/>
</code>```

Then inside your function you can change it to check and redirect like below

document.getElementById("login_button").onclick = function () {
  const username = document.getElementById("username").value
  const password = document.getElementById("password").value

  if (username === 'Admin' && password === 'Password123') {
    location.href = "placeholder.html";
  }
};
```

That will also be case-sensitive.

Title: Redirecting from a HTML button to a new page with JS

Body:
Welcome to StackOverflow, there are a few things that I wanted to cover here as part of the answer.

The function is running onClick, the way you're using location.href is invalid though. You are redirecting to an anchor (it starts with a #), The way this is implemented in browsers is that it will redirect your scroll positioning to the top of the element with ID, if you had an element on your page with the ID of placeholder (and the page height was more than 100%) it would move the scroll position of the page, not redirect.

I believe you're looking for

location.href = "placeholder.html";

You wanted the user to be redirected based on the username and password that they enter, I will provide the solution below but before that, I wanted to say that this isn't secure, the username and password are visible inside the source code and if you planned to use this to hide important information it will not work because the code is visible to anyone who accesses the webpage, you should be using a server-side language such as NodeJS or PHP to hide that information, I assume that this is just for practise/learning  though.

The first thing you'll want to do is get the username and password.

Your <input type="email_" placeholder="email"/> should be <input type="text" placeholder="email"/>. For some reason you put the type as what looks to be a typo email_ and not email but since you said the username was admin that is just text.

I would start by giving an ID to both the username and password elements.

<input type="email" id="username" placeholder="email"/>
<input type="password" id="password" placeholder="password"/>

Then inside your function you can change it to check and redirect like below

document.getElementById("login_button").onclick = function () {
  const username = document.getElementById("username").value
  const password = document.getElementById("password").value

  if (username === 'Admin' && password === 'Password123') {
    location.href = "placeholder.html";
  }
};

That will also be case-sensitive.


问:
Avalara tax calculation
I'm new to avalara tax calculation, I have few questions
Do I need to create customer every time a new person came to buy that is call createCustomer for tax calculation?
If customer A total amount is 100 so first do I have to create customer A in avalara?
IF no ,how can I get customer Code to pass in createTransaction?
Is there any option where I just pass shipFrom and shipTo and can get tax value based on totalAmount?</p>

答:
The simple answer to your question is no, however there are some scenarios that you may want to consider for customers that you eventually develop a relationship with.

The customer code is a required field when using the AvaTax service as it is the keystone for managing exemption certificates in our service.

You could, during the CreateTransaction process for example, use data provided by the customer, or auto generate a CustomerCode (i.e. Globally Unique Identifier) to use in the CreateTransaction API.

If the customer requests an exemption later in the relationship, the CustomerCode that was generated in initial transaction could be used later to CreateCustomer API and subsequently link it to an exemption certificate using CreateCertificates API.

During future interactions with the customer using that CustomerCode, AvaTax will search for this value and identify any certificates that are linked to it.

Please visit  https://developer.avalara.com/api-reference/ for more details.

You can also interact with other AvaTax developers on Avalara's Developer Community page.

Title: Avalara tax calculation


问:
Changing the child's useState from Parent component react hooks
I have e child component named Window and I have this useState in Window component:

```<code>Window Component:
      const [showWindow, setShowWindow] = useState(false);
</code>```

Imagine this is the parent component

```<code>Parent component :
/////
////
////
<Window/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>
/////
/////
</code>```

As it can be seen I have a Button component here and I want to set the showWindow to 'true' through it.

How can I change the useState in the child component from its parent component like this example? How can I access to it?

答:
To invoke functions in a child component use the useImperativeHandle hook in the Window component and forward a ref from the parent component to the child to imperatively invoke a function to update the state in the child.

Example:

Window

```<code>import { forwardRef, useImperativeHandle, useState } from 'react';

const Window = forwardRef((props, ref) => {
  const [showWindow, setShowWindow] = useState(false);

  useImperativeHandle(ref, () => ({
    showWindow: () => setShowWindow(true),
  }));

  ...

});
</code>```

Parent

```<code>import { useRef } from 'react';

...

const windowRef = useRef();

...

<Window ref={windowRef} />
<Button onClick={() => windowRef.current.showWindow()}>
  Show Window
</Button>
</code>```

Body:
I have e child component named Window and I have this useState in Window component:

Window Component:
      const [showWindow, setShowWindow] = useState(false);

Imagine this is the parent component

Parent component :
/////
////
////
<Window/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>
/////
/////

As it can be seen I have a Button component here and I want to set the showWindow to 'true' through it.

How can I change the useState in the child component from its parent component like this example? How can I access to it?

Body:
To invoke functions in a child component use the useImperativeHandle hook in the Window component and forward a ref from the parent component to the child to imperatively invoke a function to update the state in the child.

Example:

Window

import { forwardRef, useImperativeHandle, useState } from 'react';

const Window = forwardRef((props, ref) => {
  const [showWindow, setShowWindow] = useState(false);

  useImperativeHandle(ref, () => ({
    showWindow: () => setShowWindow(true),
  }));

  ...

});

Parent

import { useRef } from 'react';

...

const windowRef = useRef();

...

<Window ref={windowRef} />
<Button onClick={() => windowRef.current.showWindow()}>
  Show Window
</Button>


问:
How to make a background using CSS gradient with flat color?
A backgrond like this with same height of red and yellow.

答:
Using Colorzilla's gradient generator, just set two colors to the same % location and you'll get a hard edge between the two colors.</p>

```<code>background: #ffff00; /* Old browsers */
background: -moz-linear-gradient(top, #ffff00 30%, #ffff00 30%, #fe0000 30%); /*  FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(30%,#ffff00), color-stop(30%,#ffff00), color-stop(30%,#fe0000)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff00', endColorstr='#fe0000',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* W3C */
</code>```

Body:
Using Colorzilla's gradient generator, just set two colors to the same % location and you'll get a hard edge between the two colors.

background: #ffff00; /* Old browsers */
background: -moz-linear-gradient(top, #ffff00 30%, #ffff00 30%, #fe0000 30%); /*  FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(30%,#ffff00), color-stop(30%,#ffff00), color-stop(30%,#fe0000)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff00', endColorstr='#fe0000',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* W3C */


问:
How to hide THIS element when I click THIS element's close button (with multiple elements)
I have an alert box that has its own close button. I didn't know users would be placing multiple instances of it on a web page.

Currently, when the close button of an element is clicked, only the first instance gets hidden. I can't close the other one after that. When I click its close button, nothing happens.

I want to be able to click each element's close button to hide that element and have the ability to hide the elements one at a time.  I feel like it has something to do with the THIS keyword, but I'm not sure.

Here's the HTML.

```<code><div class="dcom-c__alert">
<div class="dcom-c-alert__icon">
    <svg class="dcom-c-alert__icon--alert" aria-hidden="true" focusable="false">
        <use xlink:href="/public/icons/cbds-icons-ui.svg#error-circle">
        </use>
    </svg>
</div>
<div class="dcom-c-alert__message">
    <div role="alert" class="dcom-c-alert-copy">Alert: Due to the weather in NC, our branches are closed Tuesday 2/27/21.
    <a href="#" class="dcom-c-alert__icon--message" aria-label="Learn more about this alert.">Learn more
        <svg role="presentation" class="dcom-c-alert__icon--chevron" focusable="false"
            width="20" height="20">
            <use href="/public/icons/cbds-icons-ui.svg#chevron-right"
                xlink:href="/public/icons/cbds-icons-ui.svg#chevron-right">
            </use>
        </svg>
    </a>
    </div>
</div>
</code>```

```<code><button class="dcom-c-close-alert-wrapper" aria-label="Close">
    <svg class="cbds-c-icon cbds-c-iconButton__icon alert-close" focusable="true">
        <use href="../../../public/icons/cbds-icons-ui.svg#close"
            xlink:href="../../../public/icons/cbds-icons-ui.svg#close"></use>
    </svg>
</button>
</code>```

Here's my JavaScript code. Can anyone please help? Thank you.

```<code>const alert = document.querySelector('#dcom-c-alert');
const hideAlert = document.querySelector('.dcom-c-close-alert-wrapper');

function closeAlert() {
    alert.classList.add('hide');
}

hideAlert.addEventListener('click', function () {
    closeAlert();
});

hideAlert.addEventListener("keydown", e => {
    // ADA: Next button activates with spacebar or enter key
    if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
        closeAlert();
    }
});
</code>```

答:
After reading this post, I gained some clarity and solved my own issue. The key was creating a temporary variable (alert, in my case) to hold the index of the current alert.

How can delete the clicked item using the click event if all items have the same Id

Here's my JavasScript:

```<code>alerts.forEach(alert => {
    let alert = alerts[i];
    closeButtons[i].addEventListener('click', function () {
        alert.remove();
    });
});
</code>```

Body:
I have an alert box that has its own close button. I didn't know users would be placing multiple instances of it on a web page.

Currently, when the close button of an element is clicked, only the first instance gets hidden. I can't close the other one after that. When I click its close button, nothing happens.

I want to be able to click each element's close button to hide that element and have the ability to hide the elements one at a time.  I feel like it has something to do with the THIS keyword, but I'm not sure.

Here's the HTML.

    <svg class="dcom-c-alert__icon--alert" aria-hidden="true" focusable="false">
        <use xlink:href="/public/icons/cbds-icons-ui.svg#error-circle">
        </use>
    </svg>

Alert: Due to the weather in NC, our branches are closed Tuesday 2/27/21.
    Learn more
        <svg role="presentation" class="dcom-c-alert__icon--chevron" focusable="false"
            width="20" height="20">
            <use href="/public/icons/cbds-icons-ui.svg#chevron-right"
                xlink:href="/public/icons/cbds-icons-ui.svg#chevron-right">
            </use>
        </svg>

<button class="dcom-c-close-alert-wrapper" aria-label="Close">
    <svg class="cbds-c-icon cbds-c-iconButton__icon alert-close" focusable="true">
        <use href="../../../public/icons/cbds-icons-ui.svg#close"
            xlink:href="../../../public/icons/cbds-icons-ui.svg#close"></use>
    </svg>
</button>

Here's my JavaScript code. Can anyone please help? Thank you.

const alert = document.querySelector('#dcom-c-alert');
const hideAlert = document.querySelector('.dcom-c-close-alert-wrapper');

function closeAlert() {
    alert.classList.add('hide');
}

hideAlert.addEventListener('click', function () {
    closeAlert();
});

hideAlert.addEventListener("keydown", e => {
    // ADA: Next button activates with spacebar or enter key
    if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
        closeAlert();
    }
});

Body:
After reading this post, I gained some clarity and solved my own issue. The key was creating a temporary variable (alert, in my case) to hold the index of the current alert.

How can delete the clicked item using the click event if all items have the same Id

Here's my JavasScript:

alerts.forEach(alert => {
    let alert = alerts[i];
    closeButtons[i].addEventListener('click', function () {
        alert.remove();
    });
});


问:
Build a function that accepts a Class in typescript
I'm trying to build a function that would take a class definition as a parameter in order to switch on it's name

This is just to simplify my tests by creating one function that can generate data based on a given class

```<code>getMockDataForClass(c: Class, override){
   if(c === Person){ return getPersonMockData(override)}
   if(c === Dog){ return getDogMockData(override)}
...
}
</code>```

so that I can write test like:

```<code>it('should process a persons information', ()=>{
   const p = getMockDataForClass(Person)
...
})

it('should compare 2 persons', ()=>{
   const p = getMockDataForClass(Person)
   const p2 = getMockDataForClass(Person, {name: 'Jane'})
})
</code>```

However there doesn't seem to be a type of class which would allow me to make this generic

答:
Do you just want a "newable" type here?

```<code>type Class = {
    new (...args: unknown[]): unknown
    name: string // if you need it
}
</code>```

Which works as you may expect:

```<code>class Person { person = true }
class Dog { dog = true }

function getMockDataForClass(c: Class, override: Class){
   if(c === Person) { return override}
   if(c === Dog){ return override }
   return c
}

getMockDataForClass(Person, Dog)
</code>```

Playground

If you want the second argument to be an instance of the class that is the first argument, then you need to capture the class constructor as a generic parameter. And then the override is an instance of that class.

For instance:

```<code>type Class = {
    new (...args: any[]): unknown
}

class Person {
    constructor(public name: string) {}
}

class Dog {
    constructor(public breed: string) {}
}

function getMockDataForClass<T extends Class>(c: T, override: InstanceType<T>){
  //implementation...
}

getMockDataForClass(Person, {name: 'John'}) // fine
getMockDataForClass(Dog, {breed: 'Terrier'}) // fine
getMockDataForClass(Person, {breed: 'Terrier'}) // error
</code>```

Playground

Body:
I'm trying to build a function that would take a class definition as a parameter in order to switch on it's name

This is just to simplify my tests by creating one function that can generate data based on a given class

getMockDataForClass(c: Class, override){
   if(c === Person){ return getPersonMockData(override)}
   if(c === Dog){ return getDogMockData(override)}
...
}

so that I can write test like:

it('should process a persons information', ()=>{
   const p = getMockDataForClass(Person)
...
})

it('should compare 2 persons', ()=>{
   const p = getMockDataForClass(Person)
   const p2 = getMockDataForClass(Person, {name: 'Jane'})
})

However there doesn't seem to be a type of class which would allow me to make this generic

Body:
Do you just want a "newable" type here?

type Class = {
    new (...args: unknown[]): unknown
    name: string // if you need it
}

Which works as you may expect:

class Person { person = true }
class Dog { dog = true }

function getMockDataForClass(c: Class, override: Class){
   if(c === Person) { return override}
   if(c === Dog){ return override }
   return c
}

getMockDataForClass(Person, Dog)

Playground

If you want the second argument to be an instance of the class that is the first argument, then you need to capture the class constructor as a generic parameter. And then the override is an instance of that class.

For instance:

type Class = {
    new (...args: any[]): unknown
}

class Person {
    constructor(public name: string) {}
}

class Dog {
    constructor(public breed: string) {}
}

function getMockDataForClass<T extends Class>(c: T, override: InstanceType<T>){
  //implementation...
}

getMockDataForClass(Person, {name: 'John'}) // fine
getMockDataForClass(Dog, {breed: 'Terrier'}) // fine
getMockDataForClass(Person, {breed: 'Terrier'}) // error

<a href="https://www.typescriptlang.org/play?ssl=21&ssc=57&pln=19&pc=1#code/C4TwDgpgBAwgNgQwM5KgXigbwFBT1AOwgHcoAKAOioQCcBzJALigQJAG0BdASmYFcCAawIB7YgWwBfbNgDGiFFAAKEGkhEEs2AJCyNSYDT6zgImmTB8ARnACWswggC2EZgZq2CdblmnS5CqgAIiJ0Wrr6hsam5pY29lBWNBAQACZuhp7evlIyAGYCJrYaUHQQwACyIrKCQQjACABiZvDISAA8ACpQEAAewBAEqaitKAB8ZLLMnQA0UCIAbqoeqa5QAJIEBqyyEJ3gEF1j3Dj4tnmT6GgYKmoaPphQycB8NJqLy7ar0mcXDtcYELeR7PV7vJY0FbQH54UFvKCyXLYMqVaq1epNFqBMi3dQEOaYAjONYAcgAUiIABYEEmSHwAenpUDynggyPKVRqdQazRooyQZCBBKSKXSUBJnU+qlpDKZLKI7NRXIxvP5ONUeOFyTSzAlUpoMqgjJ6kLMQA" rel="nofollow noreferrer">Playground


问:
Data frame columns do not change once placing for-loop inside of function body - Rstudio
I have a dataframe with many variables and I'd like to change their names using a function. The column names have the following form

```<code>"Department_Home_Converted_Sum"
"Department_Womenswear_Converted_Sum"
"Department_Menswear_Converted_Sum"
"Department_Shoes_Converted_Sum"
"Department_Kidswear_Converted_Sum"
</code>```

So I want to remove "Department_" and "_Converted_Sum". I managed to to it just by looping through the column names like this which works fine.

```<code>for (i in seq(1,length(colnames(mydf)))){
    colnames(mydf)[i] = str_sub(colnames(mydf)[i], 11, str_length(colnames(mydf)[i])-14)
}
</code>```

But what bothers me is that once I place this inside of a function and then use the function on mydf, the dataframe has no changed column names.

```<code>rename_columns <- function(df){
   for (i in seq(1,length(colnames(df)))){
      colnames(df)[i] = str_sub(colnames(df)[i], 11, str_length(colnames(df)[i])-14)
   }
}

rename_columns(mydf)
</code>```

I also tried to add a return(df) but it did not help. Does any one know why the function can't mutate the column names?

答:
If all you want to do is want to remove "Department_" and "_Converted_Sum" you can avoid the looping by using str_remove_all() from the stringr package.

names(df) <- stringr::str_remove_all(names(df), "Department_|_Converted_Sum")
```

Body:
I have a dataframe with many variables and I'd like to change their names using a function. The column names have the following form

"Department_Home_Converted_Sum"
"Department_Womenswear_Converted_Sum"
"Department_Menswear_Converted_Sum"
"Department_Shoes_Converted_Sum"
"Department_Kidswear_Converted_Sum"

So I want to remove "Department_" and "_Converted_Sum". I managed to to it just by looping through the column names like this which works fine.

for (i in seq(1,length(colnames(mydf)))){
    colnames(mydf)[i] = str_sub(colnames(mydf)[i], 11, str_length(colnames(mydf)[i])-14)
}

But what bothers me is that once I place this inside of a function and then use the function on mydf, the dataframe has no changed column names.

rename_columns <- function(df){
   for (i in seq(1,length(colnames(df)))){
      colnames(df)[i] = str_sub(colnames(df)[i], 11, str_length(colnames(df)[i])-14)
   }
}

rename_columns(mydf)

I also tried to add a return(df) but it did not help. Does any one know why the function can't mutate the column names?