问:
how to solve federatedSignin_AWS error Please retry by calling `getIdentityId()` method.")?
Please help me out I am stuck on it for many days

Current userState: signedIn
identityIdUnavailable(message: "Fetching identity id on another thread failed. Please retry by calling getIdentityId() method.")

AWS Social login with GoogleSignIn with firebase after getting token pass the token to

func federatedSignin_AWS(with token: String) {
    guard let plugin = try? Amplify.Auth.getPlugin(for: AWSCognitoAuthPlugin().key) as? AWSCognitoAuthPlugin,
          case let .awsMobileClient(client) = plugin.getEscapeHatch() else {
              print("Failed to fetch escape hatch")

              return
          }

    client.federatedSignIn(providerName: "etc", token: token) { (userState, error) in
        guard error == nil, let userState = userState else {
            print("Error in federatedSignIn: \(error!)")

            return
        }
        print("Current userState: \(userState)")

        client.getIdentityId().continueWith { task in
            guard task.error == nil, let result = task.result else {
                print(task.error ?? "")

                return task
            }
            print("AWS token is: " + String(result))

            DispatchQueue.main.async {
                self.loaderSubView.removeFromSuperview()

                //---------------------------------------------Create User Table in Dynamo DB------------------------------------------------

                Amplify.API.query(request: .get(UserTable.self, byId: self.userID)) { event in
                    switch event {
                    case .success(let result):
                        switch result {
                        case .success(let users):
                            guard let users = users else {
                                print("Could not find todo")
                                //-----------------------------------if table not created already in the dynamodb ---------------------------------------------------------------
                                let users = UserTable(id: self.userID, userCreatedDate: "", userModifyDate: "", userName: self.userName, userEmailAddress: self.userEmail, userPhoneNo: self.userPhoneNumber, profilePicture: "", token: "", AppPurchaseDate: "", AppPurchaseExpireDate: "", planInMB: "", isInAppPurchased: "")

                                Amplify.API.mutate(request: .create(users)) { event in
                                    switch event {
                                    case .success(let result):
                                        switch result {
                                        case .success(let users):
                                            print("Successfully created the todo: \(users)")
                                            self.getUserProfile()
                                            DispatchQueue.main.async {
                                                let storyBoard : UIStoryboard = UIStoryboard(name: "SideMenu", bundle:nil)
                                                let vc = storyBoard.instantiateViewController(withIdentifier: "EditProfileVC") as! EditProfileVC
                                                vc.isFromSocialLogin = true
                                                self.navigationController?.pushViewController(vc, animated: true)
                                            }
                                        case .failure(let graphQLError):
                                            print("Failed to create graphql \(graphQLError)")
                                        }
                                    case .failure(let apiError):
                                        print("Failed to create a todo", apiError)
                                    }
                                }

                                return
                            }
                            //-----------------------------------if table already created ---------------------------------------------------------------
                            DispatchQueue.main.async {
                                self.getUserProfile()
                                let storyBoard : UIStoryboard = UIStoryboard(name: "SideMenu", bundle:nil)
                                let nextViewController = storyBoard.instantiateViewController(withIdentifier: "EditProfileVC") as! EditProfileVC
                                nextViewController.isFromSocialLogin = true
                                self.navigationController?.pushViewController(nextViewController, animated: true)
                                print("Successfully retrieved todo: \(users)")
                            }
                            //----------------------------------------------------------------------------------------------------------------------------
                        case .failure(let error):
                            print("Got failed result with \(error.errorDescription)")
                        }
                    case .failure(let error):
                        print("Got failed event with error \(error)")
                    }
                }

                //----------------------------------------------------------------------------------------------------------------------------------------
            }

            return task
        }
    }
}
```

My expected result is the awsclient get identity id without error

Body:
Please help me out I am stuck on it for many days

Current userState: signedIn
identityIdUnavailable(message: "Fetching identity id on another thread failed. Please retry by calling getIdentityId() method.")

AWS Social login with GoogleSignIn with firebase after getting token pass the token to

func federatedSignin_AWS(with token: String) {
    guard let plugin = try? Amplify.Auth.getPlugin(for: AWSCognitoAuthPlugin().key) as? AWSCognitoAuthPlugin,
          case let .awsMobileClient(client) = plugin.getEscapeHatch() else {
              print("Failed to fetch escape hatch")

              return
          }

    client.federatedSignIn(providerName: "etc", token: token) { (userState, error) in
        guard error == nil, let userState = userState else {
            print("Error in federatedSignIn: \(error!)")

            return
        }
        print("Current userState: \(userState)")

        client.getIdentityId().continueWith { task in
            guard task.error == nil, let result = task.result else {
                print(task.error ?? "")

                return task
            }
            print("AWS token is: " + String(result))

            DispatchQueue.main.async {
                self.loaderSubView.removeFromSuperview()

                //---------------------------------------------Create User Table in Dynamo DB------------------------------------------------

                Amplify.API.query(request: .get(UserTable.self, byId: self.userID)) { event in
                    switch event {
                    case .success(let result):
                        switch result {
                        case .success(let users):
                            guard let users = users else {
                                print("Could not find todo")
                                //-----------------------------------if table not created already in the dynamodb ---------------------------------------------------------------
                                let users = UserTable(id: self.userID, userCreatedDate: "", userModifyDate: "", userName: self.userName, userEmailAddress: self.userEmail, userPhoneNo: self.userPhoneNumber, profilePicture: "", token: "", AppPurchaseDate: "", AppPurchaseExpireDate: "", planInMB: "", isInAppPurchased: "")

                                Amplify.API.mutate(request: .create(users)) { event in
                                    switch event {
                                    case .success(let result):
                                        switch result {
                                        case .success(let users):
                                            print("Successfully created the todo: \(users)")
                                            self.getUserProfile()
                                            DispatchQueue.main.async {
                                                let storyBoard : UIStoryboard = UIStoryboard(name: "SideMenu", bundle:nil)
                                                let vc = storyBoard.instantiateViewController(withIdentifier: "EditProfileVC") as! EditProfileVC
                                                vc.isFromSocialLogin = true
                                                self.navigationController?.pushViewController(vc, animated: true)
                                            }
                                        case .failure(let graphQLError):
                                            print("Failed to create graphql \(graphQLError)")
                                        }
                                    case .failure(let apiError):
                                        print("Failed to create a todo", apiError)
                                    }
                                }

                                return
                            }
                            //-----------------------------------if table already created ---------------------------------------------------------------
                            DispatchQueue.main.async {
                                self.getUserProfile()
                                let storyBoard : UIStoryboard = UIStoryboard(name: "SideMenu", bundle:nil)
                                let nextViewController = storyBoard.instantiateViewController(withIdentifier: "EditProfileVC") as! EditProfileVC
                                nextViewController.isFromSocialLogin = true
                                self.navigationController?.pushViewController(nextViewController, animated: true)
                                print("Successfully retrieved todo: \(users)")
                            }
                            //----------------------------------------------------------------------------------------------------------------------------
                        case .failure(let error):
                            print("Got failed result with \(error.errorDescription)")
                        }
                    case .failure(let error):
                        print("Got failed event with error \(error)")
                    }
                }

                //----------------------------------------------------------------------------------------------------------------------------------------
            }

            return task
        }
    }
}

My expected result is the awsclient get identity id without error


来源: stackexchange

问:
Getting InvalidParameterValue: Missing final '@domain' while sending email in aws ses nodejs
I am using lambda function to send email using aws ses. My account is in production and domain is also verified but still i am not able to send email using aws ses. I am getting this error

```<code>2022-12-28T09:57:42.851Z    9334073b-987b-47aa-bb57-54a92ad7d09e    ERROR   InvalidParameterValue: Missing final '@domain'
    at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/query.js:50:29)
    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:686:14)
    at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:688:12)
    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
  code: 'InvalidParameterValue',
  time: 2022-12-28T09:57:42.849Z,
  requestId: 'e5854086-b690-4faf-bb79-f6e54a655508',
  statusCode: 400,
  retryable: false,
  retryDelay: 67.29353748593772
</code>```

  const params = {
    Destination: {
      ToAddresses: ["alpha.prime0502@gmail.com"]
    },
    Message: {
      Body: {
        Html: {
         Charset: "UTF-8",
         Data: resetPasswordEmail(name,passcode)
        },
       },
       Subject: {
        Data: subject
       }
    },
    Source: "readwise.mksmohan.com",
  };

  try {
    const result = await ses.sendEmail(params).promise();

    return result;
  } catch (error) {
    console.error(error);
  }
```

ContentLicense: CC BY-SA 4.0

Body:
I am using lambda function to send email using aws ses. My account is in production and domain is also verified but still i am not able to send email using aws ses. I am getting this error

2022-12-28T09:57:42.851Z    9334073b-987b-47aa-bb57-54a92ad7d09e    ERROR   InvalidParameterValue: Missing final '@domain'
    at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/query.js:50:29)
    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:686:14)
    at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:688:12)
    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
  code: 'InvalidParameterValue',
  time: 2022-12-28T09:57:42.849Z,
  requestId: 'e5854086-b690-4faf-bb79-f6e54a655508',
  statusCode: 400,
  retryable: false,
  retryDelay: 67.29353748593772

  const params = {
    Destination: {
      ToAddresses: ["alpha.prime0502@gmail.com"]
    },
    Message: {
      Body: {
        Html: {
         Charset: "UTF-8",
         Data: resetPasswordEmail(name,passcode)
        },
       },
       Subject: {
        Data: subject
       }
    },
    Source: "readwise.mksmohan.com",
  };

  try {
    const result = await ses.sendEmail(params).promise();

    return result;
  } catch (error) {
    console.error(error);
  }


问:
How can we use LocationRequest.Builder in requestLocationUpdates() function as a parameter
As LocationRequest.create() is deprecated and instead of it we shall use LocationRequest.Builder but when i pass this in requestLocationUpdates() as a parameter, it shows error.

Here's my code:

```<code>private boolean isLocationpermissionOk;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private FusedLocationProviderClient fusedLocationProviderClient;
</code>```
```<code>@RequiresApi(api = Build.VERSION_CODES.S)
private void setUpLocationUpdate() {
    locationRequest= new LocationRequest.Builder(10000).build();
    locationCallback=new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            if(locationResult!=null) {
                for(Location location : locationResult.getLocations()){
                    Log.d("TAG","onLocationResult"+location.getLongitude()+" "+location.getLatitude());
                }
            }
            super.onLocationResult(locationResult);

        }
    };
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.getMainLooper())
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(requireContext(), "Location Updated Started", Toast.LENGTH_SHORT).show();
                    }
                }
            });
</code>```

Body:
As LocationRequest.create() is deprecated and instead of it we shall use LocationRequest.Builder but when i pass this in requestLocationUpdates() as a parameter, it shows error.

Here's my code:

private boolean isLocationpermissionOk;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private FusedLocationProviderClient fusedLocationProviderClient;

@RequiresApi(api = Build.VERSION_CODES.S)
private void setUpLocationUpdate() {
    locationRequest= new LocationRequest.Builder(10000).build();
    locationCallback=new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            if(locationResult!=null) {
                for(Location location : locationResult.getLocations()){
                    Log.d("TAG","onLocationResult"+location.getLongitude()+" "+location.getLatitude());
                }
            }
            super.onLocationResult(locationResult);

        }
    };
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.getMainLooper())
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(requireContext(), "Location Updated Started", Toast.LENGTH_SHORT).show();
                    }
                }
            });


问:
How to configure HSTS in nginx for setup with multiple applications using the same domain (but different subdomains)
I have the following situation/requirements:

Application A:

Should be accessible via domain.com and www.domain.com

Publishes an API via api.domain.com

domain.com and www.domain.com should use the HSTS header

api.domain.com should only be accessible via HTTPS

Application B:

Should be accessible via b.domain.com

Publishes an API via api.b.domain.com

b.domain.com should use the HSTS header

api.b.domain.com should only be accessible via HTTPS

Application C:

Should be accessible via c.domain.com

c.domain.com should not use the HSTS header

All domains (but the api.* domains) should be accessible via HTTP and redirect to HTTPS (as long as the UA does not already have received the HSTS header and anyway will access the domains via HTTPS directly).

Now my issue/question is how to handle Application A. I understand that for Application A, in order to cover both domain.com and www.domain.com, I should redirect both domain.com and www.domain.com to domain.com and then return the HSTS header for domain.com with the includeSubdomains flag. But this flag then covers all subdomains of domain.com, i.e. also the domains which Application B and Application C use (where I either want to control the HSTS settings separately or don't want to use the HSTS header at all).

I could of course not redirect www.domain.com to domain.com and return the HTST header from both www.domain.com to domain.com (depending of what the user accesses) without the includeSubdomains flag. But that would lead so a (small) security issue because the user would have to access both www.domain.com to domain.com before he is "fully" protected in terms of Application A.

What is the best approach (in terms of redirects from www.domain.ch to domain.ch or vice-versa and in terms of redirects from http to https in the unlike cases) in this case?

I basically ask this question on a conceptual level. But once I have clarity what I should do, I need to implement it in Nginx reverse proxy. So if anybody could also provide some sample configuration, that would also be appreciated.


问:
How can I create a draft on a current thread for a Gmail add-on?
I'm trying to make an add-on for Gmail in Apps Script that generates reply drafts by analyzing the thread content.

When I'm using a contextual trigger, the event passed to the function contains the messageId and I can get the message and call the function GmailApp.GmailMessage.createDraftReplyAll to create the draft.
However in order to see the reply draft, I have to go back to the inbox and access the thread again. The behavior I want is to see the reply draft on the thread I'm currently on.

An other way I've tried is to use a compose trigger instead but there is no information in the event that can help me obtain the last message (or the entire thread) content.
Here is the event I get:

```<code>{"clientPlatform":"web","draftMetadata":{"subject":"Re: test","ccRecipients":[],"bccRecipients":[],"toRecipients":["mymail@gmail.com"]},"hostApp":"gmail","gmail":{"toRecipients":["mymail@gmail.com"],"subject":"Re: test"},"commonEventObject":{"hostApp":"GMAIL","platform":"WEB"}}
</code>```

Body:
I'm trying to make an add-on for Gmail in Apps Script that generates reply drafts by analyzing the thread content.

When I'm using a contextual trigger, the event passed to the function contains the messageId and I can get the message and call the function GmailApp.GmailMessage.createDraftReplyAll to create the draft.
However in order to see the reply draft, I have to go back to the inbox and access the thread again. The behavior I want is to see the reply draft on the thread I'm currently on.

An other way I've tried is to use a compose trigger instead but there is no information in the event that can help me obtain the last message (or the entire thread) content.
Here is the event I get:

{"clientPlatform":"web","draftMetadata":{"subject":"Re: test","ccRecipients":[],"bccRecipients":[],"toRecipients":["mymail@gmail.com"]},"hostApp":"gmail","gmail":{"toRecipients":["mymail@gmail.com"],"subject":"Re: test"},"commonEventObject":{"hostApp":"GMAIL","platform":"WEB"}}


问:
Is it possible to make Django switch model variables based on a language?
I have a model with two columns where one is in English, one is in Bulgarian. Currently I am doing this:

```<code>{% if L == "bg" %}
  {{adoption.fields.story_bg|safe}}
{% else %}
  {{adoption.fields.story_eng|safe}}
{% endif %}
</code>```

But this is too much code and it is annoying to type and look at. Is there a simpler way of doing this?

Body:
I have a model with two columns where one is in English, one is in Bulgarian. Currently I am doing this:

{% if L == "bg" %}
  {{adoption.fields.story_bg|safe}}
{% else %}
  {{adoption.fields.story_eng|safe}}
{% endif %}

But this is too much code and it is annoying to type and look at. Is there a simpler way of doing this?


问:
Module not found in nextJs when using slack web API
I'm building a next.js application that uses the slack web API to fetch a list of channels once user is authenticated.

Unfortunately, I'm getting the following error:

Module not found: Can't resolve 'fs'
```
<p>Now, this only happens after I start using the slack client within my app:</p>
```  const getChannels = async (token: string) => {
    const result = await slackClient.channels.list({
      token,
    });

    return result;
  };
  use(getChannels(session?.authToken));
```

I saw a couple of posts on SO mentioning the fs error within next.js apps, but they were all related to middleware, while I'm not using any.

Why would I need to access fs? Do I have to create a custom middleware?

Body:
I'm building a next.js application that uses the slack web API to fetch a list of channels once user is authenticated.

Unfortunately, I'm getting the following error:

Module not found: Can't resolve 'fs'

Now, this only happens after I start using the slack client within my app:

  const getChannels = async (token: string) => {
    const result = await slackClient.channels.list({
      token,
    });

    return result;
  };
  use(getChannels(session?.authToken));

I saw a couple of posts on SO mentioning the fs error within next.js apps, but they were all related to middleware, while I'm not using any.

Why would I need to access fs? Do I have to create a custom middleware?


问:
how to validate the date input field using Yup validation using react hook form
I am getting output like this
but I need to indicate red color for both the error message and date input field

const input_schema = yup.object().shape({
  title: yup.string().required(requiredField).nullable(),
  start: yup.date().required().typeError(requiredField),
  end: yup.date().required().typeError(requiredField),
  description: yup.string().required(requiredField).nullable(),
  location: yup.string().required(requiredField).nullable(),
  category: yup.string().required(requiredField).nullable(),
});
```


问:
How to properly generate and execute a query to a custom database
I have a custom repo to an external database.
I followed the documentation here.

<?php

namespace Homeinfo\SysMon2\Domain\Repository;

use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;

final class CheckResultsRepository
{
    public function __construct(
        private readonly ConnectionPool $connectionPool
    ) {
    }

    public function findBySystem(int $system) {
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('checkresults');
        $statement = $queryBuilder
            ->select('checkresults.*')
            ->from('checkresults')
            ->where(
                $queryBuilder->expr()->eq(
                    'checkresults.system',
                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            );
        DebuggerUtility::var_dump($statement, "Statement: ");
        $statement->executeStatement();
    }
}
```
<p>This, however, results in the error:</p>
```
(1/1) TypeError

TYPO3\CMS\Core\Database\Query\QueryBuilder::executeStatement(): Return value must be of type int, Doctrine\DBAL\ForwardCompatibility\Result returned
in /srv/http/de/homeinfo/typo3/my-new-project/public/typo3/sysext/core/Classes/Database/Query/QueryBuilder.php line 329

    public function executeStatement(): int
    {
        // @todo Call $this->concreteQueryBuilder->executeStatement()
        //        directly with doctrine/dbal:^3.2 raise in v12.
        return $this->concreteQueryBuilder->execute();
    }

    /**
     * Gets the complete SQL string formed by the current specifications of this QueryBuilder.

at TYPO3\CMS\Core\Database\Query\QueryBuilder->executeStatement()
in /srv/http/de/homeinfo/typo3/my-new-project/packages/sysmon2/Classes/Domain/Repository/CheckResultsRepository.php line 30

                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            );
        DebuggerUtility::var_dump($statement, "Statement: ");
        $statement->executeStatement();
    }
}
```

What am I doing wrong here?

Body:
I have a custom repo to an external database.
I followed the documentation here.

<?php

namespace Homeinfo\SysMon2\Domain\Repository;

use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;

final class CheckResultsRepository
{
    public function __construct(
        private readonly ConnectionPool $connectionPool
    ) {
    }

    public function findBySystem(int $system) {
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('checkresults');
        $statement = $queryBuilder
            ->select('checkresults.*')
            ->from('checkresults')
            ->where(
                $queryBuilder->expr()->eq(
                    'checkresults.system',
                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            );
        DebuggerUtility::var_dump($statement, "Statement: ");
        $statement->executeStatement();
    }
}

This, however, results in the error:

(1/1) TypeError

TYPO3\CMS\Core\Database\Query\QueryBuilder::executeStatement(): Return value must be of type int, Doctrine\DBAL\ForwardCompatibility\Result returned
in /srv/http/de/homeinfo/typo3/my-new-project/public/typo3/sysext/core/Classes/Database/Query/QueryBuilder.php line 329

    public function executeStatement(): int
    {
        // @todo Call $this->concreteQueryBuilder->executeStatement()
        //        directly with doctrine/dbal:^3.2 raise in v12.
        return $this->concreteQueryBuilder->execute();
    }

    /**
     * Gets the complete SQL string formed by the current specifications of this QueryBuilder.

at TYPO3\CMS\Core\Database\Query\QueryBuilder->executeStatement()
in /srv/http/de/homeinfo/typo3/my-new-project/packages/sysmon2/Classes/Domain/Repository/CheckResultsRepository.php line 30

                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            );
        DebuggerUtility::var_dump($statement, "Statement: ");
        $statement->executeStatement();
    }
}

What am I doing wrong here?


问:
Android 12 suppport for configurable policy
As details provided in below link , I have tried to make global configuration to make it configurable so that it can enable configurable audio policy to check for vendor specific .xml

https://source.android.com/docs/core/audio/implement-policy

But still when I check for dumpsys of media.audio_flinger , Hw module shows only default speaker related information.

Can someone help me to have configurable Audio Policy

Tried to set global configuration as configurable as below

```<code><audioPolicyConfiguration>
    <globalConfiguration engine_library="configurable" />
...
</audioPolicyConfiguration>
</code>```

But did not worked

Body:
As details provided in below link , I have tried to make global configuration to make it configurable so that it can enable configurable audio policy to check for vendor specific .xml

https://source.android.com/docs/core/audio/implement-policy

But still when I check for dumpsys of media.audio_flinger , Hw module shows only default speaker related information.

Can someone help me to have configurable Audio Policy

Tried to set global configuration as configurable as below

<audioPolicyConfiguration>
    <globalConfiguration engine_library="configurable" />
...
</audioPolicyConfiguration>

But did not worked


问:
async Dynamic partial view using action
System.Web.HttpException: 'Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.'
InvalidOperationException: HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete.
my partail view codemy render controller methode
My get method that is async to call api

i tried to access render partial view but fails i want dynamic  async partial view using @html.Action or any other

Title: async Dynamic partial view using action


问:
In postgresql, copy a view from one database on remote server to a table on local server
I have a remote postgresql server running with views in one of the schema. I need to copy the data from a view in the remote database server and put it in a new table in my local database server

Assume

remote

remote host: hostA

remote port: 5432

remote db: dbA

remote schema: schemaA

remote user: userA

remote password: passA

local

local host: hostB

local port: 5432

local db: dbB

local schema: schemaB

local user: userB

local password: passB


问:
SVD recommendation : How to split train data and test data? | How to apply SVD in test mode?
The problem is that I can finish SVD on my whole dataset (movielens user-item rating matrix), but the homework requires splitting train data and test data and I don't know how to do. And if it's in test mode what's the usage of u,s,v (the result of SVD) and how can I calculate the user-item matrix (very very confused).

I can finish the SVD based on the user-item matrix to fulfill it.
Just have no clue about how can I do train and test.


问:
How to block loading of a specific .js file?
I need to block uploading module.js file for site for my convenience. This file simply uploads by  tag. In the HTML code, it looks like this:

```<code><script charset="utf-8" id="yui_3_17_2_1_1672056888038_9" src="https://exam.lood.so/lib/javascript.php/1671548766/mod/quiz/module.js" async=""></script>
</code>```

I'm thinking of doing it in Tampermonkey.

Here I have a script that catches all requests in the
xhr/fetch,
but I need to abort the file in the "JS" tab.

```<code>(function() {
    let _open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
       _open.call(this, method, url, async=async, user=user, password=password)
    }
    let _send = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(data) {
        let _onload  = this.onprogress;
        this.onload = function() {
            console.log(this.responseURL)
            if (this.responseURL == "my_url") {
                console.log("gotcha here!")
            }
            if (_onload != null) {
                _onload.call(this)
            }
        }
        _send.call(this, data)
    }
})();
</code>```

Blocking in devtools is not solution because since each time to block this request, you need to go here.

Body:
I need to block uploading module.js file for site for my convenience. This file simply uploads by  tag. In the HTML code, it looks like this:

I'm thinking of doing it in Tampermonkey.

Here I have a script that catches all requests in the
xhr/fetch,
but I need to abort the file in the "JS" tab.

(function() {
    let _open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
       _open.call(this, method, url, async=async, user=user, password=password)
    }
    let _send = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(data) {
        let _onload  = this.onprogress;
        this.onload = function() {
            console.log(this.responseURL)
            if (this.responseURL == "my_url") {
                console.log("gotcha here!")
            }
            if (_onload != null) {
                _onload.call(this)
            }
        }
        _send.call(this, data)
    }
})();

Blocking in devtools is not solution because since each time to block this request, you need to go here.


问:
Read a specific object from a CollectionGroup
I have a collection within another (CollectionGroup) and now I want to read a specific object from it. Currently I'm trying as shown below, but I'm not getting any result:

```<code>db.collectionGroup("Objekte")
  .whereEqualTo("timestamp",key.toString())
  .get()
  .addOnSuccessListener { doc->
    for (document : doc) {
        if(document != null)
        {
            Log.d("TAG", "DocumentSnapshot data: ${document.data}")
       } else{
            Log.d("TAG", "No such document")
       }
    }
}
</code>```

TIMESTAMP LOGOUT:

TIMESTAMP:1672216119769

Body:
I have a collection within another (CollectionGroup) and now I want to read a specific object from it. Currently I'm trying as shown below, but I'm not getting any result:

db.collectionGroup("Objekte")
  .whereEqualTo("timestamp",key.toString())
  .get()
  .addOnSuccessListener { doc->
    for (document : doc) {
        if(document != null)
        {
            Log.d("TAG", "DocumentSnapshot data: ${document.data}")
       } else{
            Log.d("TAG", "No such document")
       }
    }
}

TIMESTAMP LOGOUT:

TIMESTAMP:1672216119769


问:
C++ compilation error on visual studio 2008
I am using visual studio 2008 due to some compatibility issues, i am getting the following error while building my project -

fatal error C1083: Cannot open include file: 'vcruntime.h' : No such file or directory.
I even installed Windows sdk and included the path in my workstation but this error is just taking my time, oit has been almost a day now, i even tried to search this 'vcruntime.h' but its not present in my system

i would love to here some suggestions,

tried installing windows sdk and added to my projects path but not working


问:
How to close browser with ending browser session in webdriverio?
I have following test cases - in wdio.conf.js:

```<code>afterTest: async function (test, context, { error, result, duration, passed, retries }) {

await browser.end(); // Error thrown browser.end is not a function
// await browser.closewindows(); // No session found after test 1 execute
// await browser.close(); // Error thrown browser.end is not a function
},
beforeTest: async function (test, context) {
    await browser.url("/");
    await browser.maximizeWindow();
}
</code>```

In Test File:

```<code>Describe("Suite 1", async () => {
it("test 1", async () => {
 - perform different task on browser
 - logout()
});
it("test 2", async () => {
 - perform different task on browser
 - logout()
});
it("test 3", async () => {
 - perform different task on browser
 - logout()
});
});
</code>```

I want to open browser on EACH TEST (it block) under describe block and once EACH TEST is completed I want to close browser. and so on for each it block.

I have used close(), closewindow() and end() methods but no use. Error commented near each method.

Body:
I have following test cases - in wdio.conf.js:

afterTest: async function (test, context, { error, result, duration, passed, retries }) {

await browser.end(); // Error thrown browser.end is not a function
// await browser.closewindows(); // No session found after test 1 execute
// await browser.close(); // Error thrown browser.end is not a function
},
beforeTest: async function (test, context) {
    await browser.url("/");
    await browser.maximizeWindow();
}

In Test File:

Describe("Suite 1", async () => {
it("test 1", async () => {
 - perform different task on browser
 - logout()
});
it("test 2", async () => {
 - perform different task on browser
 - logout()
});
it("test 3", async () => {
 - perform different task on browser
 - logout()
});
});

I want to open browser on EACH TEST (it block) under describe block and once EACH TEST is completed I want to close browser. and so on for each it block.

I have used close(), closewindow() and end() methods but no use. Error commented near each method.


问:
SDP being modified while sending in SIP packet
im struggling with trying to hold the current call.
i noticed that the SDP has the parameter a=sendonly value which is correct but it's being modified to a=sendrecv while sending SDP with SIP packet:
Im using SIP.js with React Native Environment.

Code:

```<code>const options: SessionInviteOptions = {
          sessionDescriptionHandlerModifiers: this.holdState
                ? []
                : [holdModifier],
            };
this.session.invite(options);
</code>```

Output:

sip.sessionDescriptionHandler:

```<code>sip.sessionDescriptionHandler | sdp is v=0

o=- 7531569285136237213 6 IN IP4 127.0.0.1

s=-

t=0 0

a=group:BUNDLE audio

a=extmap-allow-mixed

a=msid-semantic: WMS FD023174-1814-41B9-8A33-A4ABE314A28C

c=IN IP4 185.63.92.97

a=rtcp:9 IN IP4 0.0.0.0

a=ice-ufrag:M/IT

a=ice-pwd:sroDMNtHVklewZOTihWmBIRk

a=ice-options:trickle renomination

a=setup:actpass

a=mid:audio

a=sendonly

a=rtcp-mux

a=rtpmap:111 opus/48000/2

a=rtcp-fb:111 transport-cc

a=fmtp:111 minptime=10;useinbandfec=1

a=rtpmap:63 red/48000/2

a=fmtp:63 111/111
</code>```

sip.Transport | Sending WebSocket message:

```<code>sip.Transport | Sending WebSocket message:

INVITE sip:+33184807573@185.63.92.49:5080;transport=udp SIP/2.0

Route: <sip:185.63.93.210:443;transport=ws;r2=on;lr>

Route: <sip:185.63.93.210;r2=on;lr>

Via: SIP/2.0/TCP tn1ok329u7cv.invalid;branch=z9hG4bK2337389

To: <sip:+33184807573@sip211-dc3.ring.com>;tag=NFQZFyjFyjm9g

From: "testeur v1" <sip:123.9kz9y4.abc@sip211-dc3.ring.com>;

CSeq: 3 INVITE

Call-ID: vlmhl6qfn7cgv071rpke

Max-Forwards: 70

Allow: ACK,BYE,CANCEL,INFO,INVITE,MESSAGE,NOTIFY,OPTIONS,PRACK,REFER...

Contact: <sip:apfps17j@tn1ok329u7cv.invalid;transport=ws;ob>

Supported: outbound

User-Agent: Rin/RN ios 0.1

Content-Type: application/sdp

Content-Length: 1792

v=0

o=- 7531569285136237213 7 IN IP4 127.0.0.1

s=-

t=0 0

a=group:BUNDLE audio

a=extmap-allow-mixed

a=msid-semantic: WMS FD023174-1814-41B9-8A33-A4ABE314A28C

c=IN IP4 185.63.92.97

a=rtcp:9 IN IP4 0.0.0.0

a=ice-ufrag:M/IT

a=ice-pwd:sroDMNtHVklewZOTihWmBIRk

a=ice-options:trickle renomination

a=setup:actpass

a=mid:audio

a=sendrecv
</code>```

Thanks

Body:
im struggling with trying to hold the current call.
i noticed that the SDP has the parameter a=sendonly value which is correct but it's being modified to a=sendrecv while sending SDP with SIP packet:
Im using SIP.js with React Native Environment.

Code:

const options: SessionInviteOptions = {
          sessionDescriptionHandlerModifiers: this.holdState
                ? []
                : [holdModifier],
            };
this.session.invite(options);

Output:

sip.sessionDescriptionHandler:

sip.sessionDescriptionHandler | sdp is v=0

o=- 7531569285136237213 6 IN IP4 127.0.0.1

s=-

t=0 0

a=group:BUNDLE audio

a=extmap-allow-mixed

a=msid-semantic: WMS FD023174-1814-41B9-8A33-A4ABE314A28C

c=IN IP4 185.63.92.97

a=rtcp:9 IN IP4 0.0.0.0

a=ice-ufrag:M/IT

a=ice-pwd:sroDMNtHVklewZOTihWmBIRk

a=ice-options:trickle renomination

a=setup:actpass

a=mid:audio

a=sendonly

a=rtcp-mux

a=rtpmap:111 opus/48000/2

a=rtcp-fb:111 transport-cc

a=fmtp:111 minptime=10;useinbandfec=1

a=rtpmap:63 red/48000/2

a=fmtp:63 111/111

sip.Transport | Sending WebSocket message:

sip.Transport | Sending WebSocket message:

INVITE sip:+33184807573@185.63.92.49:5080;transport=udp SIP/2.0

Route: <sip:185.63.93.210:443;transport=ws;r2=on;lr>

Route: <sip:185.63.93.210;r2=on;lr>

Via: SIP/2.0/TCP tn1ok329u7cv.invalid;branch=z9hG4bK2337389

To: <sip:+33184807573@sip211-dc3.ring.com>;tag=NFQZFyjFyjm9g

From: "testeur v1" <sip:123.9kz9y4.abc@sip211-dc3.ring.com>;

CSeq: 3 INVITE

Call-ID: vlmhl6qfn7cgv071rpke

Max-Forwards: 70

Allow: ACK,BYE,CANCEL,INFO,INVITE,MESSAGE,NOTIFY,OPTIONS,PRACK,REFER...

Contact: <sip:apfps17j@tn1ok329u7cv.invalid;transport=ws;ob>

Supported: outbound

User-Agent: Rin/RN ios 0.1

Content-Type: application/sdp

Content-Length: 1792

v=0

o=- 7531569285136237213 7 IN IP4 127.0.0.1

s=-

t=0 0

a=group:BUNDLE audio

a=extmap-allow-mixed

a=msid-semantic: WMS FD023174-1814-41B9-8A33-A4ABE314A28C

c=IN IP4 185.63.92.97

a=rtcp:9 IN IP4 0.0.0.0

a=ice-ufrag:M/IT

a=ice-pwd:sroDMNtHVklewZOTihWmBIRk

a=ice-options:trickle renomination

a=setup:actpass

a=mid:audio

a=sendrecv

Thanks


问:
How can I use MUI TextField with "select" and "multiple" props?
I am trying to create multiple select input but had problem with the TextField because it is not accepting multiple props My TextField is shown in the code block.

```<code> <TextField
  label={crmFieldTitleMap(value, t)}
  size="small"
  variant="outlined"
  select
  multiple
  value={....}
  onChange={....}
  input={<OutlinedInput />}
  renderValue={....}
  MenuProps={MenuProps}
>
    {value.options.length &&
      value.options.map((item) => (
        <MenuItem key={crmFieldTitleMap(item, t)} value={item.value}>
          <Checkbox
            checked={
              crmPostData[value.value]
                ? crmPostData[value.value].includes(item.value)
                : false
            }
          />
          <ListItemText primary={crmFieldTitleMap(item, t)} />
        </MenuItem>
      ))}
</TextField>;

</code>```

With TextField I can't select multiple items but label seems pretty nice

Then I found a solution to choose multiple select which I used   and  as shown in the code block.

```<code><FormControl className="w-full ">
  <InputLabel id="multiple_select_thingy">{titleMultiple(value, t)}</InputLabel>

  <Select
    labelId="multiple_select_thingy"
    label={titleMultiple(value, t)}
    size="small"
    variant="outlined"
    multiple
    disabled={....}
    value={....}
    onChange={....}
    input={<OutlinedInput />}
    renderValue={....}
    MenuProps={MenuProps}
  >
    {value.options.length &&
      value.options.map((item) => (
        <MenuItem key={crmFieldTitleMap(item, t)} value={item.value}>
          <Checkbox
            checked={
              crmPostData[value.value]
                ? crmPostData[value.value].includes(item.value)
                : false
            }
          />
          <ListItemText primary={crmFieldTitleMap(item, t)} />
        </MenuItem>
      ))}
  </Select>
</FormControl>;

</code>```

With Select I can select multiple items perfectly but the label seems weird.

Also when there are no items selected input gets weird too

Body:
I am trying to create multiple select input but had problem with the TextField because it is not accepting multiple props My TextField is shown in the code block.

 <TextField
  label={crmFieldTitleMap(value, t)}
  size="small"
  variant="outlined"
  select
  multiple
  value={....}
  onChange={....}
  input={<OutlinedInput />}
  renderValue={....}
  MenuProps={MenuProps}
>
    {value.options.length &&
      value.options.map((item) => (
        <MenuItem key={crmFieldTitleMap(item, t)} value={item.value}>
          <Checkbox
            checked={
              crmPostData[value.value]
                ? crmPostData[value.value].includes(item.value)
                : false
            }
          />
          <ListItemText primary={crmFieldTitleMap(item, t)} />
        </MenuItem>
      ))}
</TextField>;

With TextField I can't select multiple items but label seems pretty nice

Then I found a solution to choose multiple select which I used   and  as shown in the code block.

<FormControl className="w-full ">
  <InputLabel id="multiple_select_thingy">{titleMultiple(value, t)}</InputLabel>

  <Select
    labelId="multiple_select_thingy"
    label={titleMultiple(value, t)}
    size="small"
    variant="outlined"
    multiple
    disabled={....}
    value={....}
    onChange={....}
    input={<OutlinedInput />}
    renderValue={....}
    MenuProps={MenuProps}
  >
    {value.options.length &&
      value.options.map((item) => (
        <MenuItem key={crmFieldTitleMap(item, t)} value={item.value}>
          <Checkbox
            checked={
              crmPostData[value.value]
                ? crmPostData[value.value].includes(item.value)
                : false
            }
          />
          <ListItemText primary={crmFieldTitleMap(item, t)} />
        </MenuItem>
      ))}
  </Select>
</FormControl>;

With Select I can select multiple items perfectly but the label seems weird.

Also when there are no items selected input gets weird too


问:
How to make a separate thread for each object, asynchronously
How to make a separate thread for each object in exchanges, asynchronously

```<code>async def async_client(exchange):
    client = getattr(ccxta, exchange)()
    tickers = await client.fetch_tickers()
    print(threading.active_count())
    await client.close()
    return tickers

async def multi_tickers(exchanges):
    input_coroutines = [async_client(exchange) for exchange in exchanges]
    tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
    a = print("async call spend:", time.time() - tic)
    return tickers

def asyncios():
    return asyncio.run(multi_tickers(exchanges))

if __name__ == '__main__':

    exchanges = ['binance', 'bitget', 'bitmart', 'bitvavo', 'bybit', 'gate', 'huobi', 'kucoin', 'mexc', 'okx']
    tic = time.time()
    for _ in range(len(exchanges)):
        b = threading.Thread(target=asyncios)
        b.start()
</code>```

I want all exchanges to be requested at the same time.
Thanks in advance.

Body:
How to make a separate thread for each object in exchanges, asynchronously

async def async_client(exchange):
    client = getattr(ccxta, exchange)()
    tickers = await client.fetch_tickers()
    print(threading.active_count())
    await client.close()
    return tickers

async def multi_tickers(exchanges):
    input_coroutines = [async_client(exchange) for exchange in exchanges]
    tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
    a = print("async call spend:", time.time() - tic)
    return tickers

def asyncios():
    return asyncio.run(multi_tickers(exchanges))

if __name__ == '__main__':

    exchanges = ['binance', 'bitget', 'bitmart', 'bitvavo', 'bybit', 'gate', 'huobi', 'kucoin', 'mexc', 'okx']
    tic = time.time()
    for _ in range(len(exchanges)):
        b = threading.Thread(target=asyncios)
        b.start()

I want all exchanges to be requested at the same time.
Thanks in advance.


问:
how to check the nested subdocument field is true or false
i need to check a specific nested subdocument field in the document true or false,
i know my scheme is more nested but i dont have any other option

this is my document model

```<code>[{
  "_id": {
    "$oid": "63844ad47389ec0e773d73f3"
  },
  "bid": "637b4ec45688ffbe092af629",
  "name": "hari",
  "start_date": "2022-25-11",
  "end_date": "2022-28-11",
  "start_time": "09:00:00",
  "end_time": "11:00:00",
  "excuse": "10",
  "slots": [
    {
      "date": "2022-11-23T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,    // need to check this field
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73f5"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73f6"
          }
        }

      ],
      "_id": {
        "$oid": "63844ad47389ec0e773d73f4"
      }
    },
    {
      "date": "2022-11-24T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73fc"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73fd"
          }
        }
      ],
      "_id": {
        "$oid": "63844ad47389ec0e773d73fb"
      }
    }
  ],
  "__v": 0
}]
</code>```

i need to check the  slots.slots.avaiable is true or not how to check this field
can anyone suggest me the exact query to find this ?

specification

node : v14.17.3
mongoose: ^6.6.5,
mogodb: Atlas

Body:
i need to check a specific nested subdocument field in the document true or false,
i know my scheme is more nested but i dont have any other option

this is my document model

[{
  "_id": {
    "$oid": "63844ad47389ec0e773d73f3"
  },
  "bid": "637b4ec45688ffbe092af629",
  "name": "hari",
  "start_date": "2022-25-11",
  "end_date": "2022-28-11",
  "start_time": "09:00:00",
  "end_time": "11:00:00",
  "excuse": "10",
  "slots": [
    {
      "date": "2022-11-23T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,    // need to check this field
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73f5"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73f6"
          }
        }

      ],
      "_id": {
        "$oid": "63844ad47389ec0e773d73f4"
      }
    },
    {
      "date": "2022-11-24T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73fc"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "63844ad47389ec0e773d73fd"
          }
        }
      ],
      "_id": {
        "$oid": "63844ad47389ec0e773d73fb"
      }
    }
  ],
  "__v": 0
}]

i need to check the  slots.slots.avaiable is true or not how to check this field
can anyone suggest me the exact query to find this ?

specification

node : v14.17.3
mongoose: ^6.6.5,
mogodb: Atlas


问:
how to check the nested subdocument field is true or false
I need to check  a specific nested subdocument field in the document true or false,

I know my schema is more nested but i don't have any other option

this is my document model

```<code>[{
  "_id": {
    "$oid": "773d73f3"
  },
  "bid": "092af629",
  "name": "hari",
  "start_date": "2022-25-11",
  "end_date": "2022-28-11",
  "start_time": "09:00:00",
  "end_time": "11:00:00",
  "excuse": "10",
  "slots": [
    {
      "date": "2022-11-23T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,        // need to check this field
          "status": null,
          "_id": {
            "$oid": "773d73f5"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73f6"
          }
        }

      ],
      "_id": {
        "$oid": "773d73f4"
      }
    },
    {
      "date": "2022-11-24T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73fc"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73fd"
          }
        }
      ],
      "_id": {
        "$oid": "773d73fb"
      }
    }
  ],
  "__v": 0
}]

</code>```

I need to check the  slots.slots.available is true or not.  How to check this field?  Can anyone  suggest me the exact query to find this?

specification

node :v14.17.3,

mongoose: "^6.6.5",

mongodb:Atlas

Body:
I need to check  a specific nested subdocument field in the document true or false,

I know my schema is more nested but i don't have any other option

this is my document model

[{
  "_id": {
    "$oid": "773d73f3"
  },
  "bid": "092af629",
  "name": "hari",
  "start_date": "2022-25-11",
  "end_date": "2022-28-11",
  "start_time": "09:00:00",
  "end_time": "11:00:00",
  "excuse": "10",
  "slots": [
    {
      "date": "2022-11-23T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,        // need to check this field
          "status": null,
          "_id": {
            "$oid": "773d73f5"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73f6"
          }
        }

      ],
      "_id": {
        "$oid": "773d73f4"
      }
    },
    {
      "date": "2022-11-24T00:00:00.000Z",
      "slots": [
        {
          "uid": null,
          "start_time": "01:00 AM",
          "end_time": "01:30 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73fc"
          }
        },
        {
          "uid": null,
          "start_time": "01:35 AM",
          "end_time": "02:05 AM",
          "attachment": null,
          "available": true,
          "status": null,
          "_id": {
            "$oid": "773d73fd"
          }
        }
      ],
      "_id": {
        "$oid": "773d73fb"
      }
    }
  ],
  "__v": 0
}]

I need to check the  slots.slots.available is true or not.  How to check this field?  Can anyone  suggest me the exact query to find this?

specification

node :v14.17.3,

mongoose: "^6.6.5",

mongodb:Atlas


问:
Change UIButton gradient background color when tapped (Swift)
I am creating a button that when clicked it will change its own color. The problem is its background color is gradient so i have to addSublayer. But I want to change to another color, when running the machine will crash.

```<code>    @IBAction func actionMute(_ sender:AnyObject!) {

        hasMuted = !hasMuted

        let colorTop =  UIColor(red: 17/255.0, green: 168/255.0, blue: 153/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 1/255.0, green: 107/255.0, blue: 184/255.0, alpha: 1.0).cgColor
        let gradientLayer1 = CAGradientLayer()
        gradientLayer1.colors = [colorTop, colorBottom]
        gradientLayer1.locations = [0.0, 1.0]
        gradientLayer1.frame = self.muteBtn.bounds
        gradientLayer1.cornerRadius = 40

        let gradientLayer2 = CAGradientLayer()
        gradientLayer2.colors = [UIColor.red.cgColor, UIColor.white.cgColor]
        gradientLayer2.locations = [0.0, 1.0]
        gradientLayer2.frame = self.muteBtn.bounds
        gradientLayer2.cornerRadius = 40

        if hasMuted {
            self.muteBtn.layer.borderColor = UIColor(red:248/255, green:249/255, blue:252/255, alpha: 1).cgColor
            self.muteBtn.layer.backgroundColor = UIColor.white.cgColor
            self.muteBtn.layer.sublayers[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer2, at: 0)
        } else {
            self.muteBtn.layer.borderColor = UIColor(red:17/255, green:168/255, blue:253/255, alpha: 1).cgColor

            //background
            self.muteBtn.layer.backgroundColor = colorBottom
            self.muteBtn.layer.sublayers?[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer1, at: 0)
        }
    }
</code>```

The error when app crash like this:

```<code>* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0xee9b537b0)
    frame #0: 0x00000001988fecf4 libobjc.A.dylib`objc_msgSend + 20
libobjc.A.dylib`objc_msgSend:
->  0x1988fecf4 <+20>: ldr    x11, [x16, #0x10]
    0x1988fecf8 <+24>: and    x10, x11, #0xfffffffffffe
    0x1988fecfc <+28>: tbnz   w11, #0x0, 0x1988fed50    ; <+112>
    0x1988fed00 <+32>: eor    x12, x1, x1, lsr #7
Target 0: (Runner) stopped.
[log] methodCallHandler onCallToggleMic
Lost connection to device.
Exited
</code>```

The button like this

After removing the line removeFromSuperlayer(), the app runs normally but not only changes color once.
Is there a way to create a button similar to this?

Body:
I am creating a button that when clicked it will change its own color. The problem is its background color is gradient so i have to addSublayer. But I want to change to another color, when running the machine will crash.

    @IBAction func actionMute(_ sender:AnyObject!) {

        hasMuted = !hasMuted

        let colorTop =  UIColor(red: 17/255.0, green: 168/255.0, blue: 153/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 1/255.0, green: 107/255.0, blue: 184/255.0, alpha: 1.0).cgColor
        let gradientLayer1 = CAGradientLayer()
        gradientLayer1.colors = [colorTop, colorBottom]
        gradientLayer1.locations = [0.0, 1.0]
        gradientLayer1.frame = self.muteBtn.bounds
        gradientLayer1.cornerRadius = 40

        let gradientLayer2 = CAGradientLayer()
        gradientLayer2.colors = [UIColor.red.cgColor, UIColor.white.cgColor]
        gradientLayer2.locations = [0.0, 1.0]
        gradientLayer2.frame = self.muteBtn.bounds
        gradientLayer2.cornerRadius = 40

        if hasMuted {
            self.muteBtn.layer.borderColor = UIColor(red:248/255, green:249/255, blue:252/255, alpha: 1).cgColor
            self.muteBtn.layer.backgroundColor = UIColor.white.cgColor
            self.muteBtn.layer.sublayers[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer2, at: 0)
        } else {
            self.muteBtn.layer.borderColor = UIColor(red:17/255, green:168/255, blue:253/255, alpha: 1).cgColor

            //background
            self.muteBtn.layer.backgroundColor = colorBottom
            self.muteBtn.layer.sublayers?[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer1, at: 0)
        }
    }

The error when app crash like this:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0xee9b537b0)
    frame #0: 0x00000001988fecf4 libobjc.A.dylib`objc_msgSend + 20
libobjc.A.dylib`objc_msgSend:
->  0x1988fecf4 <+20>: ldr    x11, [x16, #0x10]
    0x1988fecf8 <+24>: and    x10, x11, #0xfffffffffffe
    0x1988fecfc <+28>: tbnz   w11, #0x0, 0x1988fed50    ; <+112>
    0x1988fed00 <+32>: eor    x12, x1, x1, lsr #7
Target 0: (Runner) stopped.
[log] methodCallHandler onCallToggleMic
Lost connection to device.
Exited

The button like this

After removing the line removeFromSuperlayer(), the app runs normally but not only changes color once.
Is there a way to create a button similar to this?


问:
Oauth card doesn't return token when sign-in invoke activity is triggered from mobile device
I have implemented an OAuth sign in flow for my teams bot using Microsoft AAD v2 and the OAuthPrompt dialog with the help of this guide.

My dialog definition is as followed:

```<code>AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = configuration["ConnectionName"],
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000,
                EndOnInvalidMessage = true
            }));
</code>```

and I initiate it as the first step of my root dialog

```<code>private async Task<DialogTurnResult> LoginPromptAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}
</code>```

I'm also passing the invoke activity using the OnTeamsSigninVerifyStateAsync function

```<code>protected override async Task OnTeamsSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}
</code>```

It is working fine on the desktop client, but while trying to sign in from my mobile device, the bot receives the response without the token.

The authentication flow is almost similar to the one implemented in this sample

I tried adding 'login.microsoftonline.com' as well as 'token.botframework.com' to validDomains property in the manifest to no avail.
I also added
devicePermissions": [ "openExternal" ]
to the manifest, again to no avail.

I also tried debugging the bot locally and found that the sign in invoke activity from a mobile device results in the following 404 error

UPDATE: I found that the sample (from which I picked up the authentication flow) also fails to login through mobile, I'm unable to figure out whether the problem is something from my side or from the sample code being outdated.

It'd be super helpful if somebody could clone the sample and see if results are the same.

Body:
I have implemented an OAuth sign in flow for my teams bot using Microsoft AAD v2 and the OAuthPrompt dialog with the help of this guide.

My dialog definition is as followed:

AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = configuration["ConnectionName"],
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000,
                EndOnInvalidMessage = true
            }));

and I initiate it as the first step of my root dialog

private async Task<DialogTurnResult> LoginPromptAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}

I'm also passing the invoke activity using the OnTeamsSigninVerifyStateAsync function

protected override async Task OnTeamsSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}

It is working fine on the desktop client, but while trying to sign in from my mobile device, the bot receives the response without the token.

The authentication flow is almost similar to the one implemented in this sample

I tried adding 'login.microsoftonline.com' as well as 'token.botframework.com' to validDomains property in the manifest to no avail.
I also added
devicePermissions": [ "openExternal" ]
to the manifest, again to no avail.

I also tried debugging the bot locally and found that the sign in invoke activity from a mobile device results in the following 404 error

UPDATE: I found that the sample (from which I picked up the authentication flow) also fails to login through mobile, I'm unable to figure out whether the problem is something from my side or from the sample code being outdated.

It'd be super helpful if somebody could clone the sample and see if results are the same.


问:
Error: The type or namespace name does not exist in the namespace "Microsoft" in GitHub Actions
I'm tasked to automate a dotnet build and deployment process on GitHub. Earlier the engineers were manually building the solution on VScode and didn't face this issue.

Here's the Error screenshot: Build Error Screenshot

Here's my workflow file:

```<code>name: Build_Artifacts_Pipeline
on:
  push:
    branches:
      - 'cs1_pipeline_test'
jobs:
  build_artifacts:
    runs-on: [windows-2019]
    steps:
    - name: pre-checkout
      run:
         git config --system core.longpaths true
    - name: checkout repo
      uses: actions/checkout@v3
    - name: Setup MSBuild
      uses: microsoft/setup-msbuild@v1.1
      with:
        vs-version: '15.0'
    - name: Create a deploy folder
      run: |
        cd
        mkdir D:\a\CS\Deploy_Reports
    - name: Setup dotnet
      uses: actions/setup-dotnet@v2
      with:
       dotnet-version: '5.0'
       DOTNET_NOLOGO: 'true'
       DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
    - name: Setup NuGet
      uses: Nuget/setup-nuget@v1
      with:
        nuget-version: '6.0.2'
    - name: Cache NuGet Packages
      uses: actions/cache@v1
      id: cache
      with:
        path: ~/.nuget/packages
        key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
#     - name: NuGet Restore
#       if: steps.cache.outputs.cache-hit != 'true'
#       run: nuget restore ./WBC.sln
    - name: Build Dotnet Framework Project
      run: |
        nuget install ./WBC.UI.Reporting.Web/packages.config -Source http://nuget.org/api/v2
        msbuild ./WBC.UI.Reporting.Web/WBC.UI.Reporting.Web.csproj /p:GenerateSerializationAssemblies=Off /t:Build /p:DeployOnBuild=true /p:Configuration=Release /p:PublishProfile=NewProfile.pubxml /p:OutDir=D:\a\CS\Deploy_Reports\
</code>```

Here's my csproj: .csproj

Body:
I'm tasked to automate a dotnet build and deployment process on GitHub. Earlier the engineers were manually building the solution on VScode and didn't face this issue.

Here's the Error screenshot: Build Error Screenshot

Here's my workflow file:

name: Build_Artifacts_Pipeline
on:
  push:
    branches:
      - 'cs1_pipeline_test'
jobs:
  build_artifacts:
    runs-on: [windows-2019]
    steps:
    - name: pre-checkout
      run:
         git config --system core.longpaths true
    - name: checkout repo
      uses: actions/checkout@v3
    - name: Setup MSBuild
      uses: microsoft/setup-msbuild@v1.1
      with:
        vs-version: '15.0'
    - name: Create a deploy folder
      run: |
        cd
        mkdir D:\a\CS\Deploy_Reports
    - name: Setup dotnet
      uses: actions/setup-dotnet@v2
      with:
       dotnet-version: '5.0'
       DOTNET_NOLOGO: 'true'
       DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
    - name: Setup NuGet
      uses: Nuget/setup-nuget@v1
      with:
        nuget-version: '6.0.2'
    - name: Cache NuGet Packages
      uses: actions/cache@v1
      id: cache
      with:
        path: ~/.nuget/packages
        key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
#     - name: NuGet Restore
#       if: steps.cache.outputs.cache-hit != 'true'
#       run: nuget restore ./WBC.sln
    - name: Build Dotnet Framework Project
      run: |
        nuget install ./WBC.UI.Reporting.Web/packages.config -Source http://nuget.org/api/v2
        msbuild ./WBC.UI.Reporting.Web/WBC.UI.Reporting.Web.csproj /p:GenerateSerializationAssemblies=Off /t:Build /p:DeployOnBuild=true /p:Configuration=Release /p:PublishProfile=NewProfile.pubxml /p:OutDir=D:\a\CS\Deploy_Reports\

Here's my csproj: .csproj


问:
Firebase Remote Config throws fetch status 0 exception when user offline on Unity Editor
In my gaming Unity ( 2021.3.2f1 version) project, I'm using remote config SDK ( 9.5.0)  for finetuning the game data. Players can play on offline mode, in order to do that I'm setting default values of each config key from json local path. Below code shows the implementation of config method. SetupRemoteConfig() is called when the firebase app is initiliazed.

```<code>public void SetupRemoteConfig()
{
    var remoteConfig = FirebaseRemoteConfig.DefaultInstance;

    Dictionary<string, object> configDefaults = new Dictionary<string, object>();
    configDefaults.Add(ConfigKeys.adjust_testMode.ToString(), true);
    configDefaults.Add(ConfigKeys.ShopPageCoinPackConfigs.ToString(), GetDefaultJsonString(ConfigKeys.ShopPageCoinPackConfigs));

    var configSettings = new ConfigSettings();

    if (Debug.isDebugBuild)
    {
        configSettings.MinimumFetchInternalInMilliseconds = 0;
        configSettings.FetchTimeoutInMilliseconds = 0;
    }
    else
    {
        configSettings.MinimumFetchInternalInMilliseconds = 900000;
        configSettings.FetchTimeoutInMilliseconds = 12000;
    }

    remoteConfig.SetConfigSettingsAsync(configSettings).ContinueWithOnMainThread(task =>
    {
        //Set Default Config Values
        remoteConfig.SetDefaultsAsync(configDefaults).ContinueWithOnMainThread(task =>
        {
            remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task =>
            {
                var info = remoteConfig.Info;
                if (task.IsCanceled)
                {
                    Debug.Log("Fetch canceled.");

                }
                else if (task.IsFaulted)
                {
                    Debug.Log("Fetch encountered an error.");

                }
                else if (task.IsCompletedSuccessfully)
                {
                    Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).", info.FetchTime));
                }

                switch (info.LastFetchStatus)
                {
                    case LastFetchStatus.Failure:
                        switch (info.LastFetchFailureReason)
                        {
                            case FetchFailureReason.Error:
                                Debug.Log("Fetch failed for unknown reason");
                                break;
                            case FetchFailureReason.Throttled:
                                Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
                                break;
                        }
                        break;
                    case LastFetchStatus.Pending:
                        Debug.Log("Latest Fetch call still pending.");
                        break;
                }

                IDictionary<string, ConfigValue> values = remoteConfig.AllValues;
                Debug.Log("Fetching firebase remote config data successful.");
                OnDataFetched?.Invoke(values);

            });

        });
    });

    }
</code>```

It works perfectly when Unity editor connects to Internet. However, when I test the offline mode of my game on the Unity Editor, all the default config values are loaded perfectly but remote config SDK throws an exception like this:

fetching failure: http code 0
UnityEngine.Debug:LogError (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string)
Firebase.AppUtil:PollCallbacks ()
Firebase.Platform.FirebaseAppUtils:PollCallbacks ()
Firebase.Platform.FirebaseHandler:Update ()
Firebase.Platform.FirebaseMonoBehaviour:Update ()

I try to catch this exception and continue loading the game, because default config values are loaded perfectly. However I couldn't catch the exception, it throws anyway. And Editor only logged "task.IsFaulted" condition. How can I catch this exception or how should I handle this error when firebase offline?

Body:
In my gaming Unity ( 2021.3.2f1 version) project, I'm using remote config SDK ( 9.5.0)  for finetuning the game data. Players can play on offline mode, in order to do that I'm setting default values of each config key from json local path. Below code shows the implementation of config method. SetupRemoteConfig() is called when the firebase app is initiliazed.

public void SetupRemoteConfig()
{
    var remoteConfig = FirebaseRemoteConfig.DefaultInstance;

    Dictionary<string, object> configDefaults = new Dictionary<string, object>();
    configDefaults.Add(ConfigKeys.adjust_testMode.ToString(), true);
    configDefaults.Add(ConfigKeys.ShopPageCoinPackConfigs.ToString(), GetDefaultJsonString(ConfigKeys.ShopPageCoinPackConfigs));

    var configSettings = new ConfigSettings();

    if (Debug.isDebugBuild)
    {
        configSettings.MinimumFetchInternalInMilliseconds = 0;
        configSettings.FetchTimeoutInMilliseconds = 0;
    }
    else
    {
        configSettings.MinimumFetchInternalInMilliseconds = 900000;
        configSettings.FetchTimeoutInMilliseconds = 12000;
    }

    remoteConfig.SetConfigSettingsAsync(configSettings).ContinueWithOnMainThread(task =>
    {
        //Set Default Config Values
        remoteConfig.SetDefaultsAsync(configDefaults).ContinueWithOnMainThread(task =>
        {
            remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task =>
            {
                var info = remoteConfig.Info;
                if (task.IsCanceled)
                {
                    Debug.Log("Fetch canceled.");

                }
                else if (task.IsFaulted)
                {
                    Debug.Log("Fetch encountered an error.");

                }
                else if (task.IsCompletedSuccessfully)
                {
                    Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).", info.FetchTime));
                }

                switch (info.LastFetchStatus)
                {
                    case LastFetchStatus.Failure:
                        switch (info.LastFetchFailureReason)
                        {
                            case FetchFailureReason.Error:
                                Debug.Log("Fetch failed for unknown reason");
                                break;
                            case FetchFailureReason.Throttled:
                                Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
                                break;
                        }
                        break;
                    case LastFetchStatus.Pending:
                        Debug.Log("Latest Fetch call still pending.");
                        break;
                }

                IDictionary<string, ConfigValue> values = remoteConfig.AllValues;
                Debug.Log("Fetching firebase remote config data successful.");
                OnDataFetched?.Invoke(values);

            });

        });
    });

    }

It works perfectly when Unity editor connects to Internet. However, when I test the offline mode of my game on the Unity Editor, all the default config values are loaded perfectly but remote config SDK throws an exception like this:

fetching failure: http code 0
UnityEngine.Debug:LogError (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string)
Firebase.AppUtil:PollCallbacks ()
Firebase.Platform.FirebaseAppUtils:PollCallbacks ()
Firebase.Platform.FirebaseHandler:Update ()
Firebase.Platform.FirebaseMonoBehaviour:Update ()

I try to catch this exception and continue loading the game, because default config values are loaded perfectly. However I couldn't catch the exception, it throws anyway. And Editor only logged "task.IsFaulted" condition. How can I catch this exception or how should I handle this error when firebase offline?


问:
Interaction between CGI-Webserver and C++ code
I have a c++ code on a robot infrastructure. I would like to make a web-UI that is accessible via the robots WiFi shield. I have never done this before so i have some questions.

Is there a way to have my c++ code directly interact with the cgi of the
website or do i need to use intermediary files?

Would i have to start both the cgi and the c++ code or can i start the cgi code from my c++ program?

Is there an alternative to compiling as cgi? Like maybe having the interface open directly in the c++ code?

I am sure this is a duplicate, but i didnt find anything, so any hint is appreciated!

Currently i have the c++ code send out html commands as string to the localhost,which works and i can see them in my browser. But it does not render as website, and just displays as html, probably because it is not compiled as cgi.

```<code>            pushCommand("HTTP / 1.1 200 OK\r\n");
            pushCommand("Content-Type: text/html\r\n");
            pushCommand("Connection: close\r\n");
            // the connection will be closed after completion of the response
            pushCommand("Refresh: 5\r\n"); // refresh the page automatically every 5 sec
            pushCommand("\r\n");
            pushCommand("<!DOCTYPE HTML>\r\n");
            pushCommand("<html lang=\"en\">\r\n");
            pushCommand("\r\n");
            pushCommand("<html><head><title>CGI demo stage one</title></head>\r\n");
            pushCommand("<body><h1>CGI demo stage one</h1>\r\n");
            pushCommand("This program will calculate the average of some numbers<br>\r\n");
            pushCommand("<form action=cgidemo.cgi?step2 method=post>\r\n");
            pushCommand("  How many numbers would you like to enter? <input type=text name=number size=10><br>\r\n");
            pushCommand("  What is your favourite colour? <input type=text name=favcol size=20><br>\r\n");
            pushCommand("  <input type=submit value=\" DO IT \">\r\n");
            pushCommand("</form>\r\n");
            pushCommand("</body></html>\r\n");
</code>```

where pushCommand(cmd) is basically a fifo implementation doing the following for every entry:

```<code>//doing this only once when the client is accepted
cout << "WEBUI Accepting client...\n" << endl;
int fd = accept(m_sockfd, (struct sockaddr*)&clientaddr, &len);

//doing this for every entry of the fifo cue
cmd.copy(sendBuff, cmd.length());
sendBuff[cmd.length()] = 10;
n = send(fd, sendBuff, cmd.length() + 1, 0);

</code>```

Body:
I have a c++ code on a robot infrastructure. I would like to make a web-UI that is accessible via the robots WiFi shield. I have never done this before so i have some questions.

Is there a way to have my c++ code directly interact with the cgi of the
website or do i need to use intermediary files?

Would i have to start both the cgi and the c++ code or can i start the cgi code from my c++ program?

Is there an alternative to compiling as cgi? Like maybe having the interface open directly in the c++ code?

I am sure this is a duplicate, but i didnt find anything, so any hint is appreciated!

Currently i have the c++ code send out html commands as string to the localhost,which works and i can see them in my browser. But it does not render as website, and just displays as html, probably because it is not compiled as cgi.

            pushCommand("HTTP / 1.1 200 OK\r\n");
            pushCommand("Content-Type: text/html\r\n");
            pushCommand("Connection: close\r\n");
            // the connection will be closed after completion of the response
            pushCommand("Refresh: 5\r\n"); // refresh the page automatically every 5 sec
            pushCommand("\r\n");
            pushCommand("<!DOCTYPE HTML>\r\n");
            pushCommand("\r\n");
            pushCommand("\r\n");
            pushCommand("<title>CGI demo stage one</title>\r\n");
            pushCommand("
CGI demo stage one
\r\n");
            pushCommand("This program will calculate the average of some numbers
\r\n");
            pushCommand("<form action=cgidemo.cgi?step2 method=post>\r\n");
            pushCommand("  How many numbers would you like to enter? <input type=text name=number size=10>
\r\n");
            pushCommand("  What is your favourite colour? <input type=text name=favcol size=20>
\r\n");
            pushCommand("  <input type=submit value=\" DO IT \">\r\n");
            pushCommand("</form>\r\n");
            pushCommand("\r\n");

where pushCommand(cmd) is basically a fifo implementation doing the following for every entry:

//doing this only once when the client is accepted
cout << "WEBUI Accepting client...\n" << endl;
int fd = accept(m_sockfd, (struct sockaddr*)&clientaddr, &len);

//doing this for every entry of the fifo cue
cmd.copy(sendBuff, cmd.length());
sendBuff[cmd.length()] = 10;
n = send(fd, sendBuff, cmd.length() + 1, 0);


问:
How to get SIM card info and bind the data
How to get the mobile number, sim serial number for dual sim in android 11?
SubscriptionManager#getNumber() & SubscriptionManager#getNumber() & & TelephonyManager#getLine1Number() returns null value and I added required permisions.

If any one worked with SIM binding please help me


问:
How to get model instances instead of associative arrays from custom repository's select query
I have this repository, which works per se:

<?php

namespace Homeinfo\SysMon2\Domain\Repository;

use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;

final class CheckResultsRepository
{
    public function __construct(
        private readonly ConnectionPool $connectionPool
    ) {
    }

    public function findBySystem(int $system) {
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('checkresults');
        $result = $queryBuilder
            ->select('*')
            ->from('checkresults')
            ->where(
                $queryBuilder->expr()->eq(
                    'system',
                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            )
            ->executeQuery();
        return $result->fetchAll();
    }
}
```
<p>However, the data returned by <code>fetchAll()</code> is an array of associative arrays representing the table columns.
I have this model:</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace Homeinfo\SysMon2\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class CheckResults extends AbstractEntity
{
    /**
     * @var int $id
     */
    public $id;

    /**
     * @var DateTime $timestamp
     */
    public $timestamp;

    /**
     * @var int $system
     */
    public $system;

    /**
     * @var bool $icmp_request
     */
    public $icmp_request;

    /**
     * @var string $ssh_login
     */
    public $ssh_login ;

    /**
     * @var string $http_request
     */
    public $http_request;

    /**
     * @var string $application_state
     */
    public $application_state;

    /**
     * @var string $smart_check
     */
    public $smart_check;

    /**
     * @var string $baytrail_freeze
     */
    public $baytrail_freeze;

    /**
     * @var string $fsck_repair
     */
    public $fsck_repair;

    /**
     * @var bool $application_version
     */
    public $application_version;

    /**
     * @var int $ram_total
     */
    public $ram_total;

    /**
     * @var int $ram_free
     */
    public $ram_free;

    /**
     * @var int $ram_available
     */
    public $ram_available;

    /**
     * @var string $efi_mount_ok
     */
    public $efi_mount_ok;

    /**
     * @var int $download
     */
    public $download;

    /**
     * @var int $upload
     */
    public $upload;

    /**
     * @var string $root_not_ro
     */
    public $root_not_ro;

    /**
     * @var string $sensors
     */
    public $sensors;

    /**
     * @var bool $in_sync
     */
    public $in_sync;

    /**
     * @var int $recent_touch_events
     */
    public $recent_touch_events;

    /**
     * @var DateTime $offline_since
     */
    public $offline_since;

    /**
     * @var DateTime $blackscreen_since
     */
    public $blackscreen_since;
}
</code>```

What is the correct way to make the above function yield instances of that model instead of associative arrays?

Body:
I have this repository, which works per se:

<?php

namespace Homeinfo\SysMon2\Domain\Repository;

use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;

final class CheckResultsRepository
{
    public function __construct(
        private readonly ConnectionPool $connectionPool
    ) {
    }

    public function findBySystem(int $system) {
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('checkresults');
        $result = $queryBuilder
            ->select('*')
            ->from('checkresults')
            ->where(
                $queryBuilder->expr()->eq(
                    'system',
                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            )
            ->executeQuery();
        return $result->fetchAll();
    }
}

However, the data returned by fetchAll() is an array of associative arrays representing the table columns.
I have this model:

<?php

namespace Homeinfo\SysMon2\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class CheckResults extends AbstractEntity
{
    /**
     * @var int $id
     */
    public $id;

    /**
     * @var DateTime $timestamp
     */
    public $timestamp;

    /**
     * @var int $system
     */
    public $system;

    /**
     * @var bool $icmp_request
     */
    public $icmp_request;

    /**
     * @var string $ssh_login
     */
    public $ssh_login ;

    /**
     * @var string $http_request
     */
    public $http_request;

    /**
     * @var string $application_state
     */
    public $application_state;

    /**
     * @var string $smart_check
     */
    public $smart_check;

    /**
     * @var string $baytrail_freeze
     */
    public $baytrail_freeze;

    /**
     * @var string $fsck_repair
     */
    public $fsck_repair;

    /**
     * @var bool $application_version
     */
    public $application_version;

    /**
     * @var int $ram_total
     */
    public $ram_total;

    /**
     * @var int $ram_free
     */
    public $ram_free;

    /**
     * @var int $ram_available
     */
    public $ram_available;

    /**
     * @var string $efi_mount_ok
     */
    public $efi_mount_ok;

    /**
     * @var int $download
     */
    public $download;

    /**
     * @var int $upload
     */
    public $upload;

    /**
     * @var string $root_not_ro
     */
    public $root_not_ro;

    /**
     * @var string $sensors
     */
    public $sensors;

    /**
     * @var bool $in_sync
     */
    public $in_sync;

    /**
     * @var int $recent_touch_events
     */
    public $recent_touch_events;

    /**
     * @var DateTime $offline_since
     */
    public $offline_since;

    /**
     * @var DateTime $blackscreen_since
     */
    public $blackscreen_since;
}

What is the correct way to make the above function yield instances of that model instead of associative arrays?


问:
How to save large image in live time
Im generating large histological image using paste and adding patch after patch of smaller tiles in loop, at the end I save it with

```<code> skimage.io.imsave(OutPath +'/'+ "NewPhoto-skimage.tiff", image)
</code>```

My problem is that when I save image at the end it can be very big so it use a lot of memory, .

Thats why I want to save it while generating, adding patch after patch in live time while program is running. Sort of updating image after every iteration to minimalise useage of memory at once so I can save large images.

Title: How to save large image in live time

Body:
Im generating large histological image using paste and adding patch after patch of smaller tiles in loop, at the end I save it with

 skimage.io.imsave(OutPath +'/'+ "NewPhoto-skimage.tiff", image)

My problem is that when I save image at the end it can be very big so it use a lot of memory, .

Thats why I want to save it while generating, adding patch after patch in live time while program is running. Sort of updating image after every iteration to minimalise useage of memory at once so I can save large images.


问:
how to check each array element and display length of different role in same array
I have data in API and I can retrieve but on the home page, it shows the length of the different roles. I have two roles engineer and customer in one DB so I can separate that so the length of both roles.

```<code>import React, { useEffect, useState } from "react";
import { Container } from "reactstrap";
import classes from "../pages/Login.module.css";
import Building from "../../assets/building.svg";
import Engineer from "../../assets/engineer.svg";
import Customer from "../../assets/user.svg";
import axios from "axios";
import { AdminMainURL } from "../../variables/constants";

function HomeView() {
  const [isProjectsLength, setIsProjectsLength] = useState(0);
  const [isEngineersLength, setIsEngineersLength] = useState(0);
  const [isCustomersLength, setIsCustomersLength] = useState(0);
  let n = 8000000000;
  let i = 0;
  let dat = "";

  const access_token = localStorage.getItem("access-token");

  useEffect(() => {
    //project length
    axios({
      url: `${AdminMainURL}/list_project`,
      method: "get",
      headers: {
        autherization: access_token,
      },
    }).then((json) => {
      setIsProjectsLength(json.data.responseData.length);
    });

    //engineers length
    axios({
      url: `${AdminMainURL}/list_user?limit=${n}`,
      method: "get",
      headers: {
        autherization: access_token,
      },
    }).then((json) => {
      // console.log(json);
      // for (i = 0; i < json.data.responseData.length; i++) {
      //   if (json.data.responseData[i].role === "Engineer" ) {
      //     console.log("engineer");
          setIsEngineersLength(json.data.responseData.length);
        // }
        //   if (json.data.responseData[i].role === "Customer") {
        //     console.log(i);
        //     setIsCustomersLength(json.data.responseData[i].role.length);
        //   }
        //   dat += `<li>${json.data.responseData[i].role.length}</li>`
      // }
      // console.log(dat);
      // console.log(i);
      // console.log(json.data.responseData[2].role === "Customer");
    });
  }, []);

  return (
    <Container>
      <h2 className={`px-10 md:px-20 pt-16 pb-8 ${classes.overview}`}>
        Overview
      </h2>
      <Container
        className={`px-4 sm:px-8 md:px-14 lg:px-20 xl:px-24 ${classes.overview_cards}`}
      >
        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#735F87" }}
        >
          <Container className={`${classes.image}`}>
            <img src={Building} alt="Building" />
          </Container>
          <Container className={classes.text}>
            <h2>{isProjectsLength}</h2>
            <p>Projects</p>
          </Container>
        </Container>

        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#F35958" }}
        >
          <Container className={`${classes.image}`}>
            <img src={Engineer} alt="Engineer" />
          </Container>
          <Container className={classes.text}>
            <h2>{isEngineersLength}</h2>
            <p>Engineers</p>
          </Container>
        </Container>

        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#0090D9" }}
        >
          <Container className={`${classes.image}`}>
            <img src={Customer} alt="Customer" />
          </Container>
          <Container className={classes.text}>
            {/* <h2>{isCustomersLength}</h2> */}
            <h2>{isEngineersLength}</h2>
            <p>Customers</p>
          </Container>
        </Container>
      </Container>
    </Container>
  );
}

export default HomeView;
</code>```

I want a different role length in a card view. so please any solution is there tell me.

Body:
I have data in API and I can retrieve but on the home page, it shows the length of the different roles. I have two roles engineer and customer in one DB so I can separate that so the length of both roles.

import React, { useEffect, useState } from "react";
import { Container } from "reactstrap";
import classes from "../pages/Login.module.css";
import Building from "../../assets/building.svg";
import Engineer from "../../assets/engineer.svg";
import Customer from "../../assets/user.svg";
import axios from "axios";
import { AdminMainURL } from "../../variables/constants";

function HomeView() {
  const [isProjectsLength, setIsProjectsLength] = useState(0);
  const [isEngineersLength, setIsEngineersLength] = useState(0);
  const [isCustomersLength, setIsCustomersLength] = useState(0);
  let n = 8000000000;
  let i = 0;
  let dat = "";

  const access_token = localStorage.getItem("access-token");

  useEffect(() => {
    //project length
    axios({
      url: `${AdminMainURL}/list_project`,
      method: "get",
      headers: {
        autherization: access_token,
      },
    }).then((json) => {
      setIsProjectsLength(json.data.responseData.length);
    });

    //engineers length
    axios({
      url: `${AdminMainURL}/list_user?limit=${n}`,
      method: "get",
      headers: {
        autherization: access_token,
      },
    }).then((json) => {
      // console.log(json);
      // for (i = 0; i < json.data.responseData.length; i++) {
      //   if (json.data.responseData[i].role === "Engineer" ) {
      //     console.log("engineer");
          setIsEngineersLength(json.data.responseData.length);
        // }
        //   if (json.data.responseData[i].role === "Customer") {
        //     console.log(i);
        //     setIsCustomersLength(json.data.responseData[i].role.length);
        //   }
        //   dat += `<li>${json.data.responseData[i].role.length}</li>`
      // }
      // console.log(dat);
      // console.log(i);
      // console.log(json.data.responseData[2].role === "Customer");
    });
  }, []);

  return (
    <Container>
      <h2 className={`px-10 md:px-20 pt-16 pb-8 ${classes.overview}`}>
        Overview

      <Container
        className={`px-4 sm:px-8 md:px-14 lg:px-20 xl:px-24 ${classes.overview_cards}`}
      >
        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#735F87" }}
        >
          <Container className={`${classes.image}`}>

          </Container>
          <Container className={classes.text}>

{isProjectsLength}

Projects

          </Container>
        </Container>

        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#F35958" }}
        >
          <Container className={`${classes.image}`}>

          </Container>
          <Container className={classes.text}>

{isEngineersLength}

Engineers

          </Container>
        </Container>

        <Container
          className={classes.overview_card}
          style={{ backgroundColor: "#0090D9" }}
        >
          <Container className={`${classes.image}`}>

          </Container>
          <Container className={classes.text}>
            {/*
{isCustomersLength}
 */}

{isEngineersLength}

Customers

          </Container>
        </Container>
      </Container>
    </Container>
  );
}

export default HomeView;

I want a different role length in a card view. so please any solution is there tell me.