问:
Print words within the string from last to first
for example I entered follwoing string ;
" hello I am Mohsen" ;
now I want to Print on output :
"Mohsen am I hello "

please help me !

答:
Both Corralien's and Tobi208's works, and can be combined to the shorter version;

```<code>s = "hello I am Mohsen"
print(' '.join(s.split(' ')[::-1]))
</code>```

or if you want to input the string in the terminal as a prompt;

```<code>s = input()
print(' '.join(s.split(' ')[::-1]))
</code>```

Body:
Both Corralien's and Tobi208's works, and can be combined to the shorter version;

s = "hello I am Mohsen"
print(' '.join(s.split(' ')[::-1]))

or if you want to input the string in the terminal as a prompt;

s = input()
print(' '.join(s.split(' ')[::-1]))


来源: stackexchange

问:
Flutter Firebase Messaging Crashing Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE
Recently we released android application targets to 31 which has reported more crashes (only Android OS 12 users) in Firebase Messaging (PendingIntent). When Application is in Pause/Background state on Notification Receive its crashing.
I've tried possible solutions but no luck still crashing. As i understood is we have to add PendingIntent.FLAG_IMMUTABLE on PendingIntent start activity but not getting any idea how to add or fix this.

If anyone faced same issue and fixed. Share solution for this.

Thanks in advance...

```<code>dependencies{
    implementation platform('com.google.firebase:firebase-bom')
    implementation 'com.google.firebase:firebase-messaging'
    implementation 'com.google.firebase:firebase-iid'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}
</code>```
```<code>E/AndroidRuntime( 7058): java.lang.IllegalArgumentException: com.package: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/AndroidRuntime( 7058): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
E/AndroidRuntime( 7058):    at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:444)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:408)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(com.google.firebase:firebase-messaging@@20.3.0:125)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:9)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.DisplayNotification.handleNotification(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging@@20.3.0:65)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging@@20.3.0:44)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging@@20.3.0:17)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging@@20.3.0:43)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime( 7058):    at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@17.6.0:2)
E/AndroidRuntime( 7058):    at java.lang.Thread.run(Thread.java:920)
W/CrashlyticsCore( 7058): Cannot send reports. Settings are unavailable.
D/TransportRuntime.SQLiteEventStore( 7058): Storing event with priority=HIGHEST, name=FIREBASE_CRASHLYTICS_REPORT for destination cct
</code>```

答:
I resolved this finally. Its crashed due to lower version of Firebase Plugins and after upgrading the Android Dependencies and Flutter plugins it got resolved.

Step 1: In android/app/build.gradle

From

```<code>implementation 'com.google.firebase:firebase-messaging:20.1.5'
</code>```

To

```<code>implementation platform('com.google.firebase:firebase-bom') // add this
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation 'com.google.firebase:firebase-iid:21.1.0' // add this
</code>```

Step 2: In Flutter pubspec.yaml

From

```<code>firebase_core: ^0.5.0+1
firebase_messaging: ^7.0.3
firebase_remote_config: ^0.4.2
firebase_crashlytics: ^0.1.4+1
firebase_dynamic_links: ^0.6.3
firebase_auth: ^0.18.4+1
</code>```

To

```<code>firebase_core: ^1.10.0
firebase_messaging: ^11.2.6
firebase_remote_config: ^2.0.0
firebase_crashlytics: ^2.5.0
firebase_dynamic_links: ^4.0.5
firebase_auth: ^3.3.6
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Recently we released android application targets to 31 which has reported more crashes (only Android OS 12 users) in Firebase Messaging (PendingIntent). When Application is in Pause/Background state on Notification Receive its crashing.
I've tried possible solutions but no luck still crashing. As i understood is we have to add PendingIntent.FLAG_IMMUTABLE on PendingIntent start activity but not getting any idea how to add or fix this.

If anyone faced same issue and fixed. Share solution for this.

Thanks in advance...

dependencies{
    implementation platform('com.google.firebase:firebase-bom')
    implementation 'com.google.firebase:firebase-messaging'
    implementation 'com.google.firebase:firebase-iid'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}

E/AndroidRuntime( 7058): java.lang.IllegalArgumentException: com.package: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/AndroidRuntime( 7058): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
E/AndroidRuntime( 7058):    at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:444)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:408)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(com.google.firebase:firebase-messaging@@20.3.0:125)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:9)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.DisplayNotification.handleNotification(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging@@20.3.0:65)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging@@20.3.0:44)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging@@20.3.0:17)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging@@20.3.0:43)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime( 7058):    at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@17.6.0:2)
E/AndroidRuntime( 7058):    at java.lang.Thread.run(Thread.java:920)
W/CrashlyticsCore( 7058): Cannot send reports. Settings are unavailable.
D/TransportRuntime.SQLiteEventStore( 7058): Storing event with priority=HIGHEST, name=FIREBASE_CRASHLYTICS_REPORT for destination cct

Body:
I resolved this finally. Its crashed due to lower version of Firebase Plugins and after upgrading the Android Dependencies and Flutter plugins it got resolved.

Step 1: In android/app/build.gradle

From

implementation 'com.google.firebase:firebase-messaging:20.1.5'

To

implementation platform('com.google.firebase:firebase-bom') // add this
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation 'com.google.firebase:firebase-iid:21.1.0' // add this

Step 2: In Flutter pubspec.yaml

From

firebase_core: ^0.5.0+1
firebase_messaging: ^7.0.3
firebase_remote_config: ^0.4.2
firebase_crashlytics: ^0.1.4+1
firebase_dynamic_links: ^0.6.3
firebase_auth: ^0.18.4+1

To

firebase_core: ^1.10.0
firebase_messaging: ^11.2.6
firebase_remote_config: ^2.0.0
firebase_crashlytics: ^2.5.0
firebase_dynamic_links: ^4.0.5
firebase_auth: ^3.3.6


问:
DRF Cannot assign must be instance error while testing
I am very new to Django and especially to testing.

I am trying to test a view which retrieves a resource object and creates a game round and gamesession object (in the get request).

This is what my tests look like:
test_views.py

```<code>class GameViewTests(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.resource = {'hash_id': '1404cc769fa538fab1b65b9cad201eca'}
        self.user = CustomUser.objects.create(username="carina")
        self.gametype = Gametype.objects.create(name="imageLabeler", rounds=5, round_duration=60, enabled=True),
        self.gamesession = Gamesession.objects.create(user=self.user, gametype=self.gametype, created=datetime.now())
        self.gameround = Gameround.objects.create(user=self.user, gamesession=self.gamesession,
                                                  created=datetime.now(), score=0)
        self.game_data = {'gametype': self.gametype,
                                 'gamesession': self.gamesession,
                                 'gameround': self.gameround,
                                 'resource': self.resource}
        self.response = self.client.get('http://localhost:8000/api/game/',
                                        self.game_data,
                                        format="json")

    def test_get(self):
        self.client = APIClient()
        response = self.client.get('http://localhost:8000/api/game/')
        self.assertEqual(response.status_code, 200)
</code>```

When I run my test, I get the ValueError: Cannot assign "(<Gametype: imageLabeler>,)": "Gamesession.gametype" must be a "Gametype" instance.

How can I make my test pass?

Update:
This is my View:

```<code>class GameView(APIView):

    def get(self, request, *args, **kwargs):
        gametype = Gametype.objects.all().get(name="imageLabeler")
        gametype_serializer = GametypeSerializer(gametype)

        current_score = 0
        if not isinstance(request.user, CustomUser):
            current_user_id = 1
        else:
            current_user_id = request.user.pk

        gamesession = Gamesession.objects.create(user_id=current_user_id,
                                                 gametype=gametype,
                                                 created=datetime.now())

        random_resource = Resource.objects.all().order_by('?').first()
        first_resource_serializer = ResourceSerializer(random_resource)

        gameround = Gameround.objects.create(user_id=current_user_id,
                                             gamesession=gamesession,
                                             created=datetime.now(),
                                             score=current_score)

        gameround_serializer = GameroundSerializer(gameround)

        start_time = gamesession.created
        # now = timezone.now()
        end_of_game = start_time + timedelta(minutes=5)
        # request.session.set_expiry(300)
        if not datetime.now() == end_of_game:
            return Response({'resource': first_resource_serializer.data, 'gameround': gameround_serializer.data,})

        else:
            return Response(status=status.HTTP_408_REQUEST_TIMEOUT)

    def post(self, request, *args, **kwargs):
        tag_serializer = TagSerializer(data=request.data)
        tagging_serializer = TaggingSerializer(data=request.data)
        gameround_id = request.data.get('gameround_id')
        gameround = Gameround.objects.all().get(id=gameround_id)

        # time where the gameround was created
        start_time = gameround.created
        # time 5 mins after gameround was created
        end_of_game = start_time + timedelta(seconds=20)
        if not datetime.now() == end_of_game:
            if tagging_serializer.is_valid(raise_exception=True):
                tagging_serializer.save(tagging=request.data)
                return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED)
            else:
                return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(status=status.HTTP_408_REQUEST_TIMEOUT)
</code>```

This is the traceback of the error:

```<code>ERROR [2022-02-08 23:32:20,856] Internal Server Error: /api/game/
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/api/src/artigo_api/frontend/views/game_rest_views.py", line 155, in get
    gametype = Gametype.objects.get(name="imageLabeler")
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 435, in get
    raise self.model.DoesNotExist(
frontend.models.Gametype.DoesNotExist: Gametype matching query does not exist.
</code>```

答:
```<code>    raise self.model.DoesNotExist(
frontend.models.Gametype.DoesNotExist: Gametype matching query does not exist.
</code>```

You don't have Gametype object with name imageLabeler in database.

you should catch DoesNotExist error to avoid program crash:

try:
    gt = Gametype.objects.get(name="imageLabeler")
except Gametype.DoesNotExist:
    print('Boom boom! here is no imageLabeler in DB')
    return Response(status=status.HTTP_404_NOT_FOUND)
```
<p>And your another problem is you creating object with name <code>labeler</code>:</p>
```self.gametype = Gametype.objects.create(name="labeler", rounds=5, round_duration=60, enabled=True)
```
<p>But trying to get <code>imageLabeler</code>:</p>
```gametype = Gametype.objects.all().get(name="imageLabeler")
```

Body:
I am very new to Django and especially to testing.

I am trying to test a view which retrieves a resource object and creates a game round and gamesession object (in the get request).

This is what my tests look like:
test_views.py

class GameViewTests(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.resource = {'hash_id': '1404cc769fa538fab1b65b9cad201eca'}
        self.user = CustomUser.objects.create(username="carina")
        self.gametype = Gametype.objects.create(name="imageLabeler", rounds=5, round_duration=60, enabled=True),
        self.gamesession = Gamesession.objects.create(user=self.user, gametype=self.gametype, created=datetime.now())
        self.gameround = Gameround.objects.create(user=self.user, gamesession=self.gamesession,
                                                  created=datetime.now(), score=0)
        self.game_data = {'gametype': self.gametype,
                                 'gamesession': self.gamesession,
                                 'gameround': self.gameround,
                                 'resource': self.resource}
        self.response = self.client.get('http://localhost:8000/api/game/',
                                        self.game_data,
                                        format="json")

    def test_get(self):
        self.client = APIClient()
        response = self.client.get('http://localhost:8000/api/game/')
        self.assertEqual(response.status_code, 200)

When I run my test, I get the ValueError: Cannot assign "(<Gametype: imageLabeler>,)": "Gamesession.gametype" must be a "Gametype" instance.

How can I make my test pass?

Update:
This is my View:

class GameView(APIView):

    def get(self, request, *args, **kwargs):
        gametype = Gametype.objects.all().get(name="imageLabeler")
        gametype_serializer = GametypeSerializer(gametype)

        current_score = 0
        if not isinstance(request.user, CustomUser):
            current_user_id = 1
        else:
            current_user_id = request.user.pk

        gamesession = Gamesession.objects.create(user_id=current_user_id,
                                                 gametype=gametype,
                                                 created=datetime.now())

        random_resource = Resource.objects.all().order_by('?').first()
        first_resource_serializer = ResourceSerializer(random_resource)

        gameround = Gameround.objects.create(user_id=current_user_id,
                                             gamesession=gamesession,
                                             created=datetime.now(),
                                             score=current_score)

        gameround_serializer = GameroundSerializer(gameround)

        start_time = gamesession.created
        # now = timezone.now()
        end_of_game = start_time + timedelta(minutes=5)
        # request.session.set_expiry(300)
        if not datetime.now() == end_of_game:
            return Response({'resource': first_resource_serializer.data, 'gameround': gameround_serializer.data,})

        else:
            return Response(status=status.HTTP_408_REQUEST_TIMEOUT)

    def post(self, request, *args, **kwargs):
        tag_serializer = TagSerializer(data=request.data)
        tagging_serializer = TaggingSerializer(data=request.data)
        gameround_id = request.data.get('gameround_id')
        gameround = Gameround.objects.all().get(id=gameround_id)

        # time where the gameround was created
        start_time = gameround.created
        # time 5 mins after gameround was created
        end_of_game = start_time + timedelta(seconds=20)
        if not datetime.now() == end_of_game:
            if tagging_serializer.is_valid(raise_exception=True):
                tagging_serializer.save(tagging=request.data)
                return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED)
            else:
                return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(status=status.HTTP_408_REQUEST_TIMEOUT)

This is the traceback of the error:

ERROR [2022-02-08 23:32:20,856] Internal Server Error: /api/game/
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/api/src/artigo_api/frontend/views/game_rest_views.py", line 155, in get
    gametype = Gametype.objects.get(name="imageLabeler")
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 435, in get
    raise self.model.DoesNotExist(
frontend.models.Gametype.DoesNotExist: Gametype matching query does not exist.

Body:
    raise self.model.DoesNotExist(
frontend.models.Gametype.DoesNotExist: Gametype matching query does not exist.

You don't have Gametype object with name imageLabeler in database.

you should catch DoesNotExist error to avoid program crash:

try:
    gt = Gametype.objects.get(name="imageLabeler")
except Gametype.DoesNotExist:
    print('Boom boom! here is no imageLabeler in DB')
    return Response(status=status.HTTP_404_NOT_FOUND)

And your another problem is you creating object with name labeler:

self.gametype = Gametype.objects.create(name="labeler", rounds=5, round_duration=60, enabled=True)

But trying to get imageLabeler:

gametype = Gametype.objects.all().get(name="imageLabeler")


问:
Update the table if value is unique
I have a query in reactjs.

The thing is, I want to render a table on my screen, as per the updated data. I am using get api to call the data, but what i need to do is to render the latest data corresponding to unique id. Otherwise show all data.

答:
```<code><tbody>
 {this.props.data && this.props.data.length ?
    (this.props.data.map((item,i,arr) => {
        return (
      // item.a === this.props.data.a ?
         <TableValue
           x={item['x']}
           y={item['y']}
           z={item['z']}
           e={item['e']}
          />
      // :""
</code>```

So this where data is adding to table....Now I need that if let say we have 4 fields---> 2 with same id and 2 with different id. So I need to render 3 fields only . For same id, the updated one should render

Title: Update the table if value is unique

Body:
<tbody>
 {this.props.data && this.props.data.length ?
    (this.props.data.map((item,i,arr) => {
        return (
      // item.a === this.props.data.a ?
         <TableValue
           x={item['x']}
           y={item['y']}
           z={item['z']}
           e={item['e']}
          />
      // :""

So this where data is adding to table....Now I need that if let say we have 4 fields---> 2 with same id and 2 with different id. So I need to render 3 fields only . For same id, the updated one should render


问:
How we can fail the testcase using Toleration threshold and Frustration threshold and how we display that result in summary report in Jmeter dashboard
How we can fail the test case using the Toleration threshold and Frustration threshold and how we display that result in a summary report in the Jmeter dashboard?</p>

答:
How we can fail the test case using the Toleration threshold and Frustration threshold - as of JMeter 5.4.3 it's not possible to "fail" samplers based on the "thresholds"

Assuming point 1 all the results, even if they exceed the thresholds, will be marked as "passed" given the status code is below 400

If you want JMeter to automatically fail the request if its response time exceeds acceptable threshold - consider adding Duration Assertion and set the maximum response time there, if the response time will be higher - JMeter will mark the relevant Sampler(s) as failed.

More information on JMeter Assertions concept: How to Use JMeter Assertions in Three Easy Steps


问:
How does the hash data exchange works with Flink Tables?
I have two Table Sources listen to a Kafka topic using Flink. On the generated graph, the data exchange for the join between these two tables is "hash". However, I did not found any information how the hash works (on a specific field ?) and how it can be configured ?</p>

答:
In the case of a Table join, the hash data exchange is based on the equality clause of the join. E.g., if you are doing

SELECT *
FROM A, B
WHERE A.id = B.id
```

then the stream records from both streams will be hashed on the id field. This will guarantee that all records from both A and B with the same id value will be sent to the same downstream instance. (This is why Flink only supports joins with an equality predicate -- they are much more readily scalable.)

Internally this turns into a keyBy from Flink's DataStream API. A Table/SQL GROUP BY works the same way.

Body:
In the case of a Table join, the hash data exchange is based on the equality clause of the join. E.g., if you are doing

SELECT *
FROM A, B
WHERE A.id = B.id

then the stream records from both streams will be hashed on the id field. This will guarantee that all records from both A and B with the same id value will be sent to the same downstream instance. (This is why Flink only supports joins with an equality predicate -- they are much more readily scalable.)

Internally this turns into a keyBy from Flink's DataStream API. A Table/SQL GROUP BY works the same way.


问:
Automapper: Map to Unknown Destination / GetAllTypeMaps missing in latest Build
Tested with: Automapper 10.1.2-alpha.0.4 (MyGet Build)

We want to map our DomainEvents to public Contracts that do not have any base classes and publish them to a Message Queue/Topic.

As it should be a dynamic mapping, we do not know the target type while the mapping to the destination contract occurs.

For that case, we had the following solution of this Post:
How can I use Automapper to map an object to an unknown destination type? as follows:

public async Task Publish(DomainEvent domainEvent)
{
    this.logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);

    try
    {
        var publicEvent = this.MapToContract(domainEvent);

        await this.publishEndpoint.Publish(publicEvent);
    }
    catch (Exception ex)
    {
        this.logger.LogError("Unexpected exception while publishing domain event.", ex);
    }
}

private object MapToContract(object source)
{
    var sourceType = source.GetType();
    TypeMap? typeMap = null;

    try
    {
        typeMap = this.mapper.ConfigurationProvider
            .GetAllTypeMaps()
            .SingleOrDefault(map => map.SourceType == sourceType);
    }
    catch (InvalidOperationException)
    {
        throw new Exception($"Multiple types for {sourceType.FullName} available. Only one allowed");
    }

    return typeMap is null
        ? throw new Exception($"No type map for {sourceType.FullName} found!")
        : this.mapper.Map(source, sourceType, typeMap.DestinationType);
}
```
<p><code>Publish(DomainEvent domainEvent)</code> gets called as event receiver whenever an domain event is raised.</p>
<p>Since the last version, we can't use the <code>MapToContract</code> method anymore because the <code>GetAllTypeMaps</code> method is not available. I was not able to find any workaround.</p>
<p>Sample of the public event class:</p>
<pre class="lang-cs prettyprint-override"><code>public record EmployeeCreated(int Id, string Name, string FirstName);
</code>```

Any ideas?

答:
Ok, had the same problem.
Solution is to use the internal extension method as follows (see https://docs.automapper.org/en/stable/11.0-Upgrade-Guide.html?highlight=internal#forallmaps-forallpropertymaps-advanced-and-other-missing-apis):

using AutoMapper.Internal;

...

this.mapper.ConfigurationProvider
   .Internal()
   .GetAllTypeMaps()
   ...
```

Body:
Tested with: Automapper 10.1.2-alpha.0.4 (MyGet Build)

We want to map our DomainEvents to public Contracts that do not have any base classes and publish them to a Message Queue/Topic.

As it should be a dynamic mapping, we do not know the target type while the mapping to the destination contract occurs.

For that case, we had the following solution of this Post:
How can I use Automapper to map an object to an unknown destination type? as follows:

public async Task Publish(DomainEvent domainEvent)
{
    this.logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);

    try
    {
        var publicEvent = this.MapToContract(domainEvent);

        await this.publishEndpoint.Publish(publicEvent);
    }
    catch (Exception ex)
    {
        this.logger.LogError("Unexpected exception while publishing domain event.", ex);
    }
}

private object MapToContract(object source)
{
    var sourceType = source.GetType();
    TypeMap? typeMap = null;

    try
    {
        typeMap = this.mapper.ConfigurationProvider
            .GetAllTypeMaps()
            .SingleOrDefault(map => map.SourceType == sourceType);
    }
    catch (InvalidOperationException)
    {
        throw new Exception($"Multiple types for {sourceType.FullName} available. Only one allowed");
    }

    return typeMap is null
        ? throw new Exception($"No type map for {sourceType.FullName} found!")
        : this.mapper.Map(source, sourceType, typeMap.DestinationType);
}

Publish(DomainEvent domainEvent) gets called as event receiver whenever an domain event is raised.

Since the last version, we can't use the MapToContract method anymore because the GetAllTypeMaps method is not available. I was not able to find any workaround.

Sample of the public event class:

public record EmployeeCreated(int Id, string Name, string FirstName);

Any ideas?


问:
Pandas | time conversions
I have a question concerning time conversion in Python/Pandas. The following is not entirely clear to me.

```<code>t1 = datetime.datetime(2021,9,15,6,0)
tt1 = t1.timestamp()
pd.to_datetime(tt1,unit='s')
[1] Timestamp('2021-09-15 04:00:00')
</code>```

What do I have to change to get the following result:

```<code>[1] Timestamp('2021-09-15 06:00:00')
</code>```

Thank you!

答:
You can offset your time difference to GMT with

pd.to_datetime(tt1, unit='s') + pd.Timedelta('02:00:00')
```

See this answer for more details.

Title: Pandas | time conversions

Body:
I have a question concerning time conversion in Python/Pandas. The following is not entirely clear to me.

t1 = datetime.datetime(2021,9,15,6,0)
tt1 = t1.timestamp()
pd.to_datetime(tt1,unit='s')
[1] Timestamp('2021-09-15 04:00:00')

What do I have to change to get the following result:

[1] Timestamp('2021-09-15 06:00:00')

Thank you!

Body:
You can offset your time difference to GMT with

pd.to_datetime(tt1, unit='s') + pd.Timedelta('02:00:00')

See this answer for more details.


问:
How to comment in body in the Kibana console editor
I do know that if we wanted to comment separately before any GET/POST request we can make it.

But how about if within the body of JSON I wanted to comment.

example:
My aim is to fire query 1. but i wanted to preserve another field for future use for testing only(quert 2), so how can i do that.

Query 1

```<code># this is just a simple comment
GET ingestion/order/_search
{
  "size":0,
      "aggs": {
        "status_aggs": {
          "terms": {
            "field": "compType.keyword"
          }
        }
      }
}
</code>```

Query 2

```<code>GET ingestion/order/_search
    {
      "size":0,
          "aggs": {
            "status_aggs": {
              "terms": {
                "field": "compType.keyword"
               #"field": "statType.keyword"
              }
            }
          }
    }
</code>```

Just wanted to comment out statType line only.
Appreciated your help if someone knows how to do that.

答: Add /* */, for example, /* "field": "statType.keyword" */

Body:
I do know that if we wanted to comment separately before any GET/POST request we can make it.

But how about if within the body of JSON I wanted to comment.

example:
My aim is to fire query 1. but i wanted to preserve another field for future use for testing only(quert 2), so how can i do that.

Query 1

# this is just a simple comment
GET ingestion/order/_search
{
  "size":0,
      "aggs": {
        "status_aggs": {
          "terms": {
            "field": "compType.keyword"
          }
        }
      }
}

Query 2

GET ingestion/order/_search
    {
      "size":0,
          "aggs": {
            "status_aggs": {
              "terms": {
                "field": "compType.keyword"
               #"field": "statType.keyword"
              }
            }
          }
    }

Just wanted to comment out statType line only.
Appreciated your help if someone knows how to do that.


问:
Vue.JS Firefox and Safari don't hides scrollbar when Chrome and Edge do
Im doing a bit of frontend development via Vue.JS and Vuetify. My goal was it to archive a hidden scrollbar (through i know i cannot delete it ^^) and i know that the code snippet shown below should do the job, they are located in the index.html that is used as a template for vue-cli to build the website:

```<code><style>
    html::-webkit-scrollbar { display: none; }
    html { -ms-overflow-style: none; }
</style>
</code>```

On Chrome and MS Edge these works flawlessly but on for example Safari and Firefox it doesn't do a thing - even if its shown in the Developer tools it seems to be just ignored completely. If I put it into each App.vue (I got an Multi Page Project) it seems to work but why? And is there a solution to this Problem?

Greetings

答:
To hide scroll bar on Chrome, Firefox and IE you can use this:

   .hide-scrollbar
{
    overflow: auto;
    -ms-overflow-style: none; /* IE 11 */
    scrollbar-width: none; /* Firefox 64 */
}```

Body:
Im doing a bit of frontend development via Vue.JS and Vuetify. My goal was it to archive a hidden scrollbar (through i know i cannot delete it ^^) and i know that the code snippet shown below should do the job, they are located in the index.html that is used as a template for vue-cli to build the website:

On Chrome and MS Edge these works flawlessly but on for example Safari and Firefox it doesn't do a thing - even if its shown in the Developer tools it seems to be just ignored completely. If I put it into each App.vue (I got an Multi Page Project) it seems to work but why? And is there a solution to this Problem?

Greetings


问:
how can i use laravel code in java script
i want to translate button name in javascript by write laravel code

```<code>$(document).on('click', '.leave-edit-btn', function() {
        $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Edit') }}");
</code>```

how can i do this?

(copied from comment):
this my code when i click on button no translation run

```<code>@section('scripts')
<script>
$(document).on('click', '.leave-edit-btn', function() {
  $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text({{ __('trans.Save') }});
});
</script>
@endsection
</code>```

答:
Using .text(text) to set an elements text requires the parameter to be a string. Use quotes around {{ __('trans.Save') }} like so:

```<code>@section('scripts')
<script>
$(document).on('click', '.leave-edit-btn', function() {
  $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Save') }}");
});
</script>
@endsection
</code>```

Body:
i want to translate button name in javascript by write laravel code

$(document).on('click', '.leave-edit-btn', function() {
        $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Edit') }}");

how can i do this?

(copied from comment):
this my code when i click on button no translation run

@section('scripts')

@endsection

Body:
Using .text(text) to set an elements text requires the parameter to be a string. Use quotes around {{ __('trans.Save') }} like so:

@section('scripts')
<script>
$(document).on('click', '.leave-edit-btn', function() {
  $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Save') }}");
});
</script>
@endsection


问:
Program to find from where the program is called
The requirement is very simple, I want to write a simple hello world program or anything so the program knows about its execution parent. For eg.

Since I am from a Java background I will give a Java example. I want to write a jar that runs and outputs the following:

Running from command line:

```<code>$ java -jar myjar.jar
Hello world called from bash
</code>```

but when running from myscript.sh:

```<code>$ sh myscript.sh
Hello world called from myscript.sh
</code>```

myscript.sh

```<code>#!/bin/bash
#
# runs the jar
java -jar myjar.jar
</code>```

Now, I am language agnostic regarding this so any language/library that can help me achieve this is welcome, the only requirement is it should be able to be called from a bash script and should recognize the script that calls it.

Every idea is welcomed.

答:
You can get the caller and the command with all its arguments as a string by passing the $PPID variable to ps, example:

```<code>printf "Called from: %s\n" "$(ps -o args= $PPID)"
</code>```

Sample output:

```<code>Called from: /bin/bash ./caller.sh
</code>```

For more output options see the ps man page

Body:
The requirement is very simple, I want to write a simple hello world program or anything so the program knows about its execution parent. For eg.

Since I am from a Java background I will give a Java example. I want to write a jar that runs and outputs the following:

Running from command line:

$ java -jar myjar.jar
Hello world called from bash

but when running from myscript.sh:

$ sh myscript.sh
Hello world called from myscript.sh

myscript.sh

#!/bin/bash
#
# runs the jar
java -jar myjar.jar

Now, I am language agnostic regarding this so any language/library that can help me achieve this is welcome, the only requirement is it should be able to be called from a bash script and should recognize the script that calls it.

Every idea is welcomed.

Body:
You can get the caller and the command with all its arguments as a string by passing the $PPID variable to ps, example:

printf "Called from: %s\n" "$(ps -o args= $PPID)"

Sample output:

Called from: /bin/bash ./caller.sh

For more output options see the ps man page


问:
How to remove an item from 2 array's with the same order?
So I am trying to remove 2 items from 2 different array's. One with value and one without value but has the same order as the first array.(also I am using discord.js).
Here's the code- https://sourceb.in/gUtLbIMoBr
I can't upload it here as it contains more then 50 lines.
Please help.</p>

答:
You can remove an item from an array like this. And you can it do it multiple times.

When asking a question show your example code and go into more detail.

let arr = ["a","b","c"]
let arr2 = ["A","B","C"]

console.log(arr)
console.log(arr2)

const removeIdx = 1

arr.splice(removeIdx, 1)
arr2.splice(removeIdx, 1)

console.log(arr)
console.log(arr2)```


问:
I/O error on GET request for Try again; nested exception is java.net.UnknownHostException: Try again
Technologies: Java + Spring boot(2.5.2). I have upgraded my application from Java 8 to Java 11 (OpenJDK).

Previously I received below error so that I used do-while loop to retry until receive success response.

Java 8 - received success response less than 5 attempts

Java 11 - at 10th attempt also I am receiving same error

Error Log:

I/O error on POST request for "https://<externalurl>": <externalurl>; nested exception is java.net.UnknownHostException: <externalurl>

```<code>@Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new ResponseErrorHandler());
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setOutputStreaming(false);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }
</code>```

答:
Custom docker image with the combination of Alpine v3.11.3 and OpenJDK 11 working for me. There is some issue with DNS resolution in all other versions of Alpine (Latest version v3.15.0 also).

We will face similar issue in Debian OS - retry logic like sending same request again will work

Body:
Technologies: Java + Spring boot(2.5.2). I have upgraded my application from Java 8 to Java 11 (OpenJDK).

Previously I received below error so that I used do-while loop to retry until receive success response.

Java 8 - received success response less than 5 attempts

Java 11 - at 10th attempt also I am receiving same error

Error Log:

I/O error on POST request for "https://<externalurl>": <externalurl>; nested exception is java.net.UnknownHostException: <externalurl>

@Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new ResponseErrorHandler());
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setOutputStreaming(false);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }


问:
How to add a popup to add a hyperlink to a cell in Excel?
I am new to Excel. I have a data sheet, and a lot of users have to enter their data in the sheet. I have a column with the header - 'linkToData'. Whenever a user clicks on a cell, there has to be a popup, which asks for the 'link text', and 'URL', so the user can enter it easily, than using 'Insert --> Link --> Insert Link'. How do I do this customization? Can you please help?

Thanks.

答:
If the existing right-click menu item "Link" is not sufficient, then you can try intercepting the SelectionChange() event for the sheet.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim nCol As Integer
    nCol = Target.Column

    If Target.Row > 1 And Cells(1, nCol) = "linkToData" Then
        If Target.Hyperlinks.Count = 0 Then
            Application.Dialogs(xlDialogInsertHyperlink).Show
        End If
    End If
End Sub
</code>```

Put this code in the VBA module for your sheet (eg "Sheet1(Sheet1)").

If the top cell in the column is "linkToData", and there isn't already a Hyperlink in the cell, then show the Insert Link dialog. You could write you own input form, but this dialog does what you need.

Body:
If the existing right-click menu item "Link" is not sufficient, then you can try intercepting the SelectionChange() event for the sheet.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim nCol As Integer
    nCol = Target.Column

    If Target.Row > 1 And Cells(1, nCol) = "linkToData" Then
        If Target.Hyperlinks.Count = 0 Then
            Application.Dialogs(xlDialogInsertHyperlink).Show
        End If
    End If
End Sub

Put this code in the VBA module for your sheet (eg "Sheet1(Sheet1)").

If the top cell in the column is "linkToData", and there isn't already a Hyperlink in the cell, then show the Insert Link dialog. You could write you own input form, but this dialog does what you need.


问:
Meeting request declined due to conflict for meeting room but graph api return response
I am creating meeting room event using microsoft graph api. Now I am trying to book same meeting room for same time. Now it declined from outlook message but graph api gives response like it is created. Why it is not declining event response. The other issue is for this declined event, invitation has been sent to attendee. Why it is not responding with decline response?</p>

答:
I got an answer from Microsoft person like this :

Meeting request from organizer side will be created and the invitation to other attendees will also be send. you are getting declined message back because the room resource is managed by the server and it will return the message based on the free/busy schedule and the event won't create in room resource calendar but it will created in the organizer and other attendees calendar.

Here meeting room is considered like other attendees and it is a default behavior that if one attendee declines the meeting it doesn't remove the organizers meeting request.


问:
Place div to the right side of the text
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

答:
You can only use width as min-content; for your text element.

For example:

width: min-content;
```

Title: Place div to the right side of the text

Body:
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

    Loooooooong teeeeeext

    Short text


问:
Google Sheets API returns "The caller does not have permission" when using server key
I've generated a server key in the API Manager and attempted to execute the following on my Mac:

```<code>curl 'https://sheets.googleapis.com/v4/spreadsheets/MySheetID?ranges=A1:B5&key=TheServerKeyIGeneratedInAPIManager'
</code>```

But this is what it returns:

```<code>{
 "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}
</code>```

What am I doing wrong here?

答:
In my case, solving this problem turned out to be trivial. You just have to:

Enter the google sheet that we want to remotely edit.

In the upper right corner, set - anyone who has the link can enter

Most importantly - on the right side you need to set permissions for people who have the link as 'editor'

if you still do not have permission, it means that you have to go to the website:
https://console.developers.google.com/iam-admin/iam/ then select your project, then select "Service accounts" and create a new one as role "owner" or" editor" for the project for example (or use one that already exists and click "create new key")

The "key" is a json file that will be downloaded when you create the account (or use "create new key" there).

ContentLicense: CC BY-SA 3.0

Body:
I've generated a server key in the API Manager and attempted to execute the following on my Mac:

curl 'https://sheets.googleapis.com/v4/spreadsheets/MySheetID?ranges=A1:B5&key=TheServerKeyIGeneratedInAPIManager'

But this is what it returns:

{
 "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

What am I doing wrong here?


问:
Is AES a viable solution for creating a hash verification system?
I am writing a program that and like to implement data verification system. It needs to return a unique string for any value entered.  My question boils down to: is it possible for an AES function to return the same value for two different entries? The source values will becoming from data held on a magnetic stripe card.

more details

I posted this through my phone originally, and I am now just getting back to this post.

I've been looking around the web and while reading Wikipedia's article on SHA, I see that SHA-2 (SHA-256/224, SHA-512/384) have no detected collisions (assuming the article is accurate/up-to-date). This is desirable. Any recommendations on what version of SHA-2 I should use?

答:
Based on the new question, I would say:

You should use whatever version of SHA you would like, given that you have the storage space to hold it.

I almost always use SHA-512 for everything, because it holds the lowest chance of collisions, and 64 bytes is usually small enough to store.

OwnerDisplayName: Anders

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Anders

OwnerDisplayName: John Gietzen


答:
```<code>Perhaps this will help?

.your-class {
    /*FireFox*/
    scrollbar-width: none;
    /*IE10+*/
    -ms-overflow-style: -ms-autohiding-scrollbar;
}
.your-class::-webkit-scrollbar {
    /*Chrome, Safari, Edge*/
    display: none;
}
</code>```

Title: Vue.JS Firefox and Safari don't hides scrollbar when Chrome and Edge do


问:
Why store.getState() doesn't update in reduxjs/toolkit
Does anyone know why though through the "useSelector" hook, the updated state is available, but the store.getState() doesn't update?

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    baseUrl: "http://example.com/"
}

function changeToLocal(state) {
    return {...state, baseUrl: "https://localhost:345345/"}
}
function changeToGlobal(state) {
    return { ...state, baseUrl: "http://example.com/"}
}

const ApiConfig = createSlice({
    name: 'changeBaseURL',
    initialState,
    reducers: {
        changeToLocal,
        changeToGlobal,
    }
})

export const {
    changeToLocal: changeToLocalAction,
    changeToGlobal: changeToGlobalAction,
} = ApiConfig.actions

export default ApiConfig.reducer;```
</div>
</div>
</p>
<p>Here after dispatching, through the "useSelector" hook, the updated state is recieved:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Header = () => {
    const dispatch = useDispatch())
    const CurrentBaseURL= useSelector(state => state.changeBaseURL.baseUrl)
    console.log(" ~ file: header.jsx ~ line 11 ~ Header ~ CurrentBaseURL", CurrentBaseURL)
    const changeBaseURl = (e) => {
        if (e.target.value === "local") {
            dispatch(changeToLocalAction())
        } else if (e.target.value === "global"){
            dispatch(changeToGlobalAction())
        }
    }
...</code>```

:

But when I wanted to use the updated baseURL in my APIConfig file, I realized that it didn't update:

import { Toast } from '../../helpers/Toast';
import axios from 'axios';
import store from '../../redux/store';
import { useSelector } from 'react-redux';
    const instance = axios.create({
        baseURL: "htttp://example.com",
        timeout: 10000,
        headers: { "x-Custom-Header": "foobar" }
    })
    instance.interceptors.response.use(response => {
        if (response.headers["token-user"]) {
            localStorage.setItem("token", response.headers["token-user"]);
        }
        if (response.data && response.data.statusIcon && response.data.status) {
            Toast(response.data.statusIcon, response.data.status);
        }
        return response;
    }, err => {
        const expectErrors = err.response && err.response > 400 && err.response.status < 500;
        if (!expectErrors) {
            console.log(err);
        return Promise.reject(err);

    });
    export default instance;```
</div>
</div>
</p>
<p>The above config is used like so:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Api from '../../../utils/request/api/Api'

export const GetDisposablePassword = (nationalCode) => {
    return Api.post(`api/Auth/GetDisposablePassword`, { nationalCode })
};</code>```

Does anyone know the answer or have a better idea?

答:
My best guess here is that you config file is not your application, wrapped by the store provider.

EDIT - To clarify :

```<code>const state = store.getState();
</code>```

Can only be used inside a component mounted in your application that is wrapped by the store provider.

Since your .config file is not wrapped and mounted in your application and wrapped by your provider, it is normal to get an undefined value.

Body:
Does anyone know why though through the "useSelector" hook, the updated state is available, but the store.getState() doesn't update?

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    baseUrl: "http://example.com/"
}

function changeToLocal(state) {
    return {...state, baseUrl: "https://localhost:345345/"}
}
function changeToGlobal(state) {
    return { ...state, baseUrl: "http://example.com/"}
}

const ApiConfig = createSlice({
    name: 'changeBaseURL',
    initialState,
    reducers: {
        changeToLocal,
        changeToGlobal,
    }
})

export const {
    changeToLocal: changeToLocalAction,
    changeToGlobal: changeToGlobalAction,
} = ApiConfig.actions

export default ApiConfig.reducer;

Here after dispatching, through the "useSelector" hook, the updated state is recieved:

const Header = () => {
    const dispatch = useDispatch())
    const CurrentBaseURL= useSelector(state => state.changeBaseURL.baseUrl)
    console.log(" ~ file: header.jsx ~ line 11 ~ Header ~ CurrentBaseURL", CurrentBaseURL)
    const changeBaseURl = (e) => {
        if (e.target.value === "local") {
            dispatch(changeToLocalAction())
        } else if (e.target.value === "global"){
            dispatch(changeToGlobalAction())
        }
    }
...

:

But when I wanted to use the updated baseURL in my APIConfig file, I realized that it didn't update:

import { Toast } from '../../helpers/Toast';
import axios from 'axios';
import store from '../../redux/store';
import { useSelector } from 'react-redux';
    const instance = axios.create({
        baseURL: "htttp://example.com",
        timeout: 10000,
        headers: { "x-Custom-Header": "foobar" }
    })
    instance.interceptors.response.use(response => {
        if (response.headers["token-user"]) {
            localStorage.setItem("token", response.headers["token-user"]);
        }
        if (response.data && response.data.statusIcon && response.data.status) {
            Toast(response.data.statusIcon, response.data.status);
        }
        return response;
    }, err => {
        const expectErrors = err.response && err.response > 400 && err.response.status < 500;
        if (!expectErrors) {
            console.log(err);
        return Promise.reject(err);

    });
    export default instance;

The above config is used like so:

import Api from '../../../utils/request/api/Api'

export const GetDisposablePassword = (nationalCode) => {
    return Api.post(`api/Auth/GetDisposablePassword`, { nationalCode })
};

Does anyone know the answer or have a better idea?

Body:
My best guess here is that you config file is not your application, wrapped by the store provider.

EDIT - To clarify :

const state = store.getState();

Can only be used inside a component mounted in your application that is wrapped by the store provider.

Since your .config file is not wrapped and mounted in your application and wrapped by your provider, it is normal to get an undefined value.


问:
How can I do a regex replace using a List as the possible match entires?
I have a list of terms which I want to match as follows:

```<code>final List _emotions = [
  '~~wink~~',
  '~~bigsmile~~',
  '~~sigh~~',
];
</code>```

And a second list of replacements:

```<code>final List _replacements = [
  '0.gif',
  '1.gif',
  '2.gif',
];
</code>```

SO that if I have text:

```<code>var text = "I went to the store and got a ~~bigsmile~~";
</code>```

I could have it replace the text as

```<code>I went to the store and got a <img src="1.gif" />
</code>```

So essentially, I was thinking of running a regex replace on my text variable,  but the search pattern would be based on my _emotions List.

Forming the replacement text should be easy, but I'm not sure how I could use the list as the basis for the search terms

How is this possible in dart?

答:
You need to merge the two string lists into a single Map<String, String> that will serve as a dictionary (make sure the _emotions strings are in lower case since you want a case insensitive matching), and then join the _emotions strings into a single alternation based pattern.

After getting a match, use String#replaceAllMapped to find the right replacement for the found emotion.

Note you can shorten the pattern if you factor in the ~~ delimiters (see code snippet below). You might also apply more advanced techniques for the vocabulary, like regex tries (see my YT video on this topic).

final List<String> _emotions = [
    'wink',
    'bigsmile',
    'sigh',
];
final List<String> _replacements = [
    '0.gif',
    '1.gif',
    '2.gif',
];
Map<String, String> map = Map.fromIterables(_emotions, _replacements);
String text = "I went to the store and got a ~~bigsmile~~";
RegExp regex = RegExp("~~(${_emotions.join('|')})~~", caseSensitive: false);
print(text.replaceAllMapped(regex, (m) => ''));
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>I went to the store and got a <img src="1.gif" />
</code>```

Body:
I have a list of terms which I want to match as follows:

final List _emotions = [
  '~~wink~~',
  '~~bigsmile~~',
  '~~sigh~~',
];

And a second list of replacements:

final List _replacements = [
  '0.gif',
  '1.gif',
  '2.gif',
];

SO that if I have text:

var text = "I went to the store and got a ~~bigsmile~~";

I could have it replace the text as

I went to the store and got a

So essentially, I was thinking of running a regex replace on my text variable,  but the search pattern would be based on my _emotions List.

Forming the replacement text should be easy, but I'm not sure how I could use the list as the basis for the search terms

How is this possible in dart?

Body:
You need to merge the two string lists into a single Map<String, String> that will serve as a dictionary (make sure the _emotions strings are in lower case since you want a case insensitive matching), and then join the _emotions strings into a single alternation based pattern.

After getting a match, use String#replaceAllMapped to find the right replacement for the found emotion.

Note you can shorten the pattern if you factor in the ~~ delimiters (see code snippet below). You might also apply more advanced techniques for the vocabulary, like regex tries (see my YT video on this topic).

final List<String> _emotions = [
    'wink',
    'bigsmile',
    'sigh',
];
final List<String> _replacements = [
    '0.gif',
    '1.gif',
    '2.gif',
];
Map<String, String> map = Map.fromIterables(_emotions, _replacements);
String text = "I went to the store and got a ~~bigsmile~~";
RegExp regex = RegExp("~~(${_emotions.join('|')})~~", caseSensitive: false);
print(text.replaceAllMapped(regex, (m) => '<img src="${map[m[1]?.toLowerCase()]}" />'));

Output:

I went to the store and got a <img src="1.gif" />


问:
LayerNorm inside nn.Sequential in torch
I am trying to use LayerNorm inside nn.Sequential in torch. This is what I am looking for-

```<code>import torch.nn as nn

class LayerNormCnn(nn.Module):
    def __init__(self):
        super(LayerNormCnn, self).__init__()
        self.net = nn.Sequential(
                nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
                nn.LayerNorm(),
                nn.ReLU(),
                nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
                nn.LayerNorm(),
                nn.ReLU(),
            )

    def forward(self, x):
        x = self.net(x)
        return x
</code>```

Unfortunately, it doesn't work because LayerNorm requires normalized_shape as input. The code above throws following exception-

```<code>    nn.LayerNorm(),
TypeError: __init__() missing 1 required positional argument: 'normalized_shape'
</code>```

Right now, this is how I have implemented it-

```<code>import torch.nn as nn
import torch.nn.functional as F

class LayerNormCnn(nn.Module):
    def __init__(self, state_shape):
        super(LayerNormCnn, self).__init__()
        self.conv1 = nn.Conv2d(state_shape[0], 32, kernel_size=3, stride=2, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1)

        # compute shape by doing a forward pass
        with torch.no_grad():
            fake_input = torch.randn(1, *state_shape)
            out        = self.conv1(fake_input)
            bn1_size   = out.size()[1:]
            out        = self.conv2(out)
            bn2_size   = out.size()[1:]

        self.bn1 = nn.LayerNorm(bn1_size)
        self.bn2 = nn.LayerNorm(bn2_size)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        return x

if __name__ == '__main__':
    in_shape   = (3, 128, 128)
    batch_size = 32

    model = LayerNormCnn(in_shape)
    x = torch.randn((batch_size,) + in_shape)
    out = model(x)
    print(out.shape)
</code>```

Is it possible to use LayerNorm inside nn.Sequential?

答:
The original layer normalisation paper advised against using layer normalisation in CNNs, as receptive fields around the boundary of images will have different values as opposed to the receptive fields in the actual image content. This issue does not arise with RNNs, which is what layer norm was originally tested for. Are you sure you want to be using LayerNorm? If you're looking to compare a different normalisation technique against BatchNorm, consider GroupNorm. This gets rid of the LayerNorm assumption that all channels in a layer contribute equally to a prediction, which is problematic particularly if the layer is convolutional. Instead, each channel is divided further into groups, that still allows a GN layer to learn different statistics across channels.

Please refer here for related discussion.

Title: LayerNorm inside nn.Sequential in torch

Body:
I am trying to use LayerNorm inside nn.Sequential in torch. This is what I am looking for-

import torch.nn as nn

class LayerNormCnn(nn.Module):
    def __init__(self):
        super(LayerNormCnn, self).__init__()
        self.net = nn.Sequential(
                nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
                nn.LayerNorm(),
                nn.ReLU(),
                nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
                nn.LayerNorm(),
                nn.ReLU(),
            )

    def forward(self, x):
        x = self.net(x)
        return x

Unfortunately, it doesn't work because LayerNorm requires normalized_shape as input. The code above throws following exception-

    nn.LayerNorm(),
TypeError: __init__() missing 1 required positional argument: 'normalized_shape'

Right now, this is how I have implemented it-

import torch.nn as nn
import torch.nn.functional as F

class LayerNormCnn(nn.Module):
    def __init__(self, state_shape):
        super(LayerNormCnn, self).__init__()
        self.conv1 = nn.Conv2d(state_shape[0], 32, kernel_size=3, stride=2, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1)

        # compute shape by doing a forward pass
        with torch.no_grad():
            fake_input = torch.randn(1, *state_shape)
            out        = self.conv1(fake_input)
            bn1_size   = out.size()[1:]
            out        = self.conv2(out)
            bn2_size   = out.size()[1:]

        self.bn1 = nn.LayerNorm(bn1_size)
        self.bn2 = nn.LayerNorm(bn2_size)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        return x

if __name__ == '__main__':
    in_shape   = (3, 128, 128)
    batch_size = 32

    model = LayerNormCnn(in_shape)
    x = torch.randn((batch_size,) + in_shape)
    out = model(x)
    print(out.shape)

Is it possible to use LayerNorm inside nn.Sequential?


问:
user(group) - item(folder), multi-root database with tree structure
¡Ay, caramba! -

this is squeezing my non computer science little brain - please help

I potentially have two DB tables-
The first one a user(folder) table which is a tree structure(parent child)(usersorganised into clients or deptartments)
Its fully editable so new structure(parentid left right etc) needs to be re-written pretty often

I then have an item(folder) table tree structure - Same thing - editable so add, delete, copy, paste, move around... as in http://www.jstree.com/demo - (the PHP MYSQL editable functionality)

NB I expect the depth of the tree to rarely be more than 5 so depth first is not really necessary...although I am considering it (safer) - there are however going to be one hell of a lot of items and potentially users.

Just looking for a bit of direction after googleing for ages...
Problem 1 - One table or two? - One table would be lovely ...only the entire DBtable would need to be re-written on a save if Im moving folders around. Considering that this structure needs to monitor all users and item...its a big SQL UPDATE

Problem 2 - Multiple root tree structures... If i just wanted to access the structure at say...user 5(root) play about and save a portion of the tree I'm opening myself up to left/right / id's being corrupt.

Basically the requirements are to have users login - They can then manage their user structure which can be organised into folders(clients).
Then allow those logged in users to add item folders(organizing items) to other users and have the functionality to be able to copy(add,rename,move,delete) item folders across users...so that those users (when logged in) can only view those items.

pheew. hope i've explained this ok

答:
I spoke to one of our top DBAs for some assistance on the matter.

The principle problem with these types of design is not the number of tables but the type of use.

If it is a single user system the use of one table is not a problem, it is a little messy to manage, but the merge command can help here.

If the data is to be accessed simultaneously by a number of users this kind of structure can cause locking problems.

"I would go for two tables with the first holding the data and second holding just the relationship information parent to child.  If you have multiple relationships between items
I.e a parent having many children it would have multiple rows in the relationship table. (Oracle have adopted this approach for their foreign key relationships (Parent- Child))"

Hope this helps


问:
How can I retrieve all members when querying for appRoleAssignedTo in Microsoft Graph?
I am attempting to programmatically retrieve a list of users (principalType = "User") and their associated appRoleId values for an enterprise app using itsresourceId value from Azure AD.  There is a total of ten Users with a combined total of twenty appRoleId values associated with the app.  However, when I run my query I receive data for just two users and a combined total of four appRoleId values.

Here's my C# code:

```<code>GraphServiceClient myGraphClient = GetGraphServiceClient([scopes]);
// Retrieve the [Id] value for the app.  Note [Id] is a pseudonym for the [resourceId] required to retrieve users and app roles assigned.
var servPrinPage = await myGraphClient.ServicePrincipals.Request()
   .Select("id,appRoles")
   .Filter($"startswith(displayName, 'Display Name')")
   .GetAsync()
   .ConfigureAwait(false);
// Using the first [Id] value from the [ServicePrincipals] page, retrieve the list of users and their assigned roles for the app.
var appRoleAssignedTo = await myGraphClient.ServicePrincipals[servPrinPage[0].Id].AppRoleAssignedTo.Request().GetAsync().ConfigureAwait(false);
</code>```

The query returns a ServicePrincipalAppRoleAssignedToCollectionPage (as expected) but the collection only contains four pages (one per User/appRoleId combination).

As an aside, the following query in Microsoft Graph Explorer produces an equivalent result:

```<code>https://graph.microsoft.com/v1.0/servicePrincipals/[resourceId]/appRoleAssignedTo
</code>```

What am I missing here?  I need to be able to retrieve the complete list of users and assigned app roles.  Any assistance is greatly appreciated.

答: Could you please remove "Filter" from the code and retry the operation. Let us know if that worked.</p>

Body:
I am attempting to programmatically retrieve a list of users (principalType = "User") and their associated appRoleId values for an enterprise app using itsresourceId value from Azure AD.  There is a total of ten Users with a combined total of twenty appRoleId values associated with the app.  However, when I run my query I receive data for just two users and a combined total of four appRoleId values.

Here's my C# code:

GraphServiceClient myGraphClient = GetGraphServiceClient([scopes]);
// Retrieve the [Id] value for the app.  Note [Id] is a pseudonym for the [resourceId] required to retrieve users and app roles assigned.
var servPrinPage = await myGraphClient.ServicePrincipals.Request()
   .Select("id,appRoles")
   .Filter($"startswith(displayName, 'Display Name')")
   .GetAsync()
   .ConfigureAwait(false);
// Using the first [Id] value from the [ServicePrincipals] page, retrieve the list of users and their assigned roles for the app.
var appRoleAssignedTo = await myGraphClient.ServicePrincipals[servPrinPage[0].Id].AppRoleAssignedTo.Request().GetAsync().ConfigureAwait(false);

The query returns a ServicePrincipalAppRoleAssignedToCollectionPage (as expected) but the collection only contains four pages (one per User/appRoleId combination).

As an aside, the following query in Microsoft Graph Explorer produces an equivalent result:

https://graph.microsoft.com/v1.0/servicePrincipals/[resourceId]/appRoleAssignedTo

What am I missing here?  I need to be able to retrieve the complete list of users and assigned app roles.  Any assistance is greatly appreciated.


问:
Is there any way to get the height of a single page if you would print the page as a pdf?
I'm trying to render a pdf from dynamic content with puppeteer and react. The layouting is done in material ui for react, so page-break-before:always is not an option because i need the grid layout which is flex and wont work with page-break-before. I need to get the height of one page, so the header of the next page doesn't overflow. If i calculate where the header should be with pagewidth * Math.sqrt(2), it gives me the position value of where it actually is. But unfortunally when i go to print it it's overflowing by a few pixels and the error is getting bigger with each page. I have wondered how to fix this problem for the last 2 days. I've even tried resetting the position with a margin.

Here are some code snippets from my program which might maybe help.

```<code>let width = 800//document.documentElement.getBoundingClientRect().width
for (let pagewidth = width; pagewidth * Math.sqrt(2) < document.documentElement.getBoundingClientRect().height; pagewidth += width) {
  let pageBreakXPosition = Math.ceil(Math.sqrt(2) * pagewidth)
  header.style.marginTop = pageBreakXPosition - header.getBoundingClientRect().top + "px"
}
</code>```

this is just the "important" part of the code because all of the other code targets the elements' width or some other styles. My problem would really be fixed if i just knew the exact point where the page would break, but appareantly my calculation for pageBreakXPosition is wrong in some way.

attached is a picture of the overflow(if you look carefully you can see that the error is getting bigger):

Page 2

Page 4

答: I think you can set the height as per your requirement and that should work</p>

Body:
I'm trying to render a pdf from dynamic content with puppeteer and react. The layouting is done in material ui for react, so page-break-before:always is not an option because i need the grid layout which is flex and wont work with page-break-before. I need to get the height of one page, so the header of the next page doesn't overflow. If i calculate where the header should be with pagewidth * Math.sqrt(2), it gives me the position value of where it actually is. But unfortunally when i go to print it it's overflowing by a few pixels and the error is getting bigger with each page. I have wondered how to fix this problem for the last 2 days. I've even tried resetting the position with a margin.

Here are some code snippets from my program which might maybe help.

let width = 800//document.documentElement.getBoundingClientRect().width
for (let pagewidth = width; pagewidth * Math.sqrt(2) < document.documentElement.getBoundingClientRect().height; pagewidth += width) {
  let pageBreakXPosition = Math.ceil(Math.sqrt(2) * pagewidth)
  header.style.marginTop = pageBreakXPosition - header.getBoundingClientRect().top + "px"
}

this is just the "important" part of the code because all of the other code targets the elements' width or some other styles. My problem would really be fixed if i just knew the exact point where the page would break, but appareantly my calculation for pageBreakXPosition is wrong in some way.

attached is a picture of the overflow(if you look carefully you can see that the error is getting bigger):

Page 2

Page 4


问:
AWS API Gateway Integration Request setup automation
I am trying to use the AWS API Gateway+Swagger to route the request to my express backend. I can't figure out how to automate the setup of the integration request as the Swagger file has no details on it.

I'm also having difficulty with the endpoint url parameter when setting my method requests to GET/VPC Link on the integration type

For example:

My api gateway path is /info/car/{model}/aggregate

Now the endpoint url is http://carapi.com/info/car/{model}/aggregate

I have lots of gateway paths all of which are the same paths that my carapi.com site uses, so I don't want to keep retyping the path over and over. When entering in the endpoint url, I was able to simplify not having to type carapi.com by using stage variables turning my endpoint url to

http://${stageVariables.carApi}/info/car/{model}/aggregate

However after reading https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#stagevariables-template-reference

I see that there is also a $context available, but it gives me an error(when I try to call the api in postman, says 'internal server error' for the message) when I try to implement the context (which through that link shows that I can implement the path).

http://${stageVariables.carApi}/${context.resourcePath}

So my question is: how do I automate the setup of Integration requests so I don't have to manually setup each and every one(as I have hundreds of paths)? Is there also anyway to not have to set the paths manually for the endpoints?

答:
I don't know of any solution which is ready to use.

In my project, we wrote a custom solution that downloads the application Swagger json, parses it, adds the required integration and generates another json file. Then we import that into API Gateway. This has been converted as a Jenkins job and runs as a post job of microservice deployment.

Another way is, instead of generating the json, directly call API Gateway APIs and add the integration.


问:
Arduino/ESP8266 debounce (using interrupt) fails only when time difference is zero between pulses
I have an ESP8266 (NodeMCU) development board. I'm trying to implement software debounce on a tactile push-button connected to GPIO5 while using an interrupt. For the "relayPin" I'm temporarily using the onboard LED (GPIO16).

The debounce works for the most part when I try to push the button down and wiggle it very rapidly. However, it fails on rare occasion and only when the time gap is zero between two different detected pulses. So essentially, it never fails when the time gap is above 0 and below the debounce time (200ms). Please see the image of the serial monitor.

While this issue occurs under extreme conditions (the switch will not be used in this manner), I'd still like to figure out if this is something to do with my code or another aspect I'm not aware of.

Image 1: Push-button circuit

Image 2: Code & serial monitor

```<code>int swButton = 5;
int relayPin = 16;

bool relayOn = false;   // Present on/off state of the relay.

int debounceTime = 200;   // Debounce time in ms.

volatile bool switchToggle = false;   // True when button press is valid (and not bounce noise).
volatile unsigned long nowPush = 0;   // The millis() time of the present button press.
volatile unsigned long lastPush = 0;  // The millis() time of the previous button press.
volatile unsigned long timeGap = 0;  // The difference of the nowPush and lastPush times.

// Interrupt Service Routine on button press (falling edge).
ICACHE_RAM_ATTR void swButtonISR() {
  nowPush = millis();
  timeGap = nowPush - lastPush;

  // Debouncing stuff, recognizing this button-press as a valid one.
  if (timeGap > debounceTime) {
    switchToggle = true;
    lastPush = nowPush;
  }
}

// Function that toggles the relay when called upon.
void toggleRelay () {
    if (relayOn) {
      digitalWrite(relayPin, LOW);   // Turn off relay.
      relayOn = false;
      Serial.println((String)"Relay ON.   Time gap: "+timeGap);
      return;
    }
    else {
      digitalWrite(relayPin, HIGH);    // Turn on relay.
      relayOn = true;
      Serial.println((String)"Relay OFF.  Time gap: "+timeGap);
      return;
    }
    return;
}

void setup() {
  Serial.begin(115200);
  pinMode(swButton, INPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(greenLED, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(swButton), swButtonISR, FALLING);
}

void loop() {
  if (switchToggle == true) {
    toggleRelay();
    switchToggle = false;
  }
}
</code>```

答:
There are a couple of changes you can make to also force a longer delay after "button release". (You could also just attach ONE interrupt handler with the CHANGE condition, to catch both FALLING and RISING edges.)

Add this

```<code>attachInterrupt(digitalPinToInterrupt(swButton), swButtonISR2, RISING);
</code>```

change this

```<code>ICACHE_RAM_ATTR void swButtonISR() {
    nowPush = millis();
    timeGap = nowPush - lastPush;

    // Debouncing stuff, recognizing this button-press as a valid one.
    if (timeGap > debounceTime) {
        switchToggle = true;
    }
    lastPush = nowPush;
}
</code>```

add this

```<code>ICACHE_RAM_ATTR void swButtonISR2() {
    lastPush = millis();
}
</code>```

Body:
I have an ESP8266 (NodeMCU) development board. I'm trying to implement software debounce on a tactile push-button connected to GPIO5 while using an interrupt. For the "relayPin" I'm temporarily using the onboard LED (GPIO16).

The debounce works for the most part when I try to push the button down and wiggle it very rapidly. However, it fails on rare occasion and only when the time gap is zero between two different detected pulses. So essentially, it never fails when the time gap is above 0 and below the debounce time (200ms). Please see the image of the serial monitor.

While this issue occurs under extreme conditions (the switch will not be used in this manner), I'd still like to figure out if this is something to do with my code or another aspect I'm not aware of.

Image 1: Push-button circuit

Image 2: Code & serial monitor

int swButton = 5;
int relayPin = 16;

bool relayOn = false;   // Present on/off state of the relay.

int debounceTime = 200;   // Debounce time in ms.

volatile bool switchToggle = false;   // True when button press is valid (and not bounce noise).
volatile unsigned long nowPush = 0;   // The millis() time of the present button press.
volatile unsigned long lastPush = 0;  // The millis() time of the previous button press.
volatile unsigned long timeGap = 0;  // The difference of the nowPush and lastPush times.

// Interrupt Service Routine on button press (falling edge).
ICACHE_RAM_ATTR void swButtonISR() {
  nowPush = millis();
  timeGap = nowPush - lastPush;

  // Debouncing stuff, recognizing this button-press as a valid one.
  if (timeGap > debounceTime) {
    switchToggle = true;
    lastPush = nowPush;
  }
}

// Function that toggles the relay when called upon.
void toggleRelay () {
    if (relayOn) {
      digitalWrite(relayPin, LOW);   // Turn off relay.
      relayOn = false;
      Serial.println((String)"Relay ON.   Time gap: "+timeGap);
      return;
    }
    else {
      digitalWrite(relayPin, HIGH);    // Turn on relay.
      relayOn = true;
      Serial.println((String)"Relay OFF.  Time gap: "+timeGap);
      return;
    }
    return;
}

void setup() {
  Serial.begin(115200);
  pinMode(swButton, INPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(greenLED, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(swButton), swButtonISR, FALLING);
}

void loop() {
  if (switchToggle == true) {
    toggleRelay();
    switchToggle = false;
  }
}

Body:
There are a couple of changes you can make to also force a longer delay after "button release". (You could also just attach ONE interrupt handler with the CHANGE condition, to catch both FALLING and RISING edges.)

Add this

attachInterrupt(digitalPinToInterrupt(swButton), swButtonISR2, RISING);

change this

ICACHE_RAM_ATTR void swButtonISR() {
    nowPush = millis();
    timeGap = nowPush - lastPush;

    // Debouncing stuff, recognizing this button-press as a valid one.
    if (timeGap > debounceTime) {
        switchToggle = true;
    }
    lastPush = nowPush;
}

add this

ICACHE_RAM_ATTR void swButtonISR2() {
    lastPush = millis();
}


问:
Why I can't pass string literals to const char* const& in this specialized function template
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

```<code>// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}
</code>```

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

```<code>void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}
</code>```

答: Oh, I changed the code to std::cout << count<const char*>(sVec, "cpp") << std::endl; Then everything is fine. It seems like compiler treats the string literal "cpp" as a const char [4] rather than const char* const&, so I have to explicitly specify the template parameter. Wonder why that happened.

Body:
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}


问:
QT is there a way to delay signal and/or abandon signal?
I am looking for a way to delay or abandon signal under some circumstances.

My GUI looks like that - I have a MainWindow frame, which contains QStackedWidget with several QWidgets. Each QWidget 'provides' mainIcon to the parent widget (MainWindow), which is then connected to a slot realizing switching between pages functionality.

I want to connect this mainIcon to a signal, show a QMessageBox and if user confirms - everything will happen normally (a signal will be passed and analyzed by parent Widget) - after a delay(user has to confirm).

However, if he declines, a signal should not be passed, and nothing should happen.

What I have came up with so far is:

```<code>connect(mainIcon, &GuiIconAction::clicked, this, [=](){
        //block signals of mainIcon - should be somehow ensured that this is the first realized slot
        if(confirmRequired)
        {
            if(QMessageBox::warning(this, "Manager",
                                    "Are you sure you want to switch window?",
                                    QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
                return;
        //get blocked signals and call them
        }
    });
</code>```

Important notes are:

GuiIconAction is a QToolButton,

Widget don't know that the parent exists (i.e. it just provides interface, but could also be placed standalone)

I don't want to realize this functionality in parent widget (MainWindow), as it is only a frame - I want it to be realized on the level of particular Widget in QStackedWidget

答:
I would suggest to implement the functionality with a slot.
In the slot you can create the message box. If the user confirms, emit a signal. Otherwise not.</p>

Body:
I am looking for a way to delay or abandon signal under some circumstances.

My GUI looks like that - I have a MainWindow frame, which contains QStackedWidget with several QWidgets. Each QWidget 'provides' mainIcon to the parent widget (MainWindow), which is then connected to a slot realizing switching between pages functionality.

I want to connect this mainIcon to a signal, show a QMessageBox and if user confirms - everything will happen normally (a signal will be passed and analyzed by parent Widget) - after a delay(user has to confirm).

However, if he declines, a signal should not be passed, and nothing should happen.

What I have came up with so far is:

connect(mainIcon, &GuiIconAction::clicked, this, [=](){
        //block signals of mainIcon - should be somehow ensured that this is the first realized slot
        if(confirmRequired)
        {
            if(QMessageBox::warning(this, "Manager",
                                    "Are you sure you want to switch window?",
                                    QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
                return;
        //get blocked signals and call them
        }
    });

Important notes are:

GuiIconAction is a QToolButton,

Widget don't know that the parent exists (i.e. it just provides interface, but could also be placed standalone)

I don't want to realize this functionality in parent widget (MainWindow), as it is only a frame - I want it to be realized on the level of particular Widget in QStackedWidget