问:
TypeError: cannot pickle '_io.BufferedReader' object when sending e-mail with Django-mailer and Djoser

The problem

I'm trying to send a Djoser user's activation email using django-mailer.

However, I receive the following error:

TL;DR:

```<code>TypeError: cannot pickle '_io.BufferedReader' object
</code>```

FULL:

```<code>Traceback (most recent call last):
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create
    settings.EMAIL.activation(self.request, context).send(to)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send
    super(BaseEmailMessage, self).send(*args, **kwargs)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages
    messages = Message.objects.bulk_create([
                                           ^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp>
    Message(email=email) for email in email_messages
    ^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__
    _setattr(self, prop, value)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email
    self.message_data = email_to_db(val)
                        ^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db
    return base64_encode(pickle.dumps(email)).decode('ascii')
                         ^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle '_io.BufferedReader' object
Internal Server Error: /api/auth/users/
Traceback (most recent call last):
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create
    settings.EMAIL.activation(self.request, context).send(to)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send
    super(BaseEmailMessage, self).send(*args, **kwargs)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages
    messages = Message.objects.bulk_create([
                                           ^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp>
    Message(email=email) for email in email_messages
    ^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__
    _setattr(self, prop, value)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email
    self.message_data = email_to_db(val)
                        ^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db
    return base64_encode(pickle.dumps(email)).decode('ascii')
                         ^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle '_io.BufferedReader' object
</code>```

Libraries and versions used (Python 3.11):

```<code> "djangorestframework==3.14.0",
 "dj-database-url==1.0.0",
 "psycopg2-binary==2.9.5",
 "django-cors-headers==3.13.0",
 "gunicorn==20.1.0",
 "pyjwt==2.6.0",
 "python-dotenv==0.21.0",
 "djoser==2.1.0",
 "djangorestframework-simplejwt==4.8.0",
 "django-mailer==2.1",
</code>```

What I've already tried:

I found this related issue on Djoser's Github. However resolution support with django-mailer in version 2.1 didn't work around here.

Related issue: https://github.com/sunscrapers/djoser/issues/609

Body:
The problem

I'm trying to send a Djoser user's activation email using django-mailer.

However, I receive the following error:

TL;DR:

TypeError: cannot pickle '_io.BufferedReader' object

FULL:

Traceback (most recent call last):
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create
    settings.EMAIL.activation(self.request, context).send(to)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send
    super(BaseEmailMessage, self).send(*args, **kwargs)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages
    messages = Message.objects.bulk_create([
                                           ^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp>
    Message(email=email) for email in email_messages
    ^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__
    _setattr(self, prop, value)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email
    self.message_data = email_to_db(val)
                        ^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db
    return base64_encode(pickle.dumps(email)).decode('ascii')
                         ^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle '_io.BufferedReader' object
Internal Server Error: /api/auth/users/
Traceback (most recent call last):
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create
    settings.EMAIL.activation(self.request, context).send(to)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send
    super(BaseEmailMessage, self).send(*args, **kwargs)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages
    messages = Message.objects.bulk_create([
                                           ^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp>
    Message(email=email) for email in email_messages
    ^^^^^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__
    _setattr(self, prop, value)
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email
    self.message_data = email_to_db(val)
                        ^^^^^^^^^^^^^^^^
  File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db
    return base64_encode(pickle.dumps(email)).decode('ascii')
                         ^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle '_io.BufferedReader' object

Libraries and versions used (Python 3.11):

 "djangorestframework==3.14.0",
 "dj-database-url==1.0.0",
 "psycopg2-binary==2.9.5",
 "django-cors-headers==3.13.0",
 "gunicorn==20.1.0",
 "pyjwt==2.6.0",
 "python-dotenv==0.21.0",
 "djoser==2.1.0",
 "djangorestframework-simplejwt==4.8.0",
 "django-mailer==2.1",

What I've already tried:

I found this related issue on Djoser's Github. However resolution support with django-mailer in version 2.1 didn't work around here.

Related issue: https://github.com/sunscrapers/djoser/issues/609


来源: stackexchange

问:
The Ionic inAppbrowser screen is blank on IOS
If I try to build my app for iOS on Ionic in inAppbrowser, remote webpage is a blank screen.
I 'm opening a remote webpage in ionic webview. the main error is occurring here. however, things are working fine in android without any issues.

here is my code
var browser = InAppBrowser.create( wpcDomain + 'checkout/?id='+user.id+'&cookie='+user.cookie+'&add-to-cart='+ _cartIds.join(',') +'&quantity='+ quantity.join(',')+${getIdsForCheckout(variation_ids, 'variation_id')}+'&wpc_mobile_checkout=true', "_blank", InAppBrowserOptions );

```<code>    if(browser){
        browser.on('loadstop')?.subscribe(event => {
            browser.executeScript({
                code: "if(window.location.href.includes('wpc_mobile_thankyou=true')){  var x = document.getElementsByClassName('wpc-primary'); x[0].addEventListener('click', function(){ window.webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify({message: 'fdafda'})) })};"
            },
            function(values) {
            });
        });

        browser.on('loadstart', loadStartCallBack);
        function loadStartCallBack() {

            document.querySelector('body').html("Loading please wait ...");

        }

        browser.on('message')?.subscribe((event) => {
            browser.close();
            browser = undefined;
            router.push('/order-history');
            EmptyCart({dispatch});
        })
    }
</code>```

Here is the issue-

To Native Cordova -> InAppBrowser open InAppBrowser168748626 ["options": [https://demo.cafeapp.com/apps/app/checkout/?id=10&wpc_mobile_checkout=true, _blank, location=no,zoom=no,hideurlbar=yes,closebuttoncaption=Close,clearcache=yes,animated=no]] 2022-12-13 09:52:20.288260+0600 App[16431:563704] Setting the WebView's frame to {{0, 0}, {414, 852}} 2022-12-13 09:52:20.849213+0600 App[16431:563704] Unbalanced calls to begin/end appearance transitions for <UIViewController: 0x140d310f0>.

ContentLicense: CC BY-SA 4.0

Body:
If I try to build my app for iOS on Ionic in inAppbrowser, remote webpage is a blank screen.
I 'm opening a remote webpage in ionic webview. the main error is occurring here. however, things are working fine in android without any issues.

here is my code
var browser = InAppBrowser.create( wpcDomain + 'checkout/?id='+user.id+'&cookie='+user.cookie+'&add-to-cart='+ _cartIds.join(',') +'&quantity='+ quantity.join(',')+${getIdsForCheckout(variation_ids, 'variation_id')}+'&wpc_mobile_checkout=true', "_blank", InAppBrowserOptions );

    if(browser){
        browser.on('loadstop')?.subscribe(event => {
            browser.executeScript({
                code: "if(window.location.href.includes('wpc_mobile_thankyou=true')){  var x = document.getElementsByClassName('wpc-primary'); x[0].addEventListener('click', function(){ window.webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify({message: 'fdafda'})) })};"
            },
            function(values) {
            });
        });

        browser.on('loadstart', loadStartCallBack);
        function loadStartCallBack() {

            document.querySelector('body').html("Loading please wait ...");

        }

        browser.on('message')?.subscribe((event) => {
            browser.close();
            browser = undefined;
            router.push('/order-history');
            EmptyCart({dispatch});
        })
    }

Here is the issue-

To Native Cordova -> InAppBrowser open InAppBrowser168748626 ["options": [https://demo.cafeapp.com/apps/app/checkout/?id=10&wpc_mobile_checkout=true, _blank, location=no,zoom=no,hideurlbar=yes,closebuttoncaption=Close,clearcache=yes,animated=no]] 2022-12-13 09:52:20.288260+0600 App[16431:563704] Setting the WebView's frame to {{0, 0}, {414, 852}} 2022-12-13 09:52:20.849213+0600 App[16431:563704] Unbalanced calls to begin/end appearance transitions for <UIViewController: 0x140d310f0>.


问:
Nginx: host not found in upstream
am using nginx in ubuntu 20.04.05 LTS and reverse proxy with following configuration for my domain

```<code>server{
listen 80;
listen [::]:80;
server_name mydomain.com www.mydomain.com;
return 301 **https**://mydomain.com$request_uri;
location / {
proxy_pass **http**://mydomain.com:3000/;
include proxy_params;
}
}

server{
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /etc/nginx/ssl/certificate.key;
ssl_certificate_key /etc/nginx/ssl/security.key;
server_name mydomain.com www.mydomain.com;

location / {
proxy_pass **http**://mydomain.com:3000/;
include proxy_params;
}

}
</code>```

Used sudo systemctl enable nginx  for autostart for nginx. when machine reboot. host not found in upstream "mydomain.com"(getting error when i check status of nginx)
This error is getting only when machine restart nginx automatically . If I start manually its working perfectly.

I checked sudo nginx -t there also showing successful. Please share idea like why its showing error in auto restart.

Title: Nginx: host not found in upstream

Body:
am using nginx in ubuntu 20.04.05 LTS and reverse proxy with following configuration for my domain

server{
listen 80;
listen [::]:80;
server_name mydomain.com www.mydomain.com;
return 301 **https**://mydomain.com$request_uri;
location / {
proxy_pass **http**://mydomain.com:3000/;
include proxy_params;
}
}

server{
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /etc/nginx/ssl/certificate.key;
ssl_certificate_key /etc/nginx/ssl/security.key;
server_name mydomain.com www.mydomain.com;

location / {
proxy_pass **http**://mydomain.com:3000/;
include proxy_params;
}

}

Used sudo systemctl enable nginx  for autostart for nginx. when machine reboot. host not found in upstream "mydomain.com"(getting error when i check status of nginx)
This error is getting only when machine restart nginx automatically . If I start manually its working perfectly.

I checked sudo nginx -t there also showing successful. Please share idea like why its showing error in auto restart.


问:
VB.NET winform change datetime picker control to a US calendar style
I'm writing a vb app that has its region set to Japan but I would like the datetime picker to use the US format.

```<code>   Dim USCultureInfo As CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-US")
   DateTimePicker1.Format = DateTimePickerFormat.Custom
   Dim formats As String() = DateTimePicker1.Value.GetDateTimeFormats(USCultureInfo)
   DateTimePicker1.CustomFormat = formats(9)
</code>```

This will give me the US formatting but when I click on the calendar it still shows the Japanese calendar.
Does anyone know how to get the whole control to be in US format?

Body:
I'm writing a vb app that has its region set to Japan but I would like the datetime picker to use the US format.

   Dim USCultureInfo As CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-US")
   DateTimePicker1.Format = DateTimePickerFormat.Custom
   Dim formats As String() = DateTimePicker1.Value.GetDateTimeFormats(USCultureInfo)
   DateTimePicker1.CustomFormat = formats(9)

This will give me the US formatting but when I click on the calendar it still shows the Japanese calendar.
Does anyone know how to get the whole control to be in US format?


问:
Errors in p4est and cmake when install dealii
Can anyone help me with this issue?

In order to use dealii, I tried to install p4est using the command

```<code>./configure && make && make install
</code>```

and

```<code>cmake .. -DP4EST_DIR=/usr/local -DDEAL_II_WITH_P4EST=ON -DDEAL_II_WITH_MPI=ON -DCMAKE_INSTALL_PREFIX=/usr/local
</code>```

under "build" folder, but some error occurs.

I also opened the file dealii-9.0.0/build/CMakeFiles/CMakeError.log, it says:

```<code>Source file was:
int main() { return 0; }

Performing C++ SOURCE FILE Test rt_LIBRARY failed with the following output:
Change Dir: /Users/chuxiaoyun/Downloads/dealii-9.0.0/build/CMakeFiles/CMakeScratch/TryCompile-Fscvq9

Run Build Command(s):/usr/bin/make -f Makefile cmTC_bc7f9/fast && /Applications/Xcode.app/Contents/Developer/usr/bin/make  -f CMakeFiles/cmTC_bc7f9.dir/build.make CMakeFiles/cmTC_bc7f9.dir/build
Building CXX object CMakeFiles/cmTC_bc7f9.dir/src.cxx.o
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -Drt_LIBRARY  -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk -mmacosx-version-min=11.6 -MD -MT CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -MF CMakeFiles/cmTC_bc7f9.dir/src.cxx.o.d -o CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -c /Users/chuxiaoyun/Downloads/dealii-9.0.0/build/CMakeFiles/CMakeScratch/TryCompile-Fscvq9/src.cxx
Linking CXX executable cmTC_bc7f9
/opt/homebrew/Cellar/cmake/3.25.0/bin/cmake -E cmake_link_script CMakeFiles/cmTC_bc7f9.dir/link.txt --verbose=1
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk -mmacosx-version-min=11.6 -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -o cmTC_bc7f9  -lrt
ld: library not found for -lrt
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [cmTC_bc7f9] Error 1
make: *** [cmTC_bc7f9/fast] Error 2
</code>```
```<code>CMake Error at cmake/macros/macro_configure_feature.cmake:112 (MESSAGE):

  Could not find the p4est library!

  Insufficient p4est installation found!

  p4est has to be configured with MPI enabled.

  Please ensure that a suitable p4est library is installed on your computer.

  If the library is not at a default location, either provide some hints for
  autodetection,

      $ P4EST_DIR="..." cmake <...>
      $ cmake -DP4EST_DIR="..." <...>

  or set the relevant variables by hand in ccmake.
  Call Stack (most recent call first):
  cmake/macros/macro_configure_feature.cmake:269 (FEATURE_ERROR_MESSAGE)
  cmake/configure/configure_p4est.cmake:78 (CONFIGURE_FEATURE)
  cmake/macros/macro_verbose_include.cmake:19 (INCLUDE)
  CMakeLists.txt:124 (VERBOSE_INCLUDE)
</code>```

I guess I haven't installed p4est correctly, so I configure it again.

```<code>#  p4est-2.8 ./configure --enable-mpi.
</code>```

( Here shows we are using MPI. I also tried p4est-2.8  ./configure --enable-mpi --prefix=/usr/local)

Then I tried to build and install p4est, but it gives me an error during installation:

```<code># make
#  ➜  p4est-2.8 make install

/Applications/Xcode.app/Contents/Developer/usr/bin/make  install-recursive
Making install in sc
/Applications/Xcode.app/Contents/Developer/usr/bin/make  install-am
 build-aux/install-sh -c -d '/Users/xiaoyun/Downloads/p4est-2.8/local/lib'
 /bin/sh ./libtool   --mode=install /usr/bin/install -c   src/libsc.la '/Users/xiaoyun/Downloads/p4est-2.8/local/lib'
libtool: install: /usr/bin/install -c src/.libs/libsc.0.dylib /Users/xiaoyun/Downloads/p4est-2.8/local/lib/libsc.0.dylib
install: /Users/xiaoyun/Downloads/p4est-2.8/local/lib/libsc.0.dylib: Permission denied
make[4]: *** [install-libLTLIBRARIES] Error 71
make[3]: *** [install-am] Error 2
make[2]: *** [install] Error 2
make[1]: *** [install-recursive] Error 1
</code>```

I have no idea why the permission is denied, I also tried sudo make install:

```<code>objc[71909]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20230f7e8) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x10c9082c8). One of the two will be used. Which one is undefined.
objc[71909]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20230f838) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x10c908318). One of the two will be used. Which one is undefined.
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
make: getcwd: Operation not permitted
make: Nothing to be done for `install'.
</code>```

Body:
Can anyone help me with this issue?

In order to use dealii, I tried to install p4est using the command

./configure && make && make install

and

cmake .. -DP4EST_DIR=/usr/local -DDEAL_II_WITH_P4EST=ON -DDEAL_II_WITH_MPI=ON -DCMAKE_INSTALL_PREFIX=/usr/local

under "build" folder, but some error occurs.

I also opened the file dealii-9.0.0/build/CMakeFiles/CMakeError.log, it says:

Source file was:
int main() { return 0; }

Performing C++ SOURCE FILE Test rt_LIBRARY failed with the following output:
Change Dir: /Users/chuxiaoyun/Downloads/dealii-9.0.0/build/CMakeFiles/CMakeScratch/TryCompile-Fscvq9

Run Build Command(s):/usr/bin/make -f Makefile cmTC_bc7f9/fast && /Applications/Xcode.app/Contents/Developer/usr/bin/make  -f CMakeFiles/cmTC_bc7f9.dir/build.make CMakeFiles/cmTC_bc7f9.dir/build
Building CXX object CMakeFiles/cmTC_bc7f9.dir/src.cxx.o
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -Drt_LIBRARY  -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk -mmacosx-version-min=11.6 -MD -MT CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -MF CMakeFiles/cmTC_bc7f9.dir/src.cxx.o.d -o CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -c /Users/chuxiaoyun/Downloads/dealii-9.0.0/build/CMakeFiles/CMakeScratch/TryCompile-Fscvq9/src.cxx
Linking CXX executable cmTC_bc7f9
/opt/homebrew/Cellar/cmake/3.25.0/bin/cmake -E cmake_link_script CMakeFiles/cmTC_bc7f9.dir/link.txt --verbose=1
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk -mmacosx-version-min=11.6 -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/cmTC_bc7f9.dir/src.cxx.o -o cmTC_bc7f9  -lrt
ld: library not found for -lrt
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [cmTC_bc7f9] Error 1
make: *** [cmTC_bc7f9/fast] Error 2

CMake Error at cmake/macros/macro_configure_feature.cmake:112 (MESSAGE):

  Could not find the p4est library!

  Insufficient p4est installation found!

  p4est has to be configured with MPI enabled.

  Please ensure that a suitable p4est library is installed on your computer.

  If the library is not at a default location, either provide some hints for
  autodetection,

      $ P4EST_DIR="..." cmake <...>
      $ cmake -DP4EST_DIR="..." <...>

  or set the relevant variables by hand in ccmake.
  Call Stack (most recent call first):
  cmake/macros/macro_configure_feature.cmake:269 (FEATURE_ERROR_MESSAGE)
  cmake/configure/configure_p4est.cmake:78 (CONFIGURE_FEATURE)
  cmake/macros/macro_verbose_include.cmake:19 (INCLUDE)
  CMakeLists.txt:124 (VERBOSE_INCLUDE)

I guess I haven't installed p4est correctly, so I configure it again.

#  p4est-2.8 ./configure --enable-mpi.

( Here shows we are using MPI. I also tried p4est-2.8  ./configure --enable-mpi --prefix=/usr/local)

Then I tried to build and install p4est, but it gives me an error during installation:

# make
#  ➜  p4est-2.8 make install

/Applications/Xcode.app/Contents/Developer/usr/bin/make  install-recursive
Making install in sc
/Applications/Xcode.app/Contents/Developer/usr/bin/make  install-am
 build-aux/install-sh -c -d '/Users/xiaoyun/Downloads/p4est-2.8/local/lib'
 /bin/sh ./libtool   --mode=install /usr/bin/install -c   src/libsc.la '/Users/xiaoyun/Downloads/p4est-2.8/local/lib'
libtool: install: /usr/bin/install -c src/.libs/libsc.0.dylib /Users/xiaoyun/Downloads/p4est-2.8/local/lib/libsc.0.dylib
install: /Users/xiaoyun/Downloads/p4est-2.8/local/lib/libsc.0.dylib: Permission denied
make[4]: *** [install-libLTLIBRARIES] Error 71
make[3]: *** [install-am] Error 2
make[2]: *** [install] Error 2
make[1]: *** [install-recursive] Error 1

I have no idea why the permission is denied, I also tried sudo make install:

objc[71909]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20230f7e8) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x10c9082c8). One of the two will be used. Which one is undefined.
objc[71909]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20230f838) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x10c908318). One of the two will be used. Which one is undefined.
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
make: getcwd: Operation not permitted
make: Nothing to be done for `install'.


问:
Interactive form for storing user information
I am learning to use HTML, CSS, JavaScript and JDBC. I want to integrate all the said together and arrive at a webpage that accepts user information that can be used to make a detailed profile of a family that can act as a repository for the family to access that information from anywhere by just logging into the website. I also want to do CURD operations to apply to all the data submitted. Need cascading dropdown menus that populate by themselves when one option is selected by user

I started off by making cascading dropdown menu that when province is selected the next dropdown selects only the corresponding cities in that province only. I was able to populate the first dropdown but could not connect it to subsequent dropdown

below is the JavaScript that I prepared for any number of cascading dropdowns but its not working and now I am unable to identify whats wrong with the code

```<code>function makeDropDown(data, filtersAsArray, targetElement) {
  const filteredArray = filterArray(data, filtersAsArray);
  //const filteredArray = data.filter((r) => r[0] === level1Filter);
  //const uniqueOptions = new Set();

  // using for each item of the array from the second place and put the valused in the uniqueoptions set
  //filteredArray.forEach((r) => uniqueOptions.add(r[1]));

  // deconstruting the set to form the array again
  //const uniqueList = [...uniqueOptions];

  const uniqueList = getUniqueValues(filteredArray, filtersAsArray.length);

  populateDropDown(targetElement, uniqueList);
  //selectLevel2.innerHTML = "";
  //uniqueList.forEach((item) => {
  //const option = document.createElement("option");
  //option.textContent = item;
  //selectLevel2.appendChild(option);
  //});
}

function applyDropDown() {
  const selectLevel1Value = document.getElementById("level1").value;
  const selectLevel2 = document.getElementById("level2");
  makeDropDown(myData, [selectLevel1Value], selectLevel2);
  applyDropDown2();
}

function applyDropDown2() {
  const selectLevel1Value = document.getElementById("level1").value;
  const selectLevel2Value = document.getElementById("level2").value;
  const selectLevel3 = document.getElementById("level3");
  makeDropDown(myData, [selectLevel1Value, selectLevel2Value], selectLevel3);
}

function afterDocumnetLoads() {
  populateFirstLevelDropDown();
  applyDropDown();
}

function getUniqueValues(data, index) {
  const uniqueOptions = new Set();
  data.forEach((r) => uniqueOptions.add(r[index]));
  return [...uniqueOptions];
}

function populateFirstLevelDropDown() {
  const uniqueList = getUniqueValues(myData, 0);
  const ele = document.getElementById("level1");
  populateDropDown(ele, uniqueList);
}

function populateDropDown(ele, listAsArray) {
  ele.innerHTML = "";
  listAsArray.forEach((item) => {
    const option = document.createElement("option");
    option.textContent = item;
    ele.appendChild(option);
  });
}

function filterArray(data, filtersAsArray) {
  return data.filter((r) => filtersAsArray.every((item, i) => item === r[i]));
}

document.getElementById("level1").addEventListener("change", applyDropDown);
document.getElementById("level2").addEventListener("change", applyDropDown2);
document.addEventListener("DOMContentLoaded", afterDocumnetLoads);
</code>```

Body:
I am learning to use HTML, CSS, JavaScript and JDBC. I want to integrate all the said together and arrive at a webpage that accepts user information that can be used to make a detailed profile of a family that can act as a repository for the family to access that information from anywhere by just logging into the website. I also want to do CURD operations to apply to all the data submitted. Need cascading dropdown menus that populate by themselves when one option is selected by user

I started off by making cascading dropdown menu that when province is selected the next dropdown selects only the corresponding cities in that province only. I was able to populate the first dropdown but could not connect it to subsequent dropdown

below is the JavaScript that I prepared for any number of cascading dropdowns but its not working and now I am unable to identify whats wrong with the code

function makeDropDown(data, filtersAsArray, targetElement) {
  const filteredArray = filterArray(data, filtersAsArray);
  //const filteredArray = data.filter((r) => r[0] === level1Filter);
  //const uniqueOptions = new Set();

  // using for each item of the array from the second place and put the valused in the uniqueoptions set
  //filteredArray.forEach((r) => uniqueOptions.add(r[1]));

  // deconstruting the set to form the array again
  //const uniqueList = [...uniqueOptions];

  const uniqueList = getUniqueValues(filteredArray, filtersAsArray.length);

  populateDropDown(targetElement, uniqueList);
  //selectLevel2.innerHTML = "";
  //uniqueList.forEach((item) => {
  //const option = document.createElement("option");
  //option.textContent = item;
  //selectLevel2.appendChild(option);
  //});
}

function applyDropDown() {
  const selectLevel1Value = document.getElementById("level1").value;
  const selectLevel2 = document.getElementById("level2");
  makeDropDown(myData, [selectLevel1Value], selectLevel2);
  applyDropDown2();
}

function applyDropDown2() {
  const selectLevel1Value = document.getElementById("level1").value;
  const selectLevel2Value = document.getElementById("level2").value;
  const selectLevel3 = document.getElementById("level3");
  makeDropDown(myData, [selectLevel1Value, selectLevel2Value], selectLevel3);
}

function afterDocumnetLoads() {
  populateFirstLevelDropDown();
  applyDropDown();
}

function getUniqueValues(data, index) {
  const uniqueOptions = new Set();
  data.forEach((r) => uniqueOptions.add(r[index]));
  return [...uniqueOptions];
}

function populateFirstLevelDropDown() {
  const uniqueList = getUniqueValues(myData, 0);
  const ele = document.getElementById("level1");
  populateDropDown(ele, uniqueList);
}

function populateDropDown(ele, listAsArray) {
  ele.innerHTML = "";
  listAsArray.forEach((item) => {
    const option = document.createElement("option");
    option.textContent = item;
    ele.appendChild(option);
  });
}

function filterArray(data, filtersAsArray) {
  return data.filter((r) => filtersAsArray.every((item, i) => item === r[i]));
}

document.getElementById("level1").addEventListener("change", applyDropDown);
document.getElementById("level2").addEventListener("change", applyDropDown2);
document.addEventListener("DOMContentLoaded", afterDocumnetLoads);


问:
Separation of the repository by content (separation of parsing and data processing)
The goal of the project is to create a recommender system in which I go through all the stages of building, training a model from collecting and processing data, creating a model to implementing it into a bot.
The problem is that I don't know if it's worth splitting the repository into two, one is responsible for collecting information, and the second for building a model. The resulting model will be used in the telegram bot, so this part of the project must also be placed in the same repository or create a separate one that will copy the model (one file) from their repository.

The first option is not to separate the repository and store parsing, processing and model building in separate folders, but this option is not always convenient, the second option is to create two separate repositories, but then the project building logic will collapse, that is, data collection, this is a strange part of the project, that it is in a separate repository. Does the community have certain rules in such a situation?


问:
python Crash course- html templates not rendering as text
I am working on a project called learning logs in the book python crash course that should be 2nd edition, chapter 18. My IDE is pycharm.
I have created a template I call index.html that inherits from a base template called base.html. Running index.html on any browser just displays the code exactly as it is and not the what the output should be. It doesn't seem to be an IDE related problem, I used the exact same code using sublime text and notepad. What am I not doing right.

base.html

```<code><p>
➊ <a href="{% url 'learning_logs:index' %}">Learning Log</a>
</p>
➋ {% block content %}{% endblock content %}

</code>```

index.html

```<code>➊ {% extends "learning_logs/base.html" %}
➋ {% block content %}
<p>Learning Log helps you keep track of your learning, for any topic
you're
learning about.</p>
➌ {% endblock content %}
</code>```

tried using different IDEs, copy pasting the code from the book.

Body:
I am working on a project called learning logs in the book python crash course that should be 2nd edition, chapter 18. My IDE is pycharm.
I have created a template I call index.html that inherits from a base template called base.html. Running index.html on any browser just displays the code exactly as it is and not the what the output should be. It doesn't seem to be an IDE related problem, I used the exact same code using sublime text and notepad. What am I not doing right.

base.html

➊ Learning Log

➋ {% block content %}{% endblock content %}

index.html

➊ {% extends "learning_logs/base.html" %}
➋ {% block content %}

Learning Log helps you keep track of your learning, for any topic
you're
learning about.

➌ {% endblock content %}

tried using different IDEs, copy pasting the code from the book.


问:
Custom Import in AWS developer console, beautifulsoup4
This question was asked before but never answered well:
I need beautifulsoup4 to scrape through a websites HTML and get information. I want to use that information in my Alexa-skill.

How do I import/use bs4 in my Alexa developer console?

I've already read how to make a deployment package (https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html), but I don't understand how to download/zip bs4.

I am new to Python, AWS and Alexa developer console, so I am sorry if that question is very easy to answer.

I tried to create a ziped folder named lamda and upload it under upload code, but running my skill wuth import bs4 just errors


问:
i got an error type 'String' is not a subtype of type 'int' of 'index' how should i fix this?
enter image description here
enter image description here

i try to make a comment screen to make a comment from post like instagram but when i click the button icon to the comment screen page, i got the error "type 'String' is not a subtype of type 'int' of 'index'"
The relevant error-causing widget was CommentsScreen. i dont know how to fix this, here is the code..

`

```<code> IconButton(
                onPressed: () => Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => CommentsScreen(
                      snap: widget.snap['postId'].toString(),
                    ),
                  ),
                ),
                icon: const Icon(
                  Icons.comment_outlined,
                ),
              ),
</code>```

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:instagram/models/user.dart';
import 'package:instagram/providers/user_provider.dart';
import 'package:instagram/resources/firestore_methods.dart';
import 'package:instagram/utils/colors.dart';
import 'package:instagram/widgets/comment_card.dart';
import 'package:provider/provider.dart';

class CommentsScreen extends StatefulWidget {
  final snap;
  const CommentsScreen({super.key, required this.snap});

  @override
  State<CommentsScreen> createState() => _CommentsScreenState();
}

class _CommentsScreenState extends State<CommentsScreen> {
  final TextEditingController _commentController = TextEditingController();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _commentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final User user = Provider.of<UserProvider>(context).getUser;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: mobileBackgroundColor,
        title: const Text('comments'),
        centerTitle: false,
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('posts')
            .doc(widget.snap['postId'])
            .collection('comments')
            .orderBy(
              'datePublished',
              descending: false,
            )
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: (snapshot.data! as dynamic).docs.length,
            itemBuilder: (context, index) => CommentCard(
              snap: (snapshot.data! as dynamic).docs[index].data(),
            ),
          );
        },
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: kToolbarHeight,
          margin: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          padding: const EdgeInsets.only(left: 16, right: 8),
          child: Row(
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(
                  user.photoUrl,
                ),
                radius: 18,
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16, right: 8.0),
                  child: TextField(
                    controller: _commentController,
                    decoration: InputDecoration(
                      hintText: 'comment as ${user.username}',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
              InkWell(
                onTap: () async {
                  FirestoreMethods().postComment(
                    widget.snap['postId'],
                    _commentController.text,
                    user.uid,
                    user.username,
                    user.photoUrl,
                  );
                  setState(() {
                    _commentController.text = "";
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    vertical: 8,
                    horizontal: 8,
                  ),
                  child: const Text(
                    'post',
                    style: TextStyle(
                      color: Colors.blueAccent,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

</code>```

`

i try to make a comment from post i was expecting that it works fine

Body:
enter image description here
enter image description here

i try to make a comment screen to make a comment from post like instagram but when i click the button icon to the comment screen page, i got the error "type 'String' is not a subtype of type 'int' of 'index'"
The relevant error-causing widget was CommentsScreen. i dont know how to fix this, here is the code..

`

 IconButton(
                onPressed: () => Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => CommentsScreen(
                      snap: widget.snap['postId'].toString(),
                    ),
                  ),
                ),
                icon: const Icon(
                  Icons.comment_outlined,
                ),
              ),

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:instagram/models/user.dart';
import 'package:instagram/providers/user_provider.dart';
import 'package:instagram/resources/firestore_methods.dart';
import 'package:instagram/utils/colors.dart';
import 'package:instagram/widgets/comment_card.dart';
import 'package:provider/provider.dart';

class CommentsScreen extends StatefulWidget {
  final snap;
  const CommentsScreen({super.key, required this.snap});

  @override
  State<CommentsScreen> createState() => _CommentsScreenState();
}

class _CommentsScreenState extends State<CommentsScreen> {
  final TextEditingController _commentController = TextEditingController();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _commentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final User user = Provider.of<UserProvider>(context).getUser;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: mobileBackgroundColor,
        title: const Text('comments'),
        centerTitle: false,
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('posts')
            .doc(widget.snap['postId'])
            .collection('comments')
            .orderBy(
              'datePublished',
              descending: false,
            )
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: (snapshot.data! as dynamic).docs.length,
            itemBuilder: (context, index) => CommentCard(
              snap: (snapshot.data! as dynamic).docs[index].data(),
            ),
          );
        },
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: kToolbarHeight,
          margin: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          padding: const EdgeInsets.only(left: 16, right: 8),
          child: Row(
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(
                  user.photoUrl,
                ),
                radius: 18,
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16, right: 8.0),
                  child: TextField(
                    controller: _commentController,
                    decoration: InputDecoration(
                      hintText: 'comment as ${user.username}',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
              InkWell(
                onTap: () async {
                  FirestoreMethods().postComment(
                    widget.snap['postId'],
                    _commentController.text,
                    user.uid,
                    user.username,
                    user.photoUrl,
                  );
                  setState(() {
                    _commentController.text = "";
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    vertical: 8,
                    horizontal: 8,
                  ),
                  child: const Text(
                    'post',
                    style: TextStyle(
                      color: Colors.blueAccent,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

`

i try to make a comment from post i was expecting that it works fine


问:
r.listen_in_background() in SpeechRecognition is terminating without giving any output
I have been trying to use the python library for Speech Recognition inorder to capture Microphone audio. I have implemented the same with the r.listen() function for listening on the main thread. I am trying to use r.listen_in_background() so as to keep listening in the background indefinitely till I exit the program. However, My program terminates abruptly after executing the r.listen_in_background() statement, without throwing any error or displaying any input. My code is as follows:

```<code>def exit_handler():
    logging.info('Exiting..')
    stop_listen()

def voice_callback(recog,audio):
    #Callback function to transcribe real time audio input from microphone
    result=#Decoded output
    print('You said  '+result['text'])

#Load the speech recogniser
atexit.register(exit_handler)
r = sr.Recognizer()
mic_i = sr.Microphone(sample_rate=20000)
with mic_i as source:
   r.adjust_for_ambient_noise(source)
#audio = r.listen(source)
print("Say something!")
stop_listen=r.listen_in_background(mic_i,voice_callback)
</code>```

My program terminates after printing "Say Something". It works correctly when I use r.listen().How could this be resolved?

Body:
I have been trying to use the python library for Speech Recognition inorder to capture Microphone audio. I have implemented the same with the r.listen() function for listening on the main thread. I am trying to use r.listen_in_background() so as to keep listening in the background indefinitely till I exit the program. However, My program terminates abruptly after executing the r.listen_in_background() statement, without throwing any error or displaying any input. My code is as follows:

def exit_handler():
    logging.info('Exiting..')
    stop_listen()

def voice_callback(recog,audio):
    #Callback function to transcribe real time audio input from microphone
    result=#Decoded output
    print('You said  '+result['text'])

#Load the speech recogniser
atexit.register(exit_handler)
r = sr.Recognizer()
mic_i = sr.Microphone(sample_rate=20000)
with mic_i as source:
   r.adjust_for_ambient_noise(source)
#audio = r.listen(source)
print("Say something!")
stop_listen=r.listen_in_background(mic_i,voice_callback)

My program terminates after printing "Say Something". It works correctly when I use r.listen().How could this be resolved?


问:
Onesignal pushNotification in react native
Hi I am using Onesignal for my application to send push notifications to my application, I am able to send the push notification and getting to my app, when i click on notification nothing is happening it is just disappearing, How can i open the application and after login to application i need to got to notifications screen, Is there anything i need to configure in onesignal and my native code. As of now i have done for android. Below is the code.

In app.js:

```<code> useEffect(() => {
    OneSignal.setAppId("myAppId");
    OneSignal.setNotificationOpenedHandler((notification) => {
      console.log("OneSignal: notification opened:", notification);
    });
  }, []);
</code>```

In build.gradle:

```<code>implementation 'com.onesignal:OneSignal:[4.0.0, 4.99.99]'
</code>```

Body:
Hi I am using Onesignal for my application to send push notifications to my application, I am able to send the push notification and getting to my app, when i click on notification nothing is happening it is just disappearing, How can i open the application and after login to application i need to got to notifications screen, Is there anything i need to configure in onesignal and my native code. As of now i have done for android. Below is the code.

In app.js:

 useEffect(() => {
    OneSignal.setAppId("myAppId");
    OneSignal.setNotificationOpenedHandler((notification) => {
      console.log("OneSignal: notification opened:", notification);
    });
  }, []);

In build.gradle:

implementation 'com.onesignal:OneSignal:[4.0.0, 4.99.99]'


问:
SwiftUI/WatchOS - Picker inside a ScrollView does not work as expected
What I am trying to build

Apple Watch app(written in SwiftUI, targeting watchOS 7 or higher, built with Xcode 14.1)

The Problem

Picker placed inside a ScrollView on an apple watch device does not work as expected

I want to find out how to get the Picker to work as expected, stated below.

Expected behavior

On an iOS simulator, a Picker inside a ScrollView works as expected.

If I try scroll interaction on the Picker area, the ScrollView part doesn’t get scrolled and only the Picker gets scrolled.

whereas on the watch simulator Example,

If I try to scroll the Picker by touching the Picker area, the whole ScrollView reacts and moves up and down. And I am not able to control the Picker properly.

The code I wrote is as follows:

```<code>ScrollView {
    //..other view elements..

    Picker(selection: $currentDay) {
        ForEach(weekDays, id: \.self) {
            Text($0)
        }
    } label: {
        Text("")
    }
    .frame(width: 148,height: 50)
    .pickerStyle(.wheel)

   //..other view elements..
}//: ScrollView

</code>```

Things I have tried

putting the Picker inside a VStack/ZStack/HStack

giving the Picker fixed frame values / giving other elements inside the ScrollView fixed frame values

Body:
What I am trying to build

Apple Watch app(written in SwiftUI, targeting watchOS 7 or higher, built with Xcode 14.1)

The Problem

Picker placed inside a ScrollView on an apple watch device does not work as expected

I want to find out how to get the Picker to work as expected, stated below.

Expected behavior

On an iOS simulator, a Picker inside a ScrollView works as expected.

If I try scroll interaction on the Picker area, the ScrollView part doesn’t get scrolled and only the Picker gets scrolled.

whereas on the watch simulator Example,

If I try to scroll the Picker by touching the Picker area, the whole ScrollView reacts and moves up and down. And I am not able to control the Picker properly.

The code I wrote is as follows:

ScrollView {
    //..other view elements..

    Picker(selection: $currentDay) {
        ForEach(weekDays, id: \.self) {
            Text($0)
        }
    } label: {
        Text("")
    }
    .frame(width: 148,height: 50)
    .pickerStyle(.wheel)

   //..other view elements..
}//: ScrollView

Things I have tried

putting the Picker inside a VStack/ZStack/HStack

giving the Picker fixed frame values / giving other elements inside the ScrollView fixed frame values


问:
InvalidArgumentError (see above for traceback):logits and labels must be broadcastable: logits_size=[183,2] labels_size=[20,2]
```<code>This is a learning-based rna and disease prediction code using cnn that I downloaded from github. The output is accuracy and auc values, but the result is very unstable (occasionally 0.3, occasionally 0.8).

I don't know what the reason is, but the division of training set and verification set in this article is a self-defined function, so I want to try 10 cross-verification. However, when I write the cross-validation code, the problem as shown in the title appears.

</code>```

This is the code that divides the training set and the verification set in the source code.

```<code>def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   Randomly shuffle data
   np.random.seed(10)
   shuffle_indices = np.random.permutation(np.arange(len(input_label)))
   input_data = [x[i] for i in shuffle_indices]
   input_label = [input_label[i] for i in shuffle_indices]
   dev_sample_index = -2 * int(dev_sample_percentage * float(len(input_label)))
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   x_train, x_dev, test_data = input_data[:dev_sample_index],     input_data[dev_sample_index:test_sample_index], input_data[test_sample_index:]
   y_train, y_dev, test_label = input_label[:dev_sample_index],   input_label[dev_sample_index:test_sample_index], input_label[test_sample_index:]

   return x_train, x_dev, test_data, y_train, y_dev, test_label
</code>```

This is my modified code.

```<code>def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   y = np.array(input_label)
   kf = KFold(n_splits=10)
   d = kf.split(x)
   for train_idx, test_idx in d:
      x_train = x[train_idx]
      x_dev = x[test_idx]
   l=kf.split(y)
   for train_idx ,test_idx in l:
      y_train=y[train_idx]
      y_dev=y[test_idx]
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   test_data=input_data[test_sample_index:]
   test_lable=input_label[test_sample_index:]
   return x_train,x_dev,y_train, y_dev,test_data,test_lable

</code>```

This is a screenshot of the error.

This is the complete code of this part.

```<code> #! /usr/bin/env python

import tensorflow as tf
import numpy as np
import os
import argparse
import data_helpers as dh
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import precision_recall_curve
from sklearn import metrics
from tensorflow.contrib import learn
import matplotlib.pyplot as plt
import sklearn.preprocessing as prep
from sklearn.metrics import average_precision_score
from sklearn.model_selection import KFold

def parse_args():
   parser = argparse.ArgumentParser(description="Run CNN.")
   ## the input file
   ##disease-gene relationships and miRNA-gene relatiohships
   parser.add_argument('--input_disease_miRNA', nargs='?', default='..\..\data\CNN\disease-miro-1024-sigmoid.csv',
                  help='Input disease_gene_relationship file')

   parser.add_argument('--input_label',nargs = '?',default='..\..\data\CNN\label.csv',
                  help='sample label')
   parser.add_argument('--batch_size', nargs='?', default=64,
                  help = 'number of samples in one batch')
   parser.add_argument('--training_epochs', nargs='?', default=1,
                  help= 'number of epochs in SGD')
   parser.add_argument('--display_step', nargs='?', default=10)
   parser.add_argument('--test_percentage', nargs='?', default=0.1,
                  help='percentage of test samples')
   parser.add_argument('--dev_percentage', nargs='?', default=0.1,
                  help='percentage of validation samples')
   parser.add_argument('--L2_norm', nargs='?', default=0.001,
                  help='percentage of validation samples')
   parser.add_argument('--keep_prob', nargs='?', default=0.5,
                  help='keep_prob when using dropout option')
   parser.add_argument('--optimizer', nargs='?', default=tf.train.AdamOptimizer,
                  help='optimizer for learning weights')
   parser.add_argument('--learning_rate', nargs='?', default=1e-3,
                  help='learning rate for the SGD')

   return parser.parse_args()
def standard_scale(X_train):

   preprocessor = prep.StandardScaler().fit(X_train)
   X_train = preprocessor.transform(X_train)

   return X_train
def weight_variable(shape):
   initial = tf.truncated_normal(shape, stddev= 0.1)
   weights = tf.Variable(initial)

   return weights
def bias_variable(shape):
   initial = tf.constant(0.1, shape = shape)
   return tf.Variable(initial)
def conv2d(x,W):
   return tf.nn.conv2d(x,W,strides=[1,1,1,1], padding= "VALID")
def max_pool_2(x, W):
   return tf.nn.max_pool(x, ksize = W, strides= [1,10,1,1], padding= "VALID")

def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   y = np.array(input_label)
   kf = KFold(n_splits=10)
   d = kf.split(x)
   for train_idx, test_idx in d:
      x_train = x[train_idx]
      x_dev = x[test_idx]
   l=kf.split(y)
   for train_idx ,test_idx in l:
      y_train=y[train_idx]
      y_dev=y[test_idx]
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   test_data=input_data[test_sample_index:]
   test_lable=input_label[test_sample_index:]
   return x_train,x_dev,y_train, y_dev,test_data,test_lable

   # # Randomly shuffle data
   # np.random.seed(10)
   # shuffle_indices = np.random.permutation(np.arange(len(input_label)))
   # input_data = [x[i] for i in shuffle_indices]
   # input_label = [input_label[i] for i in shuffle_indices]
   # dev_sample_index = -2 * int(dev_sample_percentage * float(len(input_label)))
   # test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   # x_train, x_dev, test_data = input_data[:dev_sample_index], input_data[dev_sample_index:test_sample_index], input_data[test_sample_index:]
   # y_train, y_dev, test_label = input_label[:dev_sample_index], input_label[dev_sample_index:test_sample_index], input_label[test_sample_index:]
   #
   # return x_train, x_dev, test_data, y_train, y_dev, test_label

def deepnn(x, keep_prob, args):
   with tf.name_scope('reshape'):
      x = tf.reshape(x, [-1, 1024, 1, 1])

   with tf.name_scope('conv_pool'):
      filter_shape = [4, 1, 1, 4]

      W_conv = weight_variable(filter_shape)
      b_conv = bias_variable([4])
      h_conv = tf.nn.relu(conv2d(x, W_conv) + b_conv)
      h_pool = tf.nn.max_pool(h_conv, ksize = [1, 4, 1, 1], strides= [1,4,1,1], padding= "VALID")

      # filter_shape2 = [4,1,4,4]
      # W_conv2 = weight_variable(filter_shape2)
      # b_conv2 = bias_variable([4])
      # h_conv2 = tf.nn.relu(conv2d(h_pool, W_conv2) + b_conv2)
      # h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1,4,1,1], strides= [1,4,1,1],padding="VALID")

      regula = tf.contrib.layers.l2_regularizer(args.L2_norm)
      h_input1 = tf.reshape(h_pool,[-1, 255 * 4])
      W_fc1 = weight_variable([255* 4, 50])

      b_fc1 = bias_variable([50])
      h_input2 = tf.nn.relu(tf.matmul(h_input1, W_fc1) + b_fc1)
      h_keep = tf.nn.dropout(h_input2, keep_prob)
      W_fc2 = weight_variable([50, 2])
      b_fc2 = bias_variable([2])
      h_output = tf.matmul(h_keep, W_fc2) + b_fc2
      regularizer = regula(W_fc1) + regula(W_fc2)
      return h_output, regularizer

def main(args):
   with tf.device('/cpu:0'):
      x_train, x_dev, test_data, y_train, y_dev, test_label = get_data(args)
      input_data = tf.placeholder(tf.float32, [None, 1024])
      input_label = tf.placeholder(tf.float32, [None, 2])
      keep_prob = tf.placeholder(tf.float32)
      y_conv, losses = deepnn(input_data, keep_prob, args)
      y_res = tf.nn.softmax(y_conv)
      with tf.name_scope('loss'):
         cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=input_label)
      cross_entropy = tf.reduce_mean(cross_entropy)
      los = cross_entropy + losses
      with tf.name_scope('optimizer'):
         optimizer = args.optimizer
         learning_rate = args.learning_rate
         train_step = optimizer(learning_rate).minimize(los)
         # optimizer = tf.train.MomentumOptimizer(learning_rate= 0.02, momentum=)
         # train_step = optimizer.minimize(cross_entropy)
      with tf.name_scope('accuracy'):
         predictions = tf.argmax(y_conv, 1)
         correct_predictions = tf.equal(predictions, tf.argmax(input_label, 1))
         correct_predictions = tf.cast(correct_predictions, tf.float32)
      accuracy = tf.reduce_mean(correct_predictions)

      batch_size = args.batch_size
      num_epochs = args.training_epochs
      display_step = args.display_step
      k_p = args.keep_prob
      with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())

            batches = dh.batch_iter(list(zip(x_train, y_train)), batch_size, num_epochs)

            for i, batch in enumerate(batches):
               x_batch, y_batch = zip(*batch)# 按batch把数据拿进来

               train_step.run(feed_dict={input_data: x_batch, input_label: y_batch, keep_prob: k_p})

               if i % display_step == 0:

                     loss = sess.run(los, feed_dict={input_data: x_train, input_label: y_train, keep_prob: 1.0})
                     #print('after training loss = %f' % loss)
                     y_predict = sess.run(y_res, feed_dict={input_data: x_dev, input_label: y_dev, keep_prob: 1.0})[:, 1]

                     loss = sess.run(los, feed_dict={input_data: x_dev, input_label: y_dev, keep_prob: 1.0})
                     #print('test loss = %f' % loss)

                     false_positive_rate1, true_positive_rate1, thresholds1 = roc_curve(np.array(y_dev)[:, 1], y_predict)
                     roc_auc1 = auc(false_positive_rate1, true_positive_rate1)
                     # print(roc_auc1)
            ###print(accuracy.eval(feed_dict={input_data: x_train, input_label:y_train, keep_prob: 1.0}))
            print('accuracy=',accuracy.eval(feed_dict={input_data: test_data, input_label: test_label, keep_prob: 1.0}))

            y_predict = sess.run(y_res, feed_dict={input_data: test_data, input_label: test_label, keep_prob: 1.0})[:, 1]
            false_positive_rate1, true_positive_rate1, thresholds1 = roc_curve(np.array(test_label)[:, 1], y_predict)
            roc_auc1 = auc(false_positive_rate1, true_positive_rate1)
            print('roc_auc1=',roc_auc1)

            # plt.figure()
            # lw=2
            # plt.title("ROC curve of %s (AUC = %.4f)")
            # plt.xlabel("False Positive Rate")
            # plt.ylabel("True Positive Rate")
            # plt.plot(false_positive_rate1 , true_positive_rate1)  # use pylab to plot x and y
            # plt.show()  # show the plot on the screen
            #
            # plt.show()

            # np.savetxt("result_fp_tp_md_aver.txt", roc_curve(np.array(test_label)[:, 1], y_predict))
            # precision, recall ,_ = precision_recall_curve(np.array(test_label)[:, 1], y_predict)
            #  #
            # average_precision = average_precision_score(np.array(test_label)[:, 1], y_predict)
            #  #
            # print('Average precision-recall score: {0:0.2f}'.format(average_precision))
            # y_predict[y_predict >= 0.5] = 1
            # y_predict[y_predict < 0.5] = 0
            # print(y_predict)
            # print(metrics.f1_score(np.array(test_label)[:, 1], y_predict))
            # np.savetxt("precision_aver.txt", precision)
            # np.savetxt("recall_aver.txt", recall)
if __name__ == '__main__':
   args = parse_args()
   main(args)

</code>```

please help me!!!  thanks a lot!!!

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

Body:
This is a learning-based rna and disease prediction code using cnn that I downloaded from github. The output is accuracy and auc values, but the result is very unstable (occasionally 0.3, occasionally 0.8).

I don't know what the reason is, but the division of training set and verification set in this article is a self-defined function, so I want to try 10 cross-verification. However, when I write the cross-validation code, the problem as shown in the title appears.

This is the code that divides the training set and the verification set in the source code.

def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   Randomly shuffle data
   np.random.seed(10)
   shuffle_indices = np.random.permutation(np.arange(len(input_label)))
   input_data = [x[i] for i in shuffle_indices]
   input_label = [input_label[i] for i in shuffle_indices]
   dev_sample_index = -2 * int(dev_sample_percentage * float(len(input_label)))
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   x_train, x_dev, test_data = input_data[:dev_sample_index],     input_data[dev_sample_index:test_sample_index], input_data[test_sample_index:]
   y_train, y_dev, test_label = input_label[:dev_sample_index],   input_label[dev_sample_index:test_sample_index], input_label[test_sample_index:]

   return x_train, x_dev, test_data, y_train, y_dev, test_label

This is my modified code.

def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   y = np.array(input_label)
   kf = KFold(n_splits=10)
   d = kf.split(x)
   for train_idx, test_idx in d:
      x_train = x[train_idx]
      x_dev = x[test_idx]
   l=kf.split(y)
   for train_idx ,test_idx in l:
      y_train=y[train_idx]
      y_dev=y[test_idx]
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   test_data=input_data[test_sample_index:]
   test_lable=input_label[test_sample_index:]
   return x_train,x_dev,y_train, y_dev,test_data,test_lable

This is a screenshot of the error.

This is the complete code of this part.

 #! /usr/bin/env python

import tensorflow as tf
import numpy as np
import os
import argparse
import data_helpers as dh
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import precision_recall_curve
from sklearn import metrics
from tensorflow.contrib import learn
import matplotlib.pyplot as plt
import sklearn.preprocessing as prep
from sklearn.metrics import average_precision_score
from sklearn.model_selection import KFold

def parse_args():
   parser = argparse.ArgumentParser(description="Run CNN.")
   ## the input file
   ##disease-gene relationships and miRNA-gene relatiohships
   parser.add_argument('--input_disease_miRNA', nargs='?', default='..\..\data\CNN\disease-miro-1024-sigmoid.csv',
                  help='Input disease_gene_relationship file')

   parser.add_argument('--input_label',nargs = '?',default='..\..\data\CNN\label.csv',
                  help='sample label')
   parser.add_argument('--batch_size', nargs='?', default=64,
                  help = 'number of samples in one batch')
   parser.add_argument('--training_epochs', nargs='?', default=1,
                  help= 'number of epochs in SGD')
   parser.add_argument('--display_step', nargs='?', default=10)
   parser.add_argument('--test_percentage', nargs='?', default=0.1,
                  help='percentage of test samples')
   parser.add_argument('--dev_percentage', nargs='?', default=0.1,
                  help='percentage of validation samples')
   parser.add_argument('--L2_norm', nargs='?', default=0.001,
                  help='percentage of validation samples')
   parser.add_argument('--keep_prob', nargs='?', default=0.5,
                  help='keep_prob when using dropout option')
   parser.add_argument('--optimizer', nargs='?', default=tf.train.AdamOptimizer,
                  help='optimizer for learning weights')
   parser.add_argument('--learning_rate', nargs='?', default=1e-3,
                  help='learning rate for the SGD')

   return parser.parse_args()
def standard_scale(X_train):

   preprocessor = prep.StandardScaler().fit(X_train)
   X_train = preprocessor.transform(X_train)

   return X_train
def weight_variable(shape):
   initial = tf.truncated_normal(shape, stddev= 0.1)
   weights = tf.Variable(initial)

   return weights
def bias_variable(shape):
   initial = tf.constant(0.1, shape = shape)
   return tf.Variable(initial)
def conv2d(x,W):
   return tf.nn.conv2d(x,W,strides=[1,1,1,1], padding= "VALID")
def max_pool_2(x, W):
   return tf.nn.max_pool(x, ksize = W, strides= [1,10,1,1], padding= "VALID")

def get_data(args):

   input_data, input_label = dh.get_samples(args)
   input_data = standard_scale(input_data)
   dev_sample_percentage = args.dev_percentage
   test_sample_percentage = args.test_percentage
   x = np.array(input_data)

   y = np.array(input_label)
   kf = KFold(n_splits=10)
   d = kf.split(x)
   for train_idx, test_idx in d:
      x_train = x[train_idx]
      x_dev = x[test_idx]
   l=kf.split(y)
   for train_idx ,test_idx in l:
      y_train=y[train_idx]
      y_dev=y[test_idx]
   test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   test_data=input_data[test_sample_index:]
   test_lable=input_label[test_sample_index:]
   return x_train,x_dev,y_train, y_dev,test_data,test_lable

   # # Randomly shuffle data
   # np.random.seed(10)
   # shuffle_indices = np.random.permutation(np.arange(len(input_label)))
   # input_data = [x[i] for i in shuffle_indices]
   # input_label = [input_label[i] for i in shuffle_indices]
   # dev_sample_index = -2 * int(dev_sample_percentage * float(len(input_label)))
   # test_sample_index = -1 * int(test_sample_percentage * float(len(input_label)))
   # x_train, x_dev, test_data = input_data[:dev_sample_index], input_data[dev_sample_index:test_sample_index], input_data[test_sample_index:]
   # y_train, y_dev, test_label = input_label[:dev_sample_index], input_label[dev_sample_index:test_sample_index], input_label[test_sample_index:]
   #
   # return x_train, x_dev, test_data, y_train, y_dev, test_label

def deepnn(x, keep_prob, args):
   with tf.name_scope('reshape'):
      x = tf.reshape(x, [-1, 1024, 1, 1])

   with tf.name_scope('conv_pool'):
      filter_shape = [4, 1, 1, 4]

      W_conv = weight_variable(filter_shape)
      b_conv = bias_variable([4])
      h_conv = tf.nn.relu(conv2d(x, W_conv) + b_conv)
      h_pool = tf.nn.max_pool(h_conv, ksize = [1, 4, 1, 1], strides= [1,4,1,1], padding= "VALID")

      # filter_shape2 = [4,1,4,4]
      # W_conv2 = weight_variable(filter_shape2)
      # b_conv2 = bias_variable([4])
      # h_conv2 = tf.nn.relu(conv2d(h_pool, W_conv2) + b_conv2)
      # h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1,4,1,1], strides= [1,4,1,1],padding="VALID")

      regula = tf.contrib.layers.l2_regularizer(args.L2_norm)
      h_input1 = tf.reshape(h_pool,[-1, 255 * 4])
      W_fc1 = weight_variable([255* 4, 50])

      b_fc1 = bias_variable([50])
      h_input2 = tf.nn.relu(tf.matmul(h_input1, W_fc1) + b_fc1)
      h_keep = tf.nn.dropout(h_input2, keep_prob)
      W_fc2 = weight_variable([50, 2])
      b_fc2 = bias_variable([2])
      h_output = tf.matmul(h_keep, W_fc2) + b_fc2
      regularizer = regula(W_fc1) + regula(W_fc2)
      return h_output, regularizer

def main(args):
   with tf.device('/cpu:0'):
      x_train, x_dev, test_data, y_train, y_dev, test_label = get_data(args)
      input_data = tf.placeholder(tf.float32, [None, 1024])
      input_label = tf.placeholder(tf.float32, [None, 2])
      keep_prob = tf.placeholder(tf.float32)
      y_conv, losses = deepnn(input_data, keep_prob, args)
      y_res = tf.nn.softmax(y_conv)
      with tf.name_scope('loss'):
         cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=input_label)
      cross_entropy = tf.reduce_mean(cross_entropy)
      los = cross_entropy + losses
      with tf.name_scope('optimizer'):
         optimizer = args.optimizer
         learning_rate = args.learning_rate
         train_step = optimizer(learning_rate).minimize(los)
         # optimizer = tf.train.MomentumOptimizer(learning_rate= 0.02, momentum=)
         # train_step = optimizer.minimize(cross_entropy)
      with tf.name_scope('accuracy'):
         predictions = tf.argmax(y_conv, 1)
         correct_predictions = tf.equal(predictions, tf.argmax(input_label, 1))
         correct_predictions = tf.cast(correct_predictions, tf.float32)
      accuracy = tf.reduce_mean(correct_predictions)

      batch_size = args.batch_size
      num_epochs = args.training_epochs
      display_step = args.display_step
      k_p = args.keep_prob
      with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())

            batches = dh.batch_iter(list(zip(x_train, y_train)), batch_size, num_epochs)

            for i, batch in enumerate(batches):
               x_batch, y_batch = zip(*batch)# 按batch把数据拿进来

               train_step.run(feed_dict={input_data: x_batch, input_label: y_batch, keep_prob: k_p})

               if i % display_step == 0:

                     loss = sess.run(los, feed_dict={input_data: x_train, input_label: y_train, keep_prob: 1.0})
                     #print('after training loss = %f' % loss)
                     y_predict = sess.run(y_res, feed_dict={input_data: x_dev, input_label: y_dev, keep_prob: 1.0})[:, 1]

                     loss = sess.run(los, feed_dict={input_data: x_dev, input_label: y_dev, keep_prob: 1.0})
                     #print('test loss = %f' % loss)

                     false_positive_rate1, true_positive_rate1, thresholds1 = roc_curve(np.array(y_dev)[:, 1], y_predict)
                     roc_auc1 = auc(false_positive_rate1, true_positive_rate1)
                     # print(roc_auc1)
            ###print(accuracy.eval(feed_dict={input_data: x_train, input_label:y_train, keep_prob: 1.0}))
            print('accuracy=',accuracy.eval(feed_dict={input_data: test_data, input_label: test_label, keep_prob: 1.0}))

            y_predict = sess.run(y_res, feed_dict={input_data: test_data, input_label: test_label, keep_prob: 1.0})[:, 1]
            false_positive_rate1, true_positive_rate1, thresholds1 = roc_curve(np.array(test_label)[:, 1], y_predict)
            roc_auc1 = auc(false_positive_rate1, true_positive_rate1)
            print('roc_auc1=',roc_auc1)

            # plt.figure()
            # lw=2
            # plt.title("ROC curve of %s (AUC = %.4f)")
            # plt.xlabel("False Positive Rate")
            # plt.ylabel("True Positive Rate")
            # plt.plot(false_positive_rate1 , true_positive_rate1)  # use pylab to plot x and y
            # plt.show()  # show the plot on the screen
            #
            # plt.show()

            # np.savetxt("result_fp_tp_md_aver.txt", roc_curve(np.array(test_label)[:, 1], y_predict))
            # precision, recall ,_ = precision_recall_curve(np.array(test_label)[:, 1], y_predict)
            #  #
            # average_precision = average_precision_score(np.array(test_label)[:, 1], y_predict)
            #  #
            # print('Average precision-recall score: {0:0.2f}'.format(average_precision))
            # y_predict[y_predict >= 0.5] = 1
            # y_predict[y_predict < 0.5] = 0
            # print(y_predict)
            # print(metrics.f1_score(np.array(test_label)[:, 1], y_predict))
            # np.savetxt("precision_aver.txt", precision)
            # np.savetxt("recall_aver.txt", recall)
if __name__ == '__main__':
   args = parse_args()
   main(args)

please help me!!!  thanks a lot!!!


问:
Groupby problem: count values from 2 columns
First time asking. I know that this may be a silly question, but I'm overwhelmed. I need to group a DataFrame and count the values but I’m having problems.

Lets suppose that I have this DF:

Plate   2021    2022    Total
AAA 1   1

BBB 0   1

CCC 1   1

BBB 1   1

AAA 1   1

AAA 0   1

BBB 1   0

CCC 0   1

My expected outcome would be:

Plate   2021    2022    Total
AAA 2   3   5
BBB 2   2   4
CCC 1   2   3

I tried different combinations of gropupby such as:
df.groupby('Plate').sum()

df.groupby('Plate', '2020', '2021')('total).sum()

but still didn't reach the expected result.

I would apreciate your help :)


问:
A scattermapbox shows but it does not hover
I have a dataframe df and I do

```<code>    fig.add_trace(go.Scattermapbox(
                            lat=one_mesh_p['lat'],
                            lon=one_mesh_p['lon'],
                            mode="markers",
                            marker = { 'size': 5, 'color': "blue" },
                            name="hello",
                            hoverinfo = 'text',
                            text=[str(one_mesh_p['id'])],
                            showlegend = True,
            ))

fig.update_layout(margin={"r": 20, "t": 40, "l": 20, "b": 20},
                        title={"text":file_title, "font":{"size":30}},
                        mapbox_style="open-street-map",
                        hovermode='closest',
                        mapbox=dict(
                            bearing=0,
                            center=go.layout.mapbox.Center(
                                lat=center[0],
                                lon=center[1]
                            ),
                            pitch=0,
                            zoom=zoom_level
                        ),
                        )
</code>```

However, although I see the points, there is no hovering
I have checked and one_mesh_p['id'] has the correct data

Body:
I have a dataframe df and I do

    fig.add_trace(go.Scattermapbox(
                            lat=one_mesh_p['lat'],
                            lon=one_mesh_p['lon'],
                            mode="markers",
                            marker = { 'size': 5, 'color': "blue" },
                            name="hello",
                            hoverinfo = 'text',
                            text=[str(one_mesh_p['id'])],
                            showlegend = True,
            ))

fig.update_layout(margin={"r": 20, "t": 40, "l": 20, "b": 20},
                        title={"text":file_title, "font":{"size":30}},
                        mapbox_style="open-street-map",
                        hovermode='closest',
                        mapbox=dict(
                            bearing=0,
                            center=go.layout.mapbox.Center(
                                lat=center[0],
                                lon=center[1]
                            ),
                            pitch=0,
                            zoom=zoom_level
                        ),
                        )

However, although I see the points, there is no hovering
I have checked and one_mesh_p['id'] has the correct data


问:
How does sbe handle versioning?
I've seen people use  </presence="optional" sinceVersion="1"/> with the newly added fields in a SBE message.xml.
Is there an example to show how exactly it's used?
I'm using uk.co.real_logic.sbe.SbeTool to generate the java decoder from the message.xml.
But once it's generated.

do you need to somehow make changes manually to the decoder to allow it be backward compatible. (I am only adding new fields at the end of the previous version).

when you decode the MsgObj.decode(sbeMsg), how do you make it backward compatible to work with both old version of message (lacking the new fields) and the new version of messages?

Title: How does sbe handle versioning?


问:
Cannot generate Opensearch Reports
I've updated to 2.3 on all my OpenSearch clusters in my AWS accounts. I try to generate reports in the Reporting Plugin. Both pdfs and pngs, based off of Dashboards. Only 1 time ever have I been successful to generate and download a pdf report. Most of the time the progress wheel just keeps spinning, and never finishes. I do see the browser console a few errors, and a 500, but I'm just curios if this feature even works? As across different clusters, with different versions, and different report settings it seems to not work.

Title: Cannot generate Opensearch Reports


问:
Azure API Management - Service Fabric Application Policy Settings
I have created an Azure Service Fabric application and deployed to the Azure cluster. I have created an API Management service, created Backend pointing to my Service Fabric Instance. I am having a simple GET API in the service fabric. I have created inbound processing policy like below, but its not working - getting 500 internal server error.

```<code><policies>
<inbound>
    <base />
    <set-backend-service backend-id="dev-sfc-backend" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="fabric:/M_HelloModelServices/M_HelloModelService" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>
</code>```

Below is the trace while testing API.

```<code>service-fabric-backend (1,014.098 ms){
"messages": [
    "Unable to connect to the remote server",
    "Error occured while calling backend service.",
    "No connection could be made because the target machine actively refused it <IP>:20000"
]}
</code>```

Could someone configured API Management service for Service Fabric Cluster please share how we can configure this.

Body:
I have created an Azure Service Fabric application and deployed to the Azure cluster. I have created an API Management service, created Backend pointing to my Service Fabric Instance. I am having a simple GET API in the service fabric. I have created inbound processing policy like below, but its not working - getting 500 internal server error.

<policies>
<inbound>
    <base />
    <set-backend-service backend-id="dev-sfc-backend" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="fabric:/M_HelloModelServices/M_HelloModelService" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

Below is the trace while testing API.

service-fabric-backend (1,014.098 ms){
"messages": [
    "Unable to connect to the remote server",
    "Error occured while calling backend service.",
    "No connection could be made because the target machine actively refused it <IP>:20000"
]}

Could someone configured API Management service for Service Fabric Cluster please share how we can configure this.


问:
How to show value given from master to Slave's memory as Modbus slave app C#?
im quite new in this modbus and C# world. I've been working on ModbusRTU with this kind of connection between apps (see below)

miniPC(winforms app) <=> Arduino Mega(Modbus Master) <=> Arduino nano(Modbus Slavetext

at this moment, i knew that there's no way that could be 2 masters in ModbusRTU connection. so I'm setting up my C# winform app as a slave to get the data from arduino mega(Master).

as my experiment begin, I already know how to store a data as slave to memory address as it will be read by the master using code below. (I'm using NModbus4 Class library)

```<code>
public static ModbusSlave SLAVE;

private void myform_Load(object sender, EventArgs e){

//other code//

SLAVE = ModbusSerialSlave.CreateRtu(10, myserialPort);
SLAVE.DataStore = DataStoreFactory.CreateDefaultDataStore();

slaveThread = new Thread(SLAVE.Listen);
slaveThread.Start();
}

private void SendVal_Click(object sender, EventArgs e){

SLAVE.DataStore.HoldingRegisters[1] = start_st; //sending some value
SLAVE.DataStore.HoldingRegisters[2] = finish_st; //sending another value

</code>```

everything's above works fine, until i want to reverse the operation with my C# app that has to read the value given by the Arduino Mega(Master) in a certain address and show it to multiple variable.

let's say there's a 4 variable of IR_sensor called

```<code>ushort[] IR_Vals;

IR_Vals[0];
IR_Vals[1];
IR_Vals[2];
IR_Vals[3];

</code>```

because ModbusSerialSlave doesn't have .readHoldingRegisters() method to read just like the master.

does everyone know how to deal with this? maybe some example? will appricate for help :))

Body:
im quite new in this modbus and C# world. I've been working on ModbusRTU with this kind of connection between apps (see below)

miniPC(winforms app) <=> Arduino Mega(Modbus Master) <=> Arduino nano(Modbus Slavetext

at this moment, i knew that there's no way that could be 2 masters in ModbusRTU connection. so I'm setting up my C# winform app as a slave to get the data from arduino mega(Master).

as my experiment begin, I already know how to store a data as slave to memory address as it will be read by the master using code below. (I'm using NModbus4 Class library)

public static ModbusSlave SLAVE;

private void myform_Load(object sender, EventArgs e){

//other code//

SLAVE = ModbusSerialSlave.CreateRtu(10, myserialPort);
SLAVE.DataStore = DataStoreFactory.CreateDefaultDataStore();

slaveThread = new Thread(SLAVE.Listen);
slaveThread.Start();
}

private void SendVal_Click(object sender, EventArgs e){

SLAVE.DataStore.HoldingRegisters[1] = start_st; //sending some value
SLAVE.DataStore.HoldingRegisters[2] = finish_st; //sending another value

everything's above works fine, until i want to reverse the operation with my C# app that has to read the value given by the Arduino Mega(Master) in a certain address and show it to multiple variable.

let's say there's a 4 variable of IR_sensor called

ushort[] IR_Vals;

IR_Vals[0];
IR_Vals[1];
IR_Vals[2];
IR_Vals[3];

because ModbusSerialSlave doesn't have .readHoldingRegisters() method to read just like the master.

does everyone know how to deal with this? maybe some example? will appricate for help :))


问:
typescript multiple decimal point sort using rxjs replayobject
Below is my custom table component's sorting. It is working good for String and number data types except the multiple decimal point number.
DTableSort.ts

```<code>@Component({
    selector: "myDefaultGSorter",
    template: `
        <a style="cursor: pointer" (click)="sort()" class="text-nowrap"
        [ngClass]="isSortedByMeAsc ? 'sort_by_asc' : isSortedByMeDesc ? 'sort_by_desc' : 'no_sorting'">
        <ng-content></ng-content>
        </a>`
})
</code>```

DTable.ts

```<code>import { Directive , EventEmitter , Input , Output , OnInit , OnChanges, DoCheck, IterableDiffers, IterableDiffer } from '@angular/core';
import { ReplaySubject } from "rxjs";
import * as _ from "lodash";

export interface SortEvent {
  sortBy: string|string[];
  sortOrder: string
}

@Directive({
  selector: '<table [mxData]',
  exportAs: `mxDataTable`
})

export class DTableG implements OnChanges , OnInit, DoCheck  {

  private diff: IterableDiffer<any>;
  public onPageChange = new EventEmitter<PageEvent>();

  @Output() public onSortChange = new ReplaySubject<SortEvent>(1);
  @Input("mfSortBy") public sortBy: string|string[] = "";
  @Input("mfSortOrder") public sortOrder = "asc";
  @Input("mxData") public mxData : any[] = [];

  ngOnChanges() {
    data = _.orderBy(data, this.sortBy, [this.sortOrder]);
  }
  /** sort */

  public setSort(sortBy: string|string[], sortOrder: string): void {
    if (this.sortBy !== sortBy || this.sortOrder !== sortOrder) {
        this.sortBy = sortBy;
        this.sortOrder = _.includes(["asc","desc"], sortOrder) ? sortOrder : "asc";
        this.onSortChange.next({sortBy: sortBy, sortOrder: sortOrder});
        this.onSortChange.next({sortBy: sortBy, sortOrder: sortOrder});
     }
  }
}
</code>```

And using the custom table and calling sort event with myDefaultGSorter  as below

```<code><table class="dTable" [mxData]="mgmtList" style="width: 98%;margin: 0px auto;"
       #applListMgmtTable="mxDataTable" >
  <thead>

  <tr>
    <th style="width: 13%">
      <myDefaultGSorter by="requirementId">
        Requirement ID
      </myDefaultGSorter>
    </th>
    <th style="width: 32%">
      <myDefaultGSorter by="applicableRequirement">
        Applicable Requirement
      </myDefaultGSorter>
    </th>

    <th style="width: 15%">
      <myDefaultGSorter by="requirementSource">
        Source
      </myDefaultGSorter>
    </th>
    <th style="width: 8%">Action</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor = "let dataL of applListMgmtTable.data">
    <td>
      {{dataL.requirementId}}
    </td>
    <td>
      {{dataL.applicableRequirement}}
    </td>
    <td>
      {{dataL.requirementSource}}
    </td>
    <td>
    </td>
  </tr>
  </tbody>
</table>
</code>```

Requirement ids are getting sorted as

```<code>4.1.13
4.1.19
4.1.25
4.1.7
4.1.8
4.3.2
4.3.3
4.4.2
</code>```

What I am expecting is as

```<code>4.1.7
4.1.8
4.1.13
4.1.19
4.1.25
4.3.2
4.3.3
4.4.2
</code>```

Body:
Below is my custom table component's sorting. It is working good for String and number data types except the multiple decimal point number.
DTableSort.ts

@Component({
    selector: "myDefaultGSorter",
    template: `

        <ng-content></ng-content>
        `
})

DTable.ts

import { Directive , EventEmitter , Input , Output , OnInit , OnChanges, DoCheck, IterableDiffers, IterableDiffer } from '@angular/core';
import { ReplaySubject } from "rxjs";
import * as _ from "lodash";

export interface SortEvent {
  sortBy: string|string[];
  sortOrder: string
}

@Directive({
  selector: '<table [mxData]',
  exportAs: `mxDataTable`
})

export class DTableG implements OnChanges , OnInit, DoCheck  {

  private diff: IterableDiffer<any>;
  public onPageChange = new EventEmitter<PageEvent>();

  @Output() public onSortChange = new ReplaySubject<SortEvent>(1);
  @Input("mfSortBy") public sortBy: string|string[] = "";
  @Input("mfSortOrder") public sortOrder = "asc";
  @Input("mxData") public mxData : any[] = [];

  ngOnChanges() {
    data = _.orderBy(data, this.sortBy, [this.sortOrder]);
  }
  /** sort */

  public setSort(sortBy: string|string[], sortOrder: string): void {
    if (this.sortBy !== sortBy || this.sortOrder !== sortOrder) {
        this.sortBy = sortBy;
        this.sortOrder = _.includes(["asc","desc"], sortOrder) ? sortOrder : "asc";
        this.onSortChange.next({sortBy: sortBy, sortOrder: sortOrder});
        this.onSortChange.next({sortBy: sortBy, sortOrder: sortOrder});
     }
  }
}

And using the custom table and calling sort event with myDefaultGSorter  as below

      <myDefaultGSorter by="requirementId">
        Requirement ID
      </myDefaultGSorter>

      <myDefaultGSorter by="applicableRequirement">
        Applicable Requirement
      </myDefaultGSorter>

      <myDefaultGSorter by="requirementSource">
        Source
      </myDefaultGSorter>

    Action

      {{dataL.requirementId}}

      {{dataL.applicableRequirement}}

      {{dataL.requirementSource}}

Requirement ids are getting sorted as

4.1.13
4.1.19
4.1.25
4.1.7
4.1.8
4.3.2
4.3.3
4.4.2

What I am expecting is as

4.1.7
4.1.8
4.1.13
4.1.19
4.1.25
4.3.2
4.3.3
4.4.2