问:
Different sessions created when page is called by external application as a return URL
I have an ASP.Net web apps application. Where I am using session to save a data. The application calls an external application where user can select a value and the selected value is stored in an external store and it returns a key to a return site which is an End.aspx page on our application.

I need to identify that I have received a key and then get the details and update the controls with value on the calling page. Since the End.aspx is independent page to let the calling page know that a key has been received I am saving the key in Session.

On the calling page.aspx, I have a timer pool that will call an ajax post to a WebMethod where I check if the session has the value to start processing, and then return true for the timer to stop.

All this works as expected when the site is hosted on IIS as Application on the 'Default Web Site' and the external site is also hosted in the same 'Defacult web site', but when I host this site directly as a Website on IIS and the external website is still on 'Default web site', now when the external website calls the return URL to end.aspx, it creates a new session id store, hence the WebMethod that is on the calling page gets a null value.

Is there a way to use the same session even if the two sites are hosted in different domains like in e.g., above, please can you suggest if any better approach possible.

I am storing the session in SQL.

Below is the code I am using.
have two different sites. e.g. Site1 and Site2. Site1 is hosted as website on IIS (http://site1) and site2 is hosted as application on 'Default web site' (http://myvm/site2)

In Site 1 I have a page customerpage.aspx which I open it as a popup form bookpage.aspx. In the Customerpage.aspx I open the site2 (http://myvm/site2/customerfinder.aspx?returnurl=http://site1/end.aspx).

Now from the site2 when a customer is selected it will then call the return URL. This invokes http://site1/end.aspx. In here I am adding the values sent by site2 to session, but in this case, it is creating a new session id.

Now I have the ajax call in customerpage.aspx which calls the WebMethod to keep checking if the session has the given value but since the session id on the customerpage.aspx is different it gets a null value.

In End.Aspx.cs that will be called by the external application as return URL

```<code>public class End : System.Web.UI.Page
{
   private void Page_Load(object sender, System.EventArgs e)
   {
        HttpContext.Current.Session["closed"] = true;
   }
}
</code>```

In the Customerpage.aspx.cs

```<code>    public partial class CustomerPagepopup : System.Web.UI.Page
    {
        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod(EnableSession = true)]
        public static bool CheckClosed()
        {
            bool closed = false;
            if (HttpContext.Current.Session["closed"] != null)
            {
                HttpContext.Current.Session["closed"] = null;
                return true;
            }
            return closed;
        }
   }
</code>```

here is the JS that calls the WebMethod from the customerpage.aspx

```<code>       function GetIfClosed() {
                $.ajax({
                    type: "POST",
                    url: '<%= ResolveUrl("callingpage.aspx/CheckClosed") %>',
                    data: "",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {

                        // Evaulate result..
                        var process = msg.d

                        if (process) {
                            // destroy the timer to stop polling for progress
                            clearTimeout(timer);
                            $("#cboxClose").click();
                            // Do your final message to the user here.

                        } else {

                            // poll timer for another trip
                            TimerPoll();
                        }
                    }
                });
            }
</code>```

Body:
I have an ASP.Net web apps application. Where I am using session to save a data. The application calls an external application where user can select a value and the selected value is stored in an external store and it returns a key to a return site which is an End.aspx page on our application.

I need to identify that I have received a key and then get the details and update the controls with value on the calling page. Since the End.aspx is independent page to let the calling page know that a key has been received I am saving the key in Session.

On the calling page.aspx, I have a timer pool that will call an ajax post to a WebMethod where I check if the session has the value to start processing, and then return true for the timer to stop.

All this works as expected when the site is hosted on IIS as Application on the 'Default Web Site' and the external site is also hosted in the same 'Defacult web site', but when I host this site directly as a Website on IIS and the external website is still on 'Default web site', now when the external website calls the return URL to end.aspx, it creates a new session id store, hence the WebMethod that is on the calling page gets a null value.

Is there a way to use the same session even if the two sites are hosted in different domains like in e.g., above, please can you suggest if any better approach possible.

I am storing the session in SQL.

Below is the code I am using.
have two different sites. e.g. Site1 and Site2. Site1 is hosted as website on IIS (http://site1) and site2 is hosted as application on 'Default web site' (http://myvm/site2)

In Site 1 I have a page customerpage.aspx which I open it as a popup form bookpage.aspx. In the Customerpage.aspx I open the site2 (http://myvm/site2/customerfinder.aspx?returnurl=http://site1/end.aspx).

Now from the site2 when a customer is selected it will then call the return URL. This invokes http://site1/end.aspx. In here I am adding the values sent by site2 to session, but in this case, it is creating a new session id.

Now I have the ajax call in customerpage.aspx which calls the WebMethod to keep checking if the session has the given value but since the session id on the customerpage.aspx is different it gets a null value.

In End.Aspx.cs that will be called by the external application as return URL

public class End : System.Web.UI.Page
{
   private void Page_Load(object sender, System.EventArgs e)
   {
        HttpContext.Current.Session["closed"] = true;
   }
}

In the Customerpage.aspx.cs

    public partial class CustomerPagepopup : System.Web.UI.Page
    {
        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod(EnableSession = true)]
        public static bool CheckClosed()
        {
            bool closed = false;
            if (HttpContext.Current.Session["closed"] != null)
            {
                HttpContext.Current.Session["closed"] = null;
                return true;
            }
            return closed;
        }
   }

here is the JS that calls the WebMethod from the customerpage.aspx

       function GetIfClosed() {
                $.ajax({
                    type: "POST",
                    url: '<%= ResolveUrl("callingpage.aspx/CheckClosed") %>',
                    data: "",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {

                        // Evaulate result..
                        var process = msg.d

                        if (process) {
                            // destroy the timer to stop polling for progress
                            clearTimeout(timer);
                            $("#cboxClose").click();
                            // Do your final message to the user here.

                        } else {

                            // poll timer for another trip
                            TimerPoll();
                        }
                    }
                });
            }


来源: stackexchange

问:
how to give mercurial access through PPK key
When I try to clone the project on a formatted computer  I get an error because I don't have access permission to the repositories. I try to clone to project using net beans "clone other" option. The problem arrises from the fact that the users involved in the project don't remeber how to process to grant permission was done. I know that the permission is given using a ppk file somehow. but I don't remeber how. I have the ppk from the old formatting.</p>

ContentLicense: CC BY-SA 4.0


问:
How do I use a pytest fixture to mock a child class's inherited methods with classes as properties while maintaining the API contract using autospec?

How it started

I'm testing a class, ClassToTest, that makes API calls using atlassian-python-api. The tests are going to ensure that ClassToTest performs correctly with the data it gets back from the API. Many of the atlassian-python-api API calls use instantiated classes which inherit from the same base class or group of top-level classes.

I'd like to write tests that will expose breaks in the API contract if the wrong data is returned or API calls fail, while also testing the class I wrote to ensure it does the correct things with the data returned from the API. In order to do this, I was hoping to use unittest.mock.patch("path.to.Comment", autospec=True) to copy the API spec into the MagicMock, but I don't believe it's working properly.

For the purposes of the question, ClassToTest is not that important; what I am aiming to solve is how to setup and configure the pytest fixtures in a way that I can use them to mimic the API endpoints that will return the data that ClassToTest will act upon. Ideally I'd like to reuse the fixtures without having patch conflicts. I've included relevant code from ClassToTest for illustrative purposes here:

class_to_test.py:

```<code>from atlassian.bitbucket import Cloud
from typing import NamedTuple
# these are hardcoded constants that work with the production API
from src.constants import (
    PULL_REQUEST_ID,
    REPOSITORY,
    WORKSPACE,
)

CommentType = NamedTuple("CommentType", [("top_level", str), ("inline", str)])

class ClassToTest:
    def _get_token(self):
        """this returns a token of type(str)"""

    def __init__(self, workspace, repository, pull_request_id):
        self.active_comments = None
        self.environment = sys.argv[1]
        self.comment_text = CommentType(
            top_level=r"top_level_comment text", inline=r"inline_comment text"
        )
        self.cloud = Cloud(token=self._get_token(), cloud=True)
        self.workspace = self.cloud.workspaces.get(workspace)
        self.repository = self.cloud.repositories.get(workspace, repository)
        self.pull_request = self.repository.pullrequests.get(id=pull_request_id)

    def _get_active_comments(self):
        """Returns a list of active (non-deleted) comments"""
        return [
            c for c in self.pull_request.comments() if c.data["deleted"] is False
        ]
    # a few more methods here

def main():
    instance = ClassToTest(WORKSPACE, REPOSITORY, PULL_REQUEST_ID)
    # result = instance.method() for each method I need to call.
    # do things with each result

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

The class has methods that retrieve comments from the API (_get_active_comments, above), act on the retrieved comments, retrieve pull requests, and so on. What I am trying to test is that the class methods act correctly on the data received from the API, so I need to accurately mock data returned from API calls.

How it's going

I started with a unittest.Testcase style test class and wanted the flexibility of pytest fixtures (and autospec), but removed Testcase entirely when I discovered that pytest fixtures don't really work with it. I'm currently using a pytest class and conftest.py as follows:

/test/test_class_to_test.py:

```<code>import pytest

from unittest.mock import patch

from src.class_to_test import ClassToTest

@pytest.mark.usefixtures("mocked_comment", "mocked_user")
class TestClassToTest:
    # We mock Cloud here as ClassToTest calls it in __init__ to authenticate with the API
    # _get_token retrieves an access token for the API; since we don't need it, we can mock it
    @patch("src.test_class_to_test.Cloud", autospec=True)
    @patch.object(ClassToTest, "_get_token").
    def setup_method(self, method, mock_get_token, mock_cloud):
        mock_get_token.return_value = "token"
        self.checker = ClassToTest("WORKSPACE", "REPOSITORY", 1)

    def teardown_method(self, method):
        pass

    def test_has_top_level_and_inline_comments(self, mocked_comment, mocked_pull_request):
        mock_top_comment = mocked_comment(raw="some text to search for later")

        assert isinstance(mock_top_comment.data, dict)
        assert mock_top_comment.data["raw"] == "some text to search for later"
        # the assert below this line is failing
        assert mock_top_comment.user.account_id == 1234

</code>```

conftest.py:

```<code>import pytest
from unittest.mock import patch, PropertyMock

from atlassian.bitbucket.cloud.common.comments import Comment
from atlassian.bitbucket.cloud.common.users import User

@pytest.fixture()
def mocked_user(request):
    def _mocked_user(account_id=1234):
        user_patcher = patch(
            f"atlassian.bitbucket.cloud.common.users.User", spec_set=True, autospec=True
        )
        MockUser = user_patcher.start()
        data = {"type": "user", "account_id": account_id}
        url = "user_url"
        user = MockUser(data=data, url=url)

        # setup mocked properties
        mock_id = PropertyMock(return_value=account_id)
        type(user).id = mock_id
        mockdata = PropertyMock(return_value=data)
        type(user).data = mockdata
        request.addfinalizer(user_patcher.stop)
        return user
    return _mocked_user

@pytest.fixture()
def mocked_comment(request, mocked_user):
    def _mocked_comment(raw="", inline=None, deleted=False, user_id=1234):
        comment_patcher = patch(
            f"atlassian.bitbucket.cloud.common.comments.Comment", spec_set=True, autospec=True
        )
        MockComment = comment_patcher.start()
        data = {
            "type": "pullrequest_comment",
            "user": mocked_user(user_id),
            "raw": raw,
            "deleted": deleted,
        }
        if inline:
            data["inline"] = {"from": None, "to": 1, "path": "src/code_issues.py"}
            data["raw"] = "this is an inline comment"
        comment = MockComment(data)
        # setup mocked properties
        mockdata = PropertyMock(return_value=data)
        type(comment).data = mockdata
        # mockuser = PropertyMock(return_value=mocked_user(user_id))
        # type(comment).user = mockuser
        request.addfinalizer(comment_patcher.stop)
        return comment

    return _mocked_comment

</code>```

The problem I am encountering is that the assert mock_top_comment.user.account_id == 1234 line fails when running the test, with the following error:

```<code>>       assert mock_top_comment.user.account_id == 1234
E       AssertionError: assert <MagicMock name='Comment().user.account_id' id='4399290192'> == 1234
E        +  where <MagicMock name='Comment().user.account_id' id='4399290192'> = <MagicMock name='Comment().user' id='4399634736'>.account_id
E        +    where <MagicMock name='Comment().user' id='4399634736'> = <NonCallableMagicMock name='Comment()' spec_set='Comment' id='4399234928'>.user
</code>```

How do I get the mock User class to attach to the mock Comment class in the same way that the real API makes it work? Is there something about autospec that I'm missing, or should I be abandoning unittest.mock.patch entirely and using something else?

Extra credit (EDIT: in retrospect, this may be the most important part)

I'm using mocked_comment as a pytest fixture factory and want to reuse it multiple times in the same test (for example to create multiple mocked Comments returned in a list). So far, each time I've tried to do that, I've been met with the following error:

```<code>    def test_has_top_level_and_inline_comments(self, mocked_comment, mocked_pull_request):
        mock_top_comment = mocked_comment(raw="Some comment text")
>       mock_inline_comment = mocked_comment(inline=True)

...

test/conftest.py:30: in _mocked_comment
    MockComment = comment_patcher.start()
/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/mock.py:1585: in start
    result = self.__enter__()

...

>               raise InvalidSpecError(
                    f'Cannot autospec attr {self.attribute!r} from target '
                    f'{target_name!r} as it has already been mocked out. '
                    f'[target={self.target!r}, attr={autospec!r}]')
E               unittest.mock.InvalidSpecError: Cannot autospec attr 'Comment' from target 'atlassian.bitbucket.cloud.common.comments' as it has already been mocked out. [target=<module 'atlassian.bitbucket.cloud.common.comments' from '/opt/homebrew/lib/python3.10/site-packages/atlassian/bitbucket/cloud/common/comments.py'>, attr=<MagicMock name='Comment' spec_set='Comment' id='4398964912'>]
</code>```

I thought the whole point of a pytest fixture factory was to be reusable, but I believe that using an autospec mock complicates things quite a bit. I don't want to have to hand copy every detail from the API spec into the tests, as that will have to be changed if anything in the API changes. Is there a solution for this that involves automatically and dynamically creating the necessary classes in the mocked API with the correct return values for properties?

One thing I'm considering is separating the testing into two parts: API contract, and ClassToTest testing. In this way I can write the tests for ClassToTest without relying on the API and they will pass as long as I manipulate the received data correctly. Any changes to the API will get caught by the separate contract testing tests. Then I can use non-factory fixtures with static data for testing ClassToTest.

For now though, I'm out of ideas on how to proceed with this. What should I do here? Probably the most important thing to address is how to properly link the User instance with the Comment instance in the fixtures so that my method calls in test work the same way as they do in production. Bonus points if we can figure out how to dynamically patch multiple fixtures in a single test.

I've started looking at this answer, but given the number of interconnected classes and properties, I'm not sure it will work without writing out a ton of fixtures. After following the directions and applying them to the User mock inside the Comment mock, I started getting the error in the Extra Credit section above, where autospec couldn't be used as it has already been mocked out.

Body:
How it started

I'm testing a class, ClassToTest, that makes API calls using atlassian-python-api. The tests are going to ensure that ClassToTest performs correctly with the data it gets back from the API. Many of the atlassian-python-api API calls use instantiated classes which inherit from the same base class or group of top-level classes.

I'd like to write tests that will expose breaks in the API contract if the wrong data is returned or API calls fail, while also testing the class I wrote to ensure it does the correct things with the data returned from the API. In order to do this, I was hoping to use unittest.mock.patch("path.to.Comment", autospec=True) to copy the API spec into the MagicMock, but I don't believe it's working properly.

For the purposes of the question, ClassToTest is not that important; what I am aiming to solve is how to setup and configure the pytest fixtures in a way that I can use them to mimic the API endpoints that will return the data that ClassToTest will act upon. Ideally I'd like to reuse the fixtures without having patch conflicts. I've included relevant code from ClassToTest for illustrative purposes here:

class_to_test.py:

from atlassian.bitbucket import Cloud
from typing import NamedTuple
# these are hardcoded constants that work with the production API
from src.constants import (
    PULL_REQUEST_ID,
    REPOSITORY,
    WORKSPACE,
)

CommentType = NamedTuple("CommentType", [("top_level", str), ("inline", str)])

class ClassToTest:
    def _get_token(self):
        """this returns a token of type(str)"""

    def __init__(self, workspace, repository, pull_request_id):
        self.active_comments = None
        self.environment = sys.argv[1]
        self.comment_text = CommentType(
            top_level=r"top_level_comment text", inline=r"inline_comment text"
        )
        self.cloud = Cloud(token=self._get_token(), cloud=True)
        self.workspace = self.cloud.workspaces.get(workspace)
        self.repository = self.cloud.repositories.get(workspace, repository)
        self.pull_request = self.repository.pullrequests.get(id=pull_request_id)

    def _get_active_comments(self):
        """Returns a list of active (non-deleted) comments"""
        return [
            c for c in self.pull_request.comments() if c.data["deleted"] is False
        ]
    # a few more methods here

def main():
    instance = ClassToTest(WORKSPACE, REPOSITORY, PULL_REQUEST_ID)
    # result = instance.method() for each method I need to call.
    # do things with each result

if __name__ == "__main__":
    main()

The class has methods that retrieve comments from the API (_get_active_comments, above), act on the retrieved comments, retrieve pull requests, and so on. What I am trying to test is that the class methods act correctly on the data received from the API, so I need to accurately mock data returned from API calls.

How it's going

I started with a unittest.Testcase style test class and wanted the flexibility of pytest fixtures (and autospec), but removed Testcase entirely when I discovered that pytest fixtures don't really work with it. I'm currently using a pytest class and conftest.py as follows:

/test/test_class_to_test.py:

import pytest

from unittest.mock import patch

from src.class_to_test import ClassToTest

@pytest.mark.usefixtures("mocked_comment", "mocked_user")
class TestClassToTest:
    # We mock Cloud here as ClassToTest calls it in __init__ to authenticate with the API
    # _get_token retrieves an access token for the API; since we don't need it, we can mock it
    @patch("src.test_class_to_test.Cloud", autospec=True)
    @patch.object(ClassToTest, "_get_token").
    def setup_method(self, method, mock_get_token, mock_cloud):
        mock_get_token.return_value = "token"
        self.checker = ClassToTest("WORKSPACE", "REPOSITORY", 1)

    def teardown_method(self, method):
        pass

    def test_has_top_level_and_inline_comments(self, mocked_comment, mocked_pull_request):
        mock_top_comment = mocked_comment(raw="some text to search for later")

        assert isinstance(mock_top_comment.data, dict)
        assert mock_top_comment.data["raw"] == "some text to search for later"
        # the assert below this line is failing
        assert mock_top_comment.user.account_id == 1234

conftest.py:

import pytest
from unittest.mock import patch, PropertyMock

from atlassian.bitbucket.cloud.common.comments import Comment
from atlassian.bitbucket.cloud.common.users import User

@pytest.fixture()
def mocked_user(request):
    def _mocked_user(account_id=1234):
        user_patcher = patch(
            f"atlassian.bitbucket.cloud.common.users.User", spec_set=True, autospec=True
        )
        MockUser = user_patcher.start()
        data = {"type": "user", "account_id": account_id}
        url = "user_url"
        user = MockUser(data=data, url=url)

        # setup mocked properties
        mock_id = PropertyMock(return_value=account_id)
        type(user).id = mock_id
        mockdata = PropertyMock(return_value=data)
        type(user).data = mockdata
        request.addfinalizer(user_patcher.stop)
        return user
    return _mocked_user

@pytest.fixture()
def mocked_comment(request, mocked_user):
    def _mocked_comment(raw="", inline=None, deleted=False, user_id=1234):
        comment_patcher = patch(
            f"atlassian.bitbucket.cloud.common.comments.Comment", spec_set=True, autospec=True
        )
        MockComment = comment_patcher.start()
        data = {
            "type": "pullrequest_comment",
            "user": mocked_user(user_id),
            "raw": raw,
            "deleted": deleted,
        }
        if inline:
            data["inline"] = {"from": None, "to": 1, "path": "src/code_issues.py"}
            data["raw"] = "this is an inline comment"
        comment = MockComment(data)
        # setup mocked properties
        mockdata = PropertyMock(return_value=data)
        type(comment).data = mockdata
        # mockuser = PropertyMock(return_value=mocked_user(user_id))
        # type(comment).user = mockuser
        request.addfinalizer(comment_patcher.stop)
        return comment

    return _mocked_comment

The problem I am encountering is that the assert mock_top_comment.user.account_id == 1234 line fails when running the test, with the following error:

>       assert mock_top_comment.user.account_id == 1234
E       AssertionError: assert <MagicMock name='Comment().user.account_id' id='4399290192'> == 1234
E        +  where <MagicMock name='Comment().user.account_id' id='4399290192'> = <MagicMock name='Comment().user' id='4399634736'>.account_id
E        +    where <MagicMock name='Comment().user' id='4399634736'> = <NonCallableMagicMock name='Comment()' spec_set='Comment' id='4399234928'>.user

How do I get the mock User class to attach to the mock Comment class in the same way that the real API makes it work? Is there something about autospec that I'm missing, or should I be abandoning unittest.mock.patch entirely and using something else?

Extra credit (EDIT: in retrospect, this may be the most important part)

I'm using mocked_comment as a pytest fixture factory and want to reuse it multiple times in the same test (for example to create multiple mocked Comments returned in a list). So far, each time I've tried to do that, I've been met with the following error:

    def test_has_top_level_and_inline_comments(self, mocked_comment, mocked_pull_request):
        mock_top_comment = mocked_comment(raw="Some comment text")
>       mock_inline_comment = mocked_comment(inline=True)

...

test/conftest.py:30: in _mocked_comment
    MockComment = comment_patcher.start()
/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/mock.py:1585: in start
    result = self.__enter__()

...

>               raise InvalidSpecError(
                    f'Cannot autospec attr {self.attribute!r} from target '
                    f'{target_name!r} as it has already been mocked out. '
                    f'[target={self.target!r}, attr={autospec!r}]')
E               unittest.mock.InvalidSpecError: Cannot autospec attr 'Comment' from target 'atlassian.bitbucket.cloud.common.comments' as it has already been mocked out. [target=<module 'atlassian.bitbucket.cloud.common.comments' from '/opt/homebrew/lib/python3.10/site-packages/atlassian/bitbucket/cloud/common/comments.py'>, attr=<MagicMock name='Comment' spec_set='Comment' id='4398964912'>]

I thought the whole point of a pytest fixture factory was to be reusable, but I believe that using an autospec mock complicates things quite a bit. I don't want to have to hand copy every detail from the API spec into the tests, as that will have to be changed if anything in the API changes. Is there a solution for this that involves automatically and dynamically creating the necessary classes in the mocked API with the correct return values for properties?

One thing I'm considering is separating the testing into two parts: API contract, and ClassToTest testing. In this way I can write the tests for ClassToTest without relying on the API and they will pass as long as I manipulate the received data correctly. Any changes to the API will get caught by the separate contract testing tests. Then I can use non-factory fixtures with static data for testing ClassToTest.

For now though, I'm out of ideas on how to proceed with this. What should I do here? Probably the most important thing to address is how to properly link the User instance with the Comment instance in the fixtures so that my method calls in test work the same way as they do in production. Bonus points if we can figure out how to dynamically patch multiple fixtures in a single test.

I've started looking at this answer, but given the number of interconnected classes and properties, I'm not sure it will work without writing out a ton of fixtures. After following the directions and applying them to the User mock inside the Comment mock, I started getting the error in the Extra Credit section above, where autospec couldn't be used as it has already been mocked out.


问:
How to view gunicorn output for an app that's already running?
I am running a Flask/python app on a website in my terminal using:

```<code>gunicorn --workers 4 --bind :5000 app:app
</code>```

It shows me the log but it eventually times out, even though the website is still up and running. Is there a way I can go back to viewing the log?

So far, I can only go back to seeing the log by running sudo reboot
for the Ubuntu server and then reopening the server with ssh and running the gunicorn code again.

Body:
I am running a Flask/python app on a website in my terminal using:

gunicorn --workers 4 --bind :5000 app:app

It shows me the log but it eventually times out, even though the website is still up and running. Is there a way I can go back to viewing the log?

So far, I can only go back to seeing the log by running sudo reboot
for the Ubuntu server and then reopening the server with ssh and running the gunicorn code again.


问:
.htaccess Rewrite to Force Trailing Slash at the end for the folders & viceverca for .html files
I have the following code in my .htaccess file:

```<code>
redirect 301 /file-a /folder1/file-a.html

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

RewriteRule ^(.+?\.html)/ /$1 [R=301,L]mediyaar

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1
</code>```

The above code is giving me the desired results but too many redirects are there.

I am looking for below redirection of my pages, can this be achieved with a single redirect

https://www.example.com/file-a

( redirect 301 to )
https://www.example.com/folder1/file-a.html

https://www.example.com/folder1
( Add Force Trailing Slash at the end for the folders )
https://www.example.com/folder1/

https://www.example.com/folder1/file-a-b-c.html/
( remove Trailing Slash at the end for the file )
https://www.example.com/folder1/file-a-b-c.html

Body:
I have the following code in my .htaccess file:

redirect 301 /file-a /folder1/file-a.html

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

RewriteRule ^(.+?\.html)/ /$1 [R=301,L]mediyaar

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1

The above code is giving me the desired results but too many redirects are there.

I am looking for below redirection of my pages, can this be achieved with a single redirect

https://www.example.com/file-a

( redirect 301 to )
https://www.example.com/folder1/file-a.html

https://www.example.com/folder1
( Add Force Trailing Slash at the end for the folders )
https://www.example.com/folder1/

https://www.example.com/folder1/file-a-b-c.html/
( remove Trailing Slash at the end for the file )
https://www.example.com/folder1/file-a-b-c.html


问:
Soft Deletion with Spring JPA
I've done a few changes on my code, because now I want to have a soft deletion instead of a normal one.
I would only need a few JPA annotations for this purpose.
I think I got the right idea, but now I can't even run it because it give the following error:
"""Type mismatch: cannot convert from String to Class<?>"""

My CloudProduct.java ( the one with the error ) :

```<code>package com.proj.my.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.Id;

import java.sql.Date;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import jakarta.persistence.Table;

@Entity
@Table(name="cloud_product_info")
@SQLDelete(sql = "UPDATE cloud_products_info SET deleted = true WHERE id=?")
@FilterDef(name = "deletedProductFilter", parameters = @ParamDef(name = "isDeleted", type = "boolean"))
@Filter(name = "deletedProductFilter", condition = "deleted = :isDeleted")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
        allowGetters = true)

public class CloudProduct {

    @Id
    private String productId;
    private String productName;
    private String productPrice;
    @CreationTimestamp
    @Column(updatable = false, name = "created_at")
    private Date createdAt;
    private boolean deleted = Boolean.FALSE;

    public Boolean getDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

    public CloudProduct(String productId, String productName, String productPrice, Date createdAt, boolean deleted) {
        this.productId = productId;
        this.productName = productName;
        this.productPrice = productPrice;
        this.createdAt = createdAt;
        this.deleted = deleted;
    }

    public CloudProduct() {

    }

    public String getProductId() {
        return productId;
    }
    public void setProductId(String productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductPrice() {
        return productPrice;
    }
    public void setProductPrice(String productPrice) {
        this.productPrice = productPrice;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
}
</code>```

The error is implicit on :

```<code>@FilterDef(name = "deletedProductFilter", parameters = @ParamDef(name = "isDeleted", type = "boolean"))
</code>```

Specifically on the "type = "boolean" ".
He is my CloudProductController.java

```<code>
package com.proj.my.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;

@RestController
@RequestMapping("/cloudproduct")

public class CloudProductController
{

    CloudProductService cloudProductService;

    public CloudProductController(CloudProductService cloudProductService)
    {
        this.cloudProductService = cloudProductService;
    }

    @GetMapping("{productId}")
    public CloudProduct getCloudProductDetails(@PathVariable("productId") String productId){
        return cloudProductService.getCloudProduct(productId);
    }

    @PostMapping
    public String createCloudProductDetails(@RequestBody CloudProduct cloudProduct){

        cloudProductService.createCloudProduct(cloudProduct);
        return "Success";
    }

    @PutMapping
    public String updateCloudProductDetails(@RequestBody CloudProduct cloudProduct){

        cloudProductService.updateCloudProduct(cloudProduct);
        return "Updated !";
    }

    @DeleteMapping("/{productId}")
    public void removeOne(@PathVariable("productId") String productId) {
        cloudProductService.remove(productId);
    }

    @GetMapping
    public Iterable<CloudProduct> findAll(@RequestParam(value = "isDeleted", required = false, defaultValue = "false") boolean isDeleted) {
        return cloudProductService.findAll(isDeleted);
    }

}
</code>```

My CloudProductService.java :

```<code>package com.proj.my.service;

import com.proj.my.model.CloudProduct;

public interface CloudProductService {

    public String createCloudProduct(CloudProduct cloudProduct);
    public String updateCloudProduct(CloudProduct cloudProduct);
    public CloudProduct getCloudProduct(String cloudProductId);
    public Iterable<CloudProduct> findAll(boolean isDeleted);
    public void remove(String cloudProductId);
}

</code>```

My CloudProductServiceimpl.java :

```<code>package com.proj.my.service.impl;

import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;

import jakarta.persistence.EntityManager;

@Service
public class CloudProductServiceImpl implements CloudProductService
{

    CloudProductRepository cloudProductRepository;

    @Autowired
    private EntityManager entityManager;

    public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {

        this.cloudProductRepository = cloudProductRepository;

    }

    @Override
    public String createCloudProduct(CloudProduct cloudProduct){
        cloudProductRepository.save(cloudProduct);
        return "Success";
    }

    @Override
    public String updateCloudProduct(CloudProduct cloudProduct){
        cloudProductRepository.save(cloudProduct);
        return "Success";
    }

    @Override
    public CloudProduct getCloudProduct(String cloudProductId){
        return cloudProductRepository.findById(cloudProductId).get();
    }

    public void remove(String cloudProductId){
        cloudProductRepository.deleteById(cloudProductId);
    }

    public Iterable<CloudProduct> findAll(boolean isDeleted){
        Session session = entityManager.unwrap(Session.class);
        Filter filter = session.enableFilter("deletedProductFilter");
        filter.setParameter("isDeleted", isDeleted);
        Iterable<CloudProduct> products =  cloudProductRepository.findAll();
        session.disableFilter("deletedProductFilter");
        return products;
    }

}

</code>```

I hope you can help me with this one, THANKS !!!

Title: Soft Deletion with Spring JPA

Body:
I've done a few changes on my code, because now I want to have a soft deletion instead of a normal one.
I would only need a few JPA annotations for this purpose.
I think I got the right idea, but now I can't even run it because it give the following error:
"""Type mismatch: cannot convert from String to Class<?>"""

My CloudProduct.java ( the one with the error ) :

package com.proj.my.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.Id;

import java.sql.Date;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import jakarta.persistence.Table;

@Entity
@Table(name="cloud_product_info")
@SQLDelete(sql = "UPDATE cloud_products_info SET deleted = true WHERE id=?")
@FilterDef(name = "deletedProductFilter", parameters = @ParamDef(name = "isDeleted", type = "boolean"))
@Filter(name = "deletedProductFilter", condition = "deleted = :isDeleted")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
        allowGetters = true)

public class CloudProduct {

    @Id
    private String productId;
    private String productName;
    private String productPrice;
    @CreationTimestamp
    @Column(updatable = false, name = "created_at")
    private Date createdAt;
    private boolean deleted = Boolean.FALSE;

    public Boolean getDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

    public CloudProduct(String productId, String productName, String productPrice, Date createdAt, boolean deleted) {
        this.productId = productId;
        this.productName = productName;
        this.productPrice = productPrice;
        this.createdAt = createdAt;
        this.deleted = deleted;
    }

    public CloudProduct() {

    }

    public String getProductId() {
        return productId;
    }
    public void setProductId(String productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductPrice() {
        return productPrice;
    }
    public void setProductPrice(String productPrice) {
        this.productPrice = productPrice;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
}

The error is implicit on :

@FilterDef(name = "deletedProductFilter", parameters = @ParamDef(name = "isDeleted", type = "boolean"))

Specifically on the "type = "boolean" ".
He is my CloudProductController.java

package com.proj.my.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;

@RestController
@RequestMapping("/cloudproduct")

public class CloudProductController
{

    CloudProductService cloudProductService;

    public CloudProductController(CloudProductService cloudProductService)
    {
        this.cloudProductService = cloudProductService;
    }

    @GetMapping("{productId}")
    public CloudProduct getCloudProductDetails(@PathVariable("productId") String productId){
        return cloudProductService.getCloudProduct(productId);
    }

    @PostMapping
    public String createCloudProductDetails(@RequestBody CloudProduct cloudProduct){

        cloudProductService.createCloudProduct(cloudProduct);
        return "Success";
    }

    @PutMapping
    public String updateCloudProductDetails(@RequestBody CloudProduct cloudProduct){

        cloudProductService.updateCloudProduct(cloudProduct);
        return "Updated !";
    }

    @DeleteMapping("/{productId}")
    public void removeOne(@PathVariable("productId") String productId) {
        cloudProductService.remove(productId);
    }

    @GetMapping
    public Iterable<CloudProduct> findAll(@RequestParam(value = "isDeleted", required = false, defaultValue = "false") boolean isDeleted) {
        return cloudProductService.findAll(isDeleted);
    }

}

My CloudProductService.java :

package com.proj.my.service;

import com.proj.my.model.CloudProduct;

public interface CloudProductService {

    public String createCloudProduct(CloudProduct cloudProduct);
    public String updateCloudProduct(CloudProduct cloudProduct);
    public CloudProduct getCloudProduct(String cloudProductId);
    public Iterable<CloudProduct> findAll(boolean isDeleted);
    public void remove(String cloudProductId);
}

My CloudProductServiceimpl.java :

package com.proj.my.service.impl;

import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;

import jakarta.persistence.EntityManager;

@Service
public class CloudProductServiceImpl implements CloudProductService
{

    CloudProductRepository cloudProductRepository;

    @Autowired
    private EntityManager entityManager;

    public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {

        this.cloudProductRepository = cloudProductRepository;

    }

    @Override
    public String createCloudProduct(CloudProduct cloudProduct){
        cloudProductRepository.save(cloudProduct);
        return "Success";
    }

    @Override
    public String updateCloudProduct(CloudProduct cloudProduct){
        cloudProductRepository.save(cloudProduct);
        return "Success";
    }

    @Override
    public CloudProduct getCloudProduct(String cloudProductId){
        return cloudProductRepository.findById(cloudProductId).get();
    }

    public void remove(String cloudProductId){
        cloudProductRepository.deleteById(cloudProductId);
    }

    public Iterable<CloudProduct> findAll(boolean isDeleted){
        Session session = entityManager.unwrap(Session.class);
        Filter filter = session.enableFilter("deletedProductFilter");
        filter.setParameter("isDeleted", isDeleted);
        Iterable<CloudProduct> products =  cloudProductRepository.findAll();
        session.disableFilter("deletedProductFilter");
        return products;
    }

}

I hope you can help me with this one, THANKS !!!


问:
Version mismatch vite and quasar
Trying to install Quasar on my Vite (Vue 3) project. Getting the following error:

```<code>$ npm install -D @quasar/vite-plugin@latest  sass@1.32.12
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: diop-dash@0.0.0
npm ERR! Found: @vitejs/plugin-vue@4.0.0
npm ERR! node_modules/@vitejs/plugin-vue
npm ERR!   dev @vitejs/plugin-vue@"^4.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @vitejs/plugin-vue@"^2.0.0 || ^3.0.0" from @quasar/vite-plugin@1.2.3
npm ERR! node_modules/@quasar/vite-plugin
npm ERR!   dev @quasar/vite-plugin@"1.2.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
</code>```

From this it looks like quasar's vite plugin is looking for the 2.0.0 or 3.0.0 version of @vitejs/plugin-vue but I have 4.0 installed. Is quasar not compatible with the new one, will I run into trouble if I use the --force flag? Is there another way to resolve this that doesn't involve downgrading my Vite setup?

From package.json

"dependencies": {
  "@quasar/extras": "^1.15.8",
  "pinia": "^2.0.28",
  "quasar": "^2.10.2",
  "vue": "^3.2.45",
  "vue-router": "^4.1.6"
},
"devDependencies": {
  "@quasar/vite-plugin": "^1.2.3",
  "@rushstack/eslint-patch": "^1.1.4",
  "@types/node": "^18.11.12",
  "@vitejs/plugin-vue": "^4.0.0",
  "@vue/eslint-config-prettier": "^7.0.0",
  "@vue/eslint-config-typescript": "^11.0.0",
  "@vue/tsconfig": "^0.1.3",
  "eslint": "^8.22.0",
  "eslint-plugin-vue": "^9.3.0",
  "npm-run-all": "^4.1.5",
  "prettier": "^2.7.1",
  "sass": "^1.32.12",
  "typescript": "~4.7.4",
  "vite": "^4.0.0",
  "vue-tsc": "^1.0.12"
}
```

Title: Version mismatch vite and quasar

Body:
Trying to install Quasar on my Vite (Vue 3) project. Getting the following error:

$ npm install -D @quasar/vite-plugin@latest  sass@1.32.12
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: diop-dash@0.0.0
npm ERR! Found: @vitejs/plugin-vue@4.0.0
npm ERR! node_modules/@vitejs/plugin-vue
npm ERR!   dev @vitejs/plugin-vue@"^4.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @vitejs/plugin-vue@"^2.0.0 || ^3.0.0" from @quasar/vite-plugin@1.2.3
npm ERR! node_modules/@quasar/vite-plugin
npm ERR!   dev @quasar/vite-plugin@"1.2.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

From this it looks like quasar's vite plugin is looking for the 2.0.0 or 3.0.0 version of @vitejs/plugin-vue but I have 4.0 installed. Is quasar not compatible with the new one, will I run into trouble if I use the --force flag? Is there another way to resolve this that doesn't involve downgrading my Vite setup?

From package.json

"dependencies": {
  "@quasar/extras": "^1.15.8",
  "pinia": "^2.0.28",
  "quasar": "^2.10.2",
  "vue": "^3.2.45",
  "vue-router": "^4.1.6"
},
"devDependencies": {
  "@quasar/vite-plugin": "^1.2.3",
  "@rushstack/eslint-patch": "^1.1.4",
  "@types/node": "^18.11.12",
  "@vitejs/plugin-vue": "^4.0.0",
  "@vue/eslint-config-prettier": "^7.0.0",
  "@vue/eslint-config-typescript": "^11.0.0",
  "@vue/tsconfig": "^0.1.3",
  "eslint": "^8.22.0",
  "eslint-plugin-vue": "^9.3.0",
  "npm-run-all": "^4.1.5",
  "prettier": "^2.7.1",
  "sass": "^1.32.12",
  "typescript": "~4.7.4",
  "vite": "^4.0.0",
  "vue-tsc": "^1.0.12"
}


问:
Slack POSTing to response_url only shows a message visible only to me instead of updating or editing original message
My bot responds quickly to a slash command /test and the message is publicly visible in the channel for everyone:

{
  "response_type": "in_channel",
  "text": "Please Wait, Processing..."
}
```
<p>the message the bot sends to the chat</p>
<p>Then I try to respond with <code>response_url</code> The message appears <strong>only for me</strong></p>
<p>screenshot of what I see</p>
<p>I POST the <code>response_url</code> with:</p>
<pre class="lang-json prettyprint-override"><code>{
  "replace_original": "true",
  "text": "This is the result! Thanks for waiting for them"
}
</code>```

It only shows for me as a new message instead of editing/updating the old message

I want it to edit the message the bot sent in the first message, in other words update the message with the result, and for it to be public. I don't know why it only shows for me in a new message instead of updating the message itself?

Body:
My bot responds quickly to a slash command /test and the message is publicly visible in the channel for everyone:

{
  "response_type": "in_channel",
  "text": "Please Wait, Processing..."
}

the message the bot sends to the chat

Then I try to respond with response_url The message appears only for me

screenshot of what I see

I POST the response_url with:

{
  "replace_original": "true",
  "text": "This is the result! Thanks for waiting for them"
}

It only shows for me as a new message instead of editing/updating the old message

I want it to edit the message the bot sent in the first message, in other words update the message with the result, and for it to be public. I don't know why it only shows for me in a new message instead of updating the message itself?


问:
FIO: distribute io_size over time_based runtime
I want to test a volume's ability to handle io request while im doing some operation on that volume.

for this purpose i want fio to send consecutive io requests for 3 minutes and i'll do those operations on the volume while fio sending request, such that requests will be sent while im doing those operation and also after

For this purpose i want to use the attribute time_based = 3 minutes (that is: run_time=180, time_based=true), and finish those operations within 2 minutes so that the operation will be issued while fio sending io requests and also after.

However, the snag is that for some reasons that inherited in those operations this volume can't get io request for more than 3gb, so im using io_size = 3gb , but as stated in time_based documentation:

If set, fio will run for the duration of the runtime specified even if the file(s) are completely read or written. It will simply loop over the same workload as many times as the runtime allows.

I can't allow it to loop and also can't allow it to finish after it sends 3gb cause i need thew operations to be taken in between.

For conclusion:

what Im actually looking for is a way to tell fio to send 3gb workload that evenly distributed over 3 minutes,

so that there will inbound io request in any time within 3 minutes and the total workload will not exceed 3gb.

Thanks


问:
Resources for DAX syntax when using live connection to Power BI
Can anyone provide me with some resources to learn the differences in calculating measures/dimensions using DAX in power BI when using a live connection to the data source? There appears to be some differences in how to calculate with the live connection vs importing a data set and I am interested to learn more on this topic.

Thank you!

For example, I cannot use datediff on the live SSAS connection.


问:
Kafka Message is not consumed by consumer after multiple try same message is consumed and processed
I am using the spring application to post the JSON payload to the Kafka topic. The message has been sent by the producer end, but the consumer is not processing the message the first time. After multiple retries, the same message has been processed

Tying to send the Kafka message through the producer and I am excepting the same message to be consumed by the Kafka consumer

Kafka version 2.13

Producer

```<code>KafkaTemplate<String, Object> kafkaTemplate;

    public void producer(JsonPayload payLoad) {
    try{
        kafkaTemplate.send(kafkaTopic, payLoad);
    }catch(Exception e){
        throw e;
    }
    return;
}
</code>```

Consumer

```<code>@KafkaListener(topics = "${kafka.topics")
public void Listener(Object payLoad) {
    if(payLoad != null) {
        try {
                service.processPayload(payLoad);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I am using the spring application to post the JSON payload to the Kafka topic. The message has been sent by the producer end, but the consumer is not processing the message the first time. After multiple retries, the same message has been processed

Tying to send the Kafka message through the producer and I am excepting the same message to be consumed by the Kafka consumer

Kafka version 2.13

Producer

KafkaTemplate<String, Object> kafkaTemplate;

    public void producer(JsonPayload payLoad) {
    try{
        kafkaTemplate.send(kafkaTopic, payLoad);
    }catch(Exception e){
        throw e;
    }
    return;
}

Consumer

@KafkaListener(topics = "${kafka.topics")
public void Listener(Object payLoad) {
    if(payLoad != null) {
        try {
                service.processPayload(payLoad);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
How to handle variables containing interval values and time series data while pre-processing the dataset
I am trying to prepare a patient dataset for a classification problem using python and I don't know how to handle the interval and time series data while performing pre-processing and data cleaning. Can someone please suggest any method to accurately represent them and use them. Any help is appreciated, thanks in advance.

Here is the example variable:

age_group
Entry_time

16-25
2012-01-01, 00:11

36-45
2012-01-04, 20:23

26-35
2012-02-22, 16:45

I just tried applying one hot encoding on age group variable which has 80+ unique variables and I chose top 10. Not sure if this is a right way.


问:
Sending mail based on filtered list sends blank emails for rows that are filtered out
I have a script that loops through an Excel spreadsheet, groups unique vendors and sends them their past due orders an Outlook email.

I am trying to filter on any specific buyer code in column then run the script.

It will send blank emails to the buyer codes that are filtered out. Is there a way around this? I am guessing there is an issue because of non-contiguous rows?

What the file looks like:

What happens if I filter.

Sub mailstrangejosh()

    Dim OutApp As Object, OutMail As Object
    Dim myRng As Range, v As Variant
    Dim j As Long, lastRow As Long
    Dim strbody As String

    Application.ScreenUpdating = False

    lastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    v = Range("A1:U" & lastRow).Value

    Set OutApp = CreateObject("Outlook.Application")
    With CreateObject("scripting.dictionary")
        For j = 2 To UBound(v)
            If Not .exists(v(j, 2)) Then
                .Add v(j, 2), Nothing

                strbody = " Hello " & v(j, 19) & “,” & "
" & _
"
" & _
                  "Please see below past due order(s) balances and provide a status update when you can. Thank you" & "

"

                With ActiveSheet
                    .Range("A1").AutoFilter 2, v(j, 2)
                    Set myRng = .Range("A1:U" & lastRow).SpecialCells(xlCellTypeVisible)

                    Set OutMail = OutApp.CreateItem(0)
                    With OutMail
                        .To = v(j, 20)
                        .Subject = v(j, 2) & " – PO Balance(s)"
                        .HTMLBody = strbody & RangetoHTML(myRng)
                         .display        'to show
                         '.Send 'to send
                    End With
                End With
            End If
        Next j

    End With

    Range("A1").AutoFilter

    Application.ScreenUpdating = True
End Sub

Function RangetoHTML(myRng As Range)
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook
    Dim i      As Integer

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    myRng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Cells.HorizontalAlignment = xlLeft
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
        For i = 7 To 12
            With .UsedRange.Borders(i)
                .LineStyle = xlContinuous
                .ColorIndex = xlAutomatic
                .TintAndShade = 0
                .Weight = xlMedium
            End With
        Next i
    End With

    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", "align=left x:publishsource=")
RangetoHTML = Replace(RangetoHTML, "display:none", "")

    TempWB.Close savechanges:=False

    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing

End Function
```


问:
Best approach/placeholder for a root container in react for pages using Material UI
I am very new in React and trying to build a dashboard application from scratch switches different pages.

But really stuck with the root container/placeholder for all the different pages.

This is my core template so far

RootContainer.tsx

```<code>import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';

import Drawer from './Drawer';
import AppBar from './AppBar';
import Container from '@mui/material/Container';
import Paper from '@mui/material/Paper';
import RecipeLanding from '../pages/Recipe/RecipeLanding';

export default function RootContainer() {
  const [open, setOpen] = React.useState(false);
  const title="Manage Recipes";
  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };
  const DrawerHeader = styled('div')(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  }));
  const drawerWidth = 240;

  return (
    <Box sx={{ display: 'flex',  flexDirection: 'column', height:'100%'}}>
      <AppBar open={open} onDrawerOpen={handleDrawerOpen}  />
      <Drawer open={open} onDrawerClose={handleDrawerClose} />

        <Container  maxWidth="xl" sx={{  height:'95%'}}  >
        <DrawerHeader />
          <h2>{title}</h2>
          <Paper elevation={1} sx={{bgcolor:"#f7f9ff", height:.9}}>
            <RecipeLanding />
          </Paper>

        </Container>

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

And here is the App.tsx

```<code>import './App.css';
import RootContainer from './layout/RootContainer'

function App() {
  return (
    <RootContainer />
  );
}

export default App;
</code>```

It looks fine when nothing is there in the container and I want it like that. For ultrawide screens the container I am expecting on the center with xl size. The problem I am facing when contents on it. (I made it orange to view the inner container)

With contents

So as you an see the main placeholder stays in its size and the contents overlaps.

I am not sure the approach for root container I did is correct. MUI Box is the best or Grid/Container is better?

Please help

Body:
I am very new in React and trying to build a dashboard application from scratch switches different pages.

But really stuck with the root container/placeholder for all the different pages.

This is my core template so far

RootContainer.tsx

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';

import Drawer from './Drawer';
import AppBar from './AppBar';
import Container from '@mui/material/Container';
import Paper from '@mui/material/Paper';
import RecipeLanding from '../pages/Recipe/RecipeLanding';

export default function RootContainer() {
  const [open, setOpen] = React.useState(false);
  const title="Manage Recipes";
  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };
  const DrawerHeader = styled('div')(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  }));
  const drawerWidth = 240;

  return (
    <Box sx={{ display: 'flex',  flexDirection: 'column', height:'100%'}}>
      <AppBar open={open} onDrawerOpen={handleDrawerOpen}  />
      <Drawer open={open} onDrawerClose={handleDrawerClose} />

        <Container  maxWidth="xl" sx={{  height:'95%'}}  >
        <DrawerHeader />

{title}

          <Paper elevation={1} sx={{bgcolor:"#f7f9ff", height:.9}}>
            <RecipeLanding />
          </Paper>

        </Container>

    </Box>
  );
}

And here is the App.tsx

import './App.css';
import RootContainer from './layout/RootContainer'

function App() {
  return (
    <RootContainer />
  );
}

export default App;

It looks fine when nothing is there in the container and I want it like that. For ultrawide screens the container I am expecting on the center with xl size. The problem I am facing when contents on it. (I made it orange to view the inner container)

With contents

So as you an see the main placeholder stays in its size and the contents overlaps.

I am not sure the approach for root container I did is correct. MUI Box is the best or Grid/Container is better?

Please help


问:
Why can't I log in after upgrading Django from 2.2 to 3.2?
I just upgraded my Django 2.2 project to 3.2, and now I cannot login with any user in the database. I am so confused because I'm not getting any error messages, but continually being redirected to the login page after successfully authenticating and logging in.

Here are the steps that I am taking:

Enter username/password into the login form (works great in 2.2)

The python file uses user = authenticate(username=username, password=password) and then login(request, user)

I can confirm that the username/password are correct, and printing request.user immediately after the login call logs the correct user.

When I inspect the cookies in the browser, a value for sessionid is set.

After successful login, the server sends a redirect to an auth-protected route. However, when getting the protected route, printing the request.user is AnonymousUser, and then I am redirected back to the login page.

This appears to be an issue with the sessions. I can see that the cookies are being set, and even when I manually set the sessionid cookie to be the value returned by request.session.session_key right after the call to login it still does not recognize the authorized user. I have followed the recommendations in the release notes to set DEFAULT_HASHING_ALGORITHM = 'sha1'.

Any ideas as to what is happening? Without any error messages, I am stuck and cannot figure out why I am not able to log in as a user. I have also tried this using sqlite3 and Postgres — same result.


问:
Horrible forecasting KPI scores (RMSE, MAE and MAPE) using RNN with three flavors ("LSTM", "GRU" and "RNN")
My project is trying to forecast COVID 19 total confirmed case for 2021. This is the overlook of the confirm case data, which I use to train my RNN model.
enter image description here
The confirmed number though doesn't show any repeating pattern. But there has been research studies using RNN and LSTM on the same data (in fact, I use the same data source as them). This is the research study I drew inspiration from:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8523546/
This is the result I got:

```<code>
beginning the training of the LSTM RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 33.10it/s, loss=0.115, v_num=logs, train_loss=0.0933, val_loss=0.466]
training of the LSTM RNN completed: 105.23 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  6.48it/s]
LSTM :
MAPE  :  199.3029
RMSPE  :  0.6659
RMSE  :  0.6763
-R squared  :  15366746993394475597824.0000
se  :  0.0871

beginning the training of the GRU RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 37.86it/s, loss=0.11, v_num=logs, train_loss=0.0911, val_loss=0.474]
training of the GRU RNN completed: 90.99 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  3.91it/s]
GRU :
MAPE  :  209.6602
RMSPE  :  0.6771
RMSE  :  0.6877
-R squared  :  467975998695823638528.0000
se  :  0.0871

beginning the training of the Vanilla RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 43.54it/s, loss=0.114, v_num=logs, train_loss=0.109, val_loss=0.461]
training of the Vanilla RNN completed: 79.32 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  6.08it/s]
Vanilla :
MAPE  :  200.5710
RMSPE  :  0.6673
RMSE  :  0.6778
-R squared  :  115942252717688101559392358367232.0000
se  :  0.0871

</code>```

Also, here is my prediction plot. Three of the plot looks exactly the same, different MAPE score:
enter image description here

For the package i use, i use darts (u8darts[all] when importing the packages).
for methodology, I set the parameters for my model as this. I used this article by Heiko Oinen for methodology (detailed code is below the page):
https://medium.com/towards-data-science/temporal-loops-intro-to-recurrent-neural-networks-for-time-series-forecasting-in-python-b0398963dc1f:

```<code>
</code>```

#Set up the models, run the models, plot and evaluate

EPOCH = 100

def run_RNN(flavor, ts, train, val):

```<code>#set the model up
model_RNN = RNNModel(
    model = flavor,
    model_name = flavor + str(" RNN"),
    input_chunk_length = 12,
    training_length = 20,
    hidden_dim = 20,
    batch_size = 16,
    n_epochs = EPOCH,
    dropout = 0,
    optimizer_kwargs = {'lr': 1e-3},
    log_tensorboard = True,
    random_state = 42,
    force_reset = True
)

if flavor == "RNN": flavor = "Vanilla"

#fit the model
fit_it(model_RNN, train, val, flavor)

#compute N predictions
pred = model_RNN.predict(n = FC_N,future_covariates = covariates)

#plot predictions vs actual
plot_fitted(pred, ts, flavor)

#print accuracy metrics
res_acc = accuracy_metrics(pred, ts)
</code>```
```<code></code>```

I have even tries epoch to 300, but the train loss and loss during training didn't decrease further.

I haven't gotten experience in asking questions here, I'll try to articulate and provide more detail if you have questions. Thank you so much for your help!

```<code></code>```

Body:
My project is trying to forecast COVID 19 total confirmed case for 2021. This is the overlook of the confirm case data, which I use to train my RNN model.
enter image description here
The confirmed number though doesn't show any repeating pattern. But there has been research studies using RNN and LSTM on the same data (in fact, I use the same data source as them). This is the research study I drew inspiration from:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8523546/
This is the result I got:

beginning the training of the LSTM RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 33.10it/s, loss=0.115, v_num=logs, train_loss=0.0933, val_loss=0.466]
training of the LSTM RNN completed: 105.23 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  6.48it/s]
LSTM :
MAPE  :  199.3029
RMSPE  :  0.6659
RMSE  :  0.6763
-R squared  :  15366746993394475597824.0000
se  :  0.0871

beginning the training of the GRU RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 37.86it/s, loss=0.11, v_num=logs, train_loss=0.0911, val_loss=0.474]
training of the GRU RNN completed: 90.99 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  3.91it/s]
GRU :
MAPE  :  209.6602
RMSPE  :  0.6771
RMSE  :  0.6877
-R squared  :  467975998695823638528.0000
se  :  0.0871

beginning the training of the Vanilla RNN:
Epoch 99: 100%|██████████| 29/29 [00:00<00:00, 43.54it/s, loss=0.114, v_num=logs, train_loss=0.109, val_loss=0.461]
training of the Vanilla RNN completed: 79.32 sec
Predicting DataLoader 0: 100%|██████████| 1/1 [00:00<00:00,  6.08it/s]
Vanilla :
MAPE  :  200.5710
RMSPE  :  0.6673
RMSE  :  0.6778
-R squared  :  115942252717688101559392358367232.0000
se  :  0.0871

Also, here is my prediction plot. Three of the plot looks exactly the same, different MAPE score:
enter image description here

For the package i use, i use darts (u8darts[all] when importing the packages).
for methodology, I set the parameters for my model as this. I used this article by Heiko Oinen for methodology (detailed code is below the page):
https://medium.com/towards-data-science/temporal-loops-intro-to-recurrent-neural-networks-for-time-series-forecasting-in-python-b0398963dc1f:

#Set up the models, run the models, plot and evaluate

EPOCH = 100

def run_RNN(flavor, ts, train, val):

#set the model up
model_RNN = RNNModel(
    model = flavor,
    model_name = flavor + str(" RNN"),
    input_chunk_length = 12,
    training_length = 20,
    hidden_dim = 20,
    batch_size = 16,
    n_epochs = EPOCH,
    dropout = 0,
    optimizer_kwargs = {'lr': 1e-3},
    log_tensorboard = True,
    random_state = 42,
    force_reset = True
)

if flavor == "RNN": flavor = "Vanilla"

#fit the model
fit_it(model_RNN, train, val, flavor)

#compute N predictions
pred = model_RNN.predict(n = FC_N,future_covariates = covariates)

#plot predictions vs actual
plot_fitted(pred, ts, flavor)

#print accuracy metrics
res_acc = accuracy_metrics(pred, ts)

I have even tries epoch to 300, but the train loss and loss during training didn't decrease further.

I haven't gotten experience in asking questions here, I'll try to articulate and provide more detail if you have questions. Thank you so much for your help!


问:
Mongodb: how to use wildcards in parent and grandparent references to filter a child array?
I am trying to filter multiple arrays under different parent and grandparent field names, BUT reference all grandparents and all parents with a wildcard? Is that possible?

For example I tried the snippet of code below (might have minor syntax errors as I was using pymongo and dropped the quotes). Anything I could find on wildcards was from indexing.

Any suggestions of what functions to use would be helpful. A side thought: I was thinking if it would be better to transform the jsons via XSLT before loading them into mongodb...

Thanks!

Original data

```<code>{
   "objects": {
      "superparent1a": {"parent1a_xyz": [{"name": "child1a1", "value": 10, "valid": "true"},
                                         {"name": "child1b2", "value": 4, "valid": "false"},
                                         {"name": "child1c3", "value": 5, "valid": "false"}]},

      "superparent1b": {"parent1b_tuv": [{"name": "child1b1", "value": 100, "valid": "true"},
                                         {"name": "child1b2", "value": 40, "valid": "false"},
                                         {"name": "child1b3", "value": 50, "valid": "false"}]}

   }
}
</code>```

Target output

```<code>{
   "objects": {
      "superparent1a": {"parent1a_xyz": [{"name": "child1a1", "value": 10, "valid": "true"}]},
      "superparent1b": {"parent1b_tuv": [{"name": "child1b1", "value": 100, "valid": "true"}]}
   }
}
</code>```

Snip-it of code in the aggregate function. I just got syntax errors, but couldn't find if there was a way to even do this

```<code>{$filter: {input: objects.**.**,
           as: c_var,
           cond: {$eq: [$$c_var.valid, "true"]}
          }
}
</code>```

Body:
I am trying to filter multiple arrays under different parent and grandparent field names, BUT reference all grandparents and all parents with a wildcard? Is that possible?

For example I tried the snippet of code below (might have minor syntax errors as I was using pymongo and dropped the quotes). Anything I could find on wildcards was from indexing.

Any suggestions of what functions to use would be helpful. A side thought: I was thinking if it would be better to transform the jsons via XSLT before loading them into mongodb...

Thanks!

Original data

{
   "objects": {
      "superparent1a": {"parent1a_xyz": [{"name": "child1a1", "value": 10, "valid": "true"},
                                         {"name": "child1b2", "value": 4, "valid": "false"},
                                         {"name": "child1c3", "value": 5, "valid": "false"}]},

      "superparent1b": {"parent1b_tuv": [{"name": "child1b1", "value": 100, "valid": "true"},
                                         {"name": "child1b2", "value": 40, "valid": "false"},
                                         {"name": "child1b3", "value": 50, "valid": "false"}]}

   }
}

Target output

{
   "objects": {
      "superparent1a": {"parent1a_xyz": [{"name": "child1a1", "value": 10, "valid": "true"}]},
      "superparent1b": {"parent1b_tuv": [{"name": "child1b1", "value": 100, "valid": "true"}]}
   }
}

Snip-it of code in the aggregate function. I just got syntax errors, but couldn't find if there was a way to even do this

{$filter: {input: objects.**.**,
           as: c_var,
           cond: {$eq: [$$c_var.valid, "true"]}
          }
}


问:
Handling refreshing a Cognito Token after it expires in NodeJS/Express
I would like to preface that I while I have setup a JWT access token system before, it was years ago and I don't exactly remember how we had it setup (At the time, I was more directed to code it a certain way, but it wasn't explained in any detail what I was doing.). And it was it's own system. It did not interact with Cognito.

Thus I'm trying to take what I do remember and use it to incorporate Cognito with a application I'm making.

The main question, is how do I implement refreshing a users token?

I get the general idea. At some point in the process the refresh token is sent to AWS, and if it hasn't expired it will spit back a new auth token for the user.  Just not sure where/when it makes the most sense to do it.

As my setup stands, users are sent to the standard AWS login page, that then sends them to my login page with a code. The login page sends this code to AWS, which spits back the needed tokens. They are then stored in the users local storage. Then it sends the user to what ever homepage their role is set for.

From here on out, I have the auth token sent to any api requests and is validated.

Should I be checking the auth token on the front end first and if it expires use the refresh token, or would is it expected I send the refresh token in my api requests? I also want to eventually have it automatically redirect someone to the login page if the refresh token has expired.

If it helps here is the code I use to get the tokens on the login page:

```<code>async function getTokens(code) {
    let encodedId = await requestJSON('get',['apiv1', 'auth', 'encodedId']);

    var myHeaders = new Headers();
    myHeaders.append("Authorization", `Basic ${encodedId['id']}`);
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    myHeaders.append("Cookie", "XSRF-TOKEN=<xsrf-token-here>"); //I hid my actual token with a place holder

    var urlencoded = new URLSearchParams();
    urlencoded.append("code", code);
    urlencoded.append("grant_type", "authorization_code");
    urlencoded.append("client_id", Cognito.ClientId);
    urlencoded.append("redirect_uri", "http://localhost:3000/login"); // Todo: set dynamically

    var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: urlencoded,
    redirect: 'follow'
    };

    return fetch("https://scriptel-web-sign.auth.us-east-1.amazoncognito.com/oauth2/token", requestOptions);
}
</code>```

And the code that checks the token is valid in the backend

```<code>function isValidAuth(req, groups =[]) {
    if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== "Bearer") {
        return false;
    };

    const token = req.headers.authorization.split(' ')[1];

    cognitoExpress.validate(token, (err) => {
        if(err) { return false};
    });

    //check groups
    let userGroups = getGroups(token);

    for (let i = 0; i < groups.length; i++) {
        let group = groups[i];

        if (!userGroups.includes(group)) {
            return false;
        };
    };

    return true;
};
</code>```

Let me know if there is anything confusing/out right wrong about my current logic. Thanks in advance for any help.

Body:
I would like to preface that I while I have setup a JWT access token system before, it was years ago and I don't exactly remember how we had it setup (At the time, I was more directed to code it a certain way, but it wasn't explained in any detail what I was doing.). And it was it's own system. It did not interact with Cognito.

Thus I'm trying to take what I do remember and use it to incorporate Cognito with a application I'm making.

The main question, is how do I implement refreshing a users token?

I get the general idea. At some point in the process the refresh token is sent to AWS, and if it hasn't expired it will spit back a new auth token for the user.  Just not sure where/when it makes the most sense to do it.

As my setup stands, users are sent to the standard AWS login page, that then sends them to my login page with a code. The login page sends this code to AWS, which spits back the needed tokens. They are then stored in the users local storage. Then it sends the user to what ever homepage their role is set for.

From here on out, I have the auth token sent to any api requests and is validated.

Should I be checking the auth token on the front end first and if it expires use the refresh token, or would is it expected I send the refresh token in my api requests? I also want to eventually have it automatically redirect someone to the login page if the refresh token has expired.

If it helps here is the code I use to get the tokens on the login page:

async function getTokens(code) {
    let encodedId = await requestJSON('get',['apiv1', 'auth', 'encodedId']);

    var myHeaders = new Headers();
    myHeaders.append("Authorization", `Basic ${encodedId['id']}`);
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    myHeaders.append("Cookie", "XSRF-TOKEN=<xsrf-token-here>"); //I hid my actual token with a place holder

    var urlencoded = new URLSearchParams();
    urlencoded.append("code", code);
    urlencoded.append("grant_type", "authorization_code");
    urlencoded.append("client_id", Cognito.ClientId);
    urlencoded.append("redirect_uri", "http://localhost:3000/login"); // Todo: set dynamically

    var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: urlencoded,
    redirect: 'follow'
    };

    return fetch("https://scriptel-web-sign.auth.us-east-1.amazoncognito.com/oauth2/token", requestOptions);
}

And the code that checks the token is valid in the backend

function isValidAuth(req, groups =[]) {
    if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== "Bearer") {
        return false;
    };

    const token = req.headers.authorization.split(' ')[1];

    cognitoExpress.validate(token, (err) => {
        if(err) { return false};
    });

    //check groups
    let userGroups = getGroups(token);

    for (let i = 0; i < groups.length; i++) {
        let group = groups[i];

        if (!userGroups.includes(group)) {
            return false;
        };
    };

    return true;
};

Let me know if there is anything confusing/out right wrong about my current logic. Thanks in advance for any help.


问:
Why is it that I can not capture the new value after my button is click?
I am still pretty new to JavaScript. I have a script that will click on a next Month button and I want it to capture the new Header value. Why is it that it still capture the value before the button was click? I want to use the script to to trigger the button and for it to capture the new value as well.

I tried to use the eventListener and dispatchEvent but maybe I am not using it correctly.

```<code>var CalandarMonthValue = document.getElementsByClassName('CalandarMonth')[0];
let NextMonthButton = document.getElementsByClassName('NextMonthButton')[0];

function triggerChange(element){
    let changeEvent = new Event("change");
    element.dispatchEvent(changeEvent)
}

console.log("Current Month: "+ CalandarMonthValue);

NextMonthButton.click();
NextMonthButton.addEventListener("click"),()=> {
    triggerChange(CalandarMonthValue)
});

CalandarMonthValue = document.getElementsByClassName('CalandarMonth')[0];
console.log("New Month: "+ CalendarMonthValue.textContent);
</code>```

the output I am getting is this:

```<code>Current Month: December
New Month: December
</code>```

Body:
I am still pretty new to JavaScript. I have a script that will click on a next Month button and I want it to capture the new Header value. Why is it that it still capture the value before the button was click? I want to use the script to to trigger the button and for it to capture the new value as well.

I tried to use the eventListener and dispatchEvent but maybe I am not using it correctly.

var CalandarMonthValue = document.getElementsByClassName('CalandarMonth')[0];
let NextMonthButton = document.getElementsByClassName('NextMonthButton')[0];

function triggerChange(element){
    let changeEvent = new Event("change");
    element.dispatchEvent(changeEvent)
}

console.log("Current Month: "+ CalandarMonthValue);

NextMonthButton.click();
NextMonthButton.addEventListener("click"),()=> {
    triggerChange(CalandarMonthValue)
});

CalandarMonthValue = document.getElementsByClassName('CalandarMonth')[0];
console.log("New Month: "+ CalendarMonthValue.textContent);

the output I am getting is this:

Current Month: December
New Month: December


问:
How to make flutter audio_players library works fine on web?
I am developing a Flutter App that has sound effects when dragging and dropping some widgets; when I was testing it on localhost web and mobile devices, everything works fine; but once I've deployed it on a remote web server, sounds won't play as they're suppossed to:

Sometimes, it just takes a while to load and then it would play fine.

Sometimes, it takes A LOT, by this I mean, sound would play 10 or 20 seconds after widget was pressed.

Sometimes, it won't play any sound and just show this error on console: ´

The implementation is just as told on the documentation, already tested with local assets and with URL sounds too.

How can I make it work fine on web ?

RELEVANT CODE

```<code>import 'package:audioplayers/audioplayers.dart';

class _ResultsScreenState extends State<ResultsScreen>
    with SingleTickerProviderStateMixin {

    final player = AudioPlayer();

    @override
    Widget build(BuildContext context) {
       player.setReleaseMode(ReleaseMode.stop);
       playDrums();
    }

   playDrums() async {
    drumsArePlaying = true;
    await player.play(AssetSource('sounds/drumroll.wav'));
  }
}

</code>```

Body:
I am developing a Flutter App that has sound effects when dragging and dropping some widgets; when I was testing it on localhost web and mobile devices, everything works fine; but once I've deployed it on a remote web server, sounds won't play as they're suppossed to:

Sometimes, it just takes a while to load and then it would play fine.

Sometimes, it takes A LOT, by this I mean, sound would play 10 or 20 seconds after widget was pressed.

Sometimes, it won't play any sound and just show this error on console: ´

The implementation is just as told on the documentation, already tested with local assets and with URL sounds too.

How can I make it work fine on web ?

RELEVANT CODE

import 'package:audioplayers/audioplayers.dart';

class _ResultsScreenState extends State<ResultsScreen>
    with SingleTickerProviderStateMixin {

    final player = AudioPlayer();

    @override
    Widget build(BuildContext context) {
       player.setReleaseMode(ReleaseMode.stop);
       playDrums();
    }

   playDrums() async {
    drumsArePlaying = true;
    await player.play(AssetSource('sounds/drumroll.wav'));
  }
}


问:
How to set the CDC Path of a dms-endpoint of type S3
It appears there is a new property on a source dms endpoint when it is of type s3 bucket. In the image below, there is a CDC Path property, apparently on the endpoint itself. This does not appear to come from --s3-settings CdcPath or the --extra-connection-attributes CdcPath. I have set both values via modify-endpoint route and the CDC Path property remains blank.

Here is what appears to be a new CDC Path property

It is somewhat difficult to assertain, however, I feel that these are from the --s3-settings

And finally, I feel these are being depreciated or at least compressionType has been. These are the --extra-connection-attributes

When I attempt to attach this dms-endpoint as a source to a dms-replication-task, I keep getting an invalid ARN.

When I flip over to an environemsnt where I have write access and enter a value for the CDC Path, seen in the first image, then this endpoint can be used as a source for a replication task.

I am confused perhaps the documentation is stale or else I am missing something.

How to update the CDC Path in the first image from cli?

Would the lack of a value here cause a source endpoint of type s3 from being able to be attached to a dms-replication-task?


问:
Java JPMS: `package xxx is not visible`
I have a simple Java project using the non-modularized dependency "io.prometheus:simpleclient_hotspot:0.16.0". It has been working fine until, for other reasons, I wanted to use the Java module system and add a module-info.java to my project. Once I do that, I start getting the compilation error:

```<code>error: package io.prometheus.client is not visible import io.prometheus.client.CollectorRegistry;
                    ^   (package io.prometheus.client is declared in the unnamed module, but module simpleserver does not read it)
</code>```

The prometheus client library isn't modularized, so it is called an "unnamed module". How do I get access to the packages of such a library? I assume I add a dependency in my module-info.java?

This seems like a basic, common JPMS newbie issue, but after doing lots of searches I can't find the solution to this issue.

Title: Java JPMS: `package xxx is not visible`

Body:
I have a simple Java project using the non-modularized dependency "io.prometheus:simpleclient_hotspot:0.16.0". It has been working fine until, for other reasons, I wanted to use the Java module system and add a module-info.java to my project. Once I do that, I start getting the compilation error:

error: package io.prometheus.client is not visible import io.prometheus.client.CollectorRegistry;
                    ^   (package io.prometheus.client is declared in the unnamed module, but module simpleserver does not read it)

The prometheus client library isn't modularized, so it is called an "unnamed module". How do I get access to the packages of such a library? I assume I add a dependency in my module-info.java?

This seems like a basic, common JPMS newbie issue, but after doing lots of searches I can't find the solution to this issue.


问:
open new fragment for different urls in webview without getting Url (web page) loaded in previous fragment
I am making a webview Application in which I want to set header and footer in native and rest middle part in webview. so for setting different header and footer for different pages I want to load different fragments for different url.

what I am doing is that I have taken one url loaded webview for it in fragment using loadUrl() and then check the url pattern and opened different fragment for it.

But the problem I am facing is that when in current fragment say F1 having some item list, I am clicking on any one item I get the url using doUpdateVisitedHistory() and then loading the item details in new fragment say F2 using url catched in doUpdateVisitedHistory() but when returning back to previous fragment F1 from F2 that particular item details are also getting open in F1 but what I want is that item details only get opened in F2 when url is hit and when coming back on F1 from F2, F1 remains the same as it was before the item was clicked containg items list i.e. item details don't get loaded in F1.

For solving this issue:

I have tried to catch the url in shouldOverrideUrlLoading() function of webview but the url is not getting catched in that particular function so not able to stop loading of url in current fragment.

I have also tried webview.stoploading() for this but its also not working.

So how can I stop loading url in current fragment and open new fragment for it leaving the current fragment as it is...


问:
How to stop Screen Space Overlay canvas from blocking UI button presses on World Space canvas?
I'm using Unity 2022.1.23f1 and the Universal Render Pipeline. I have a render texture, set to 480x270 with point filtering, to get a cool pixelated effect. In my scenes, I output the camera into the pixelated render texture and render it in a raw image under a Screen Space Overlay canvas. This makes it so that everything is rendered in 480x270.

Everything worked perfectly fine in the main gameplay, as there aren't any UI buttons to press. However, in my main menu scene I have three UI buttons for starting the game, accessing the options menu and quitting the game. The main menu is in 3D, featuring a desk with a monitor on it. I thought it would be cool to have the UI buttons look like they're on the monitor, which is why I made a World Space canvas, where I positioned the three UI buttons on the monitor.

I thought it would be easy to make the buttons interactable, but they don't work. I'm sure it's because the pixelation effect is blocking the UI buttons on the World Space canvas.

I removed the pixelation effect, along with the Screen Space Overlay canvas which holds it, and the buttons worked perfectly.

I googled the problem and found someone saying to remove the Graphic Raycaster component in the Scren Space Overlay Canvas, but that didn't work. I also turned off "Raycast Target" in the pixelation effect's raw image gameobject, but that also didn't work.

Is there any way to make it so that I can interact with the UI buttons in the World Space canvas, while also having the Screen Space Overlay canvas with the pixelation effect? Any help - or even suggestions to make a better pixelation effect - would be appreciated!


问:
Custom Date Component ( input ) and useRef
I'm using a custom date component for my project which has a label and an Input tag. I'm using Chakra UI as component library. I have used 3 useRef hooks to specify the ref value for date component. When I press Enter after user has input the value and pressed Enter, the focus should navigate to next input box, I want the same functionality as tab but using the Enter key. I'm also wrapping my DateComponent in forward ref.

```<code>const ref1 = useRef();
const ref2 = useRef();
const ref3 = useRef();

const handleKeyPress = (event) => {
   if(event.key === 'Enter') ref2.current.focus();
}

<Box>
  <DateComponent ref={ref1} onKeyPress={handleKeyPress}/>
  <DateComponent ref={ref2} onKeyPress={handleKeyPress}/>
  <DateComponent ref={ref3} onKeyPress={handleKeyPress}/>
</Box>
</code>```

This doesn't work for me, as the current value of ref2 is showing null in console.

Body:
I'm using a custom date component for my project which has a label and an Input tag. I'm using Chakra UI as component library. I have used 3 useRef hooks to specify the ref value for date component. When I press Enter after user has input the value and pressed Enter, the focus should navigate to next input box, I want the same functionality as tab but using the Enter key. I'm also wrapping my DateComponent in forward ref.

const ref1 = useRef();
const ref2 = useRef();
const ref3 = useRef();

const handleKeyPress = (event) => {
   if(event.key === 'Enter') ref2.current.focus();
}

<Box>
  <DateComponent ref={ref1} onKeyPress={handleKeyPress}/>
  <DateComponent ref={ref2} onKeyPress={handleKeyPress}/>
  <DateComponent ref={ref3} onKeyPress={handleKeyPress}/>
</Box>

This doesn't work for me, as the current value of ref2 is showing null in console.


问:
set mini page in account to show contacts
how can I configure the mini page in Account to show Contacts instead of cases and opportunities?
enter image description here

hope you can help me

I already tried to modify the mini page


问:
How to use Doxygen with Mermaid diagrams embedded in markdown document content?
Example: README.md

```<code># Objective
How can Doxygen generate content that includes Mermaid diagrams embedded in GitHub markdown files (*.md)?

# Mermaid Diagram
```mermaid
sequenceDiagram
    Alice->>John: Hello John, how are you?
    John-->>Alice: Great!
    Alice-)John: See you later!
```

# PlantUML Diagram
PlantUml works well with Doxygen.  Thank you!

```plantuml
@startuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response

Alice -> Bob: Another authentication Request
Alice <-- Bob: Another authentication Response
@enduml
```
</code>```

The goal is to NOT have to create standalone Mermaid diagram files (*.mdd) and reference from a markdown document.

The goal is to use Mermaid like PlantUml can be used with Doxygen.  PlantUml works great with Doxygen.  However, Mermaid has an advantage that it is rendered in browser when a markdown document is viewed in GitLab, Azure DevOps Wiki and VS Code markdown preview.

Azure DevOps git is not supported unfortunately] (Vote here).

Mermaid has a disadvantage compared to PlantUml since diagrams are not created from markdown files included in Doxygen.

I expect this may be a challenging since Mermaid uses browser side rendering.

Thank in advance for any tips on using Mermaid with Doxygen.

Body:
Example: README.md

# Objective
How can Doxygen generate content that includes Mermaid diagrams embedded in GitHub markdown files (*.md)?

# Mermaid Diagram
```mermaid
sequenceDiagram
    Alice->>John: Hello John, how are you?
    John-->>Alice: Great!
    Alice-)John: See you later!
```

# PlantUML Diagram
PlantUml works well with Doxygen.  Thank you!

```plantuml
@startuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response

Alice -> Bob: Another authentication Request
Alice <-- Bob: Another authentication Response
@enduml
```

The goal is to NOT have to create standalone Mermaid diagram files (*.mdd) and reference from a markdown document.

The goal is to use Mermaid like PlantUml can be used with Doxygen.  PlantUml works great with Doxygen.  However, Mermaid has an advantage that it is rendered in browser when a markdown document is viewed in GitLab, Azure DevOps Wiki and VS Code markdown preview.

Azure DevOps git is not supported unfortunately] (Vote here).

Mermaid has a disadvantage compared to PlantUml since diagrams are not created from markdown files included in Doxygen.

I expect this may be a challenging since Mermaid uses browser side rendering.

Thank in advance for any tips on using Mermaid with Doxygen.