问:
AWS Cognito User Pool AdminCreateUser in lambda returns no error nor data
I created an AWS Lambda function to test new Cognito User Pool account creation but no account was created in user pool and no error shown in console log.  I checked AWS Cloud Watch but no error was reported in cloud watch also.

```<code>START RequestId: ..... Version: $LATEST
END RequestId: .....
REPORT RequestId: .....  Duration: 80.12 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 84 MB
</code>```

I changed my Lambda function to something simpler; describeUserPool.  Still no error was thrown and no user pool info was printed in console.  I added a console.log print within the describeUserPool callback function but that did not print.

The lambda function was created using AWS Console Lambda inline editor.  Lambda function has AmazonESCognitoAccess policy attached (this policy has List/Read/Write access level to Cognito User Pools).

Can anyone shed some lights on what I've gotten wrong?
Thank you very much in advance.

```<code>var aws = require('aws-sdk');
aws.config.update({
    accessKeyId: 'access_key_id',
    secretAccessKey: 'secret_access_key',
    region: 'us-east-1',
    apiVersion: '2016-04-18'
});
var cognito = new aws.CognitoIdentityServiceProvider();
var params = {
    UserPoolId: 'us-region-user-pool-id'
};

exports.handler = async (event) => {
    cognito.describeUserPool(params, function(err, data) {
        console.log('hello from inside function');
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
     });
};
</code>```

If I included an incorrect params in AdminCreateUser it reported error

```<code>var aws = require('aws-sdk');
    aws.config.update({
        accessKeyId: 'access_key_id',
        secretAccessKey: 'secret_access_key',
        region: 'us-east-1',
        apiVersion: '2016-04-18'
    });

var cognito = new aws.CognitoIdentityServiceProvider();
var params = {
    UserPoolId: 'us-region-user-pool-id'
    Username: 'someone',
    TemporaryPassword: '11223344',
    DesiredDeliveryMediums: 'EMAIL',
    MessageAction: 'SUPPRESS',
    UserAttributes: [
    {
      Name: 'Email',
      Value: 'someone@example.com'
    },
    {
        Name: 'Family_Name',
        Value: 'One'
    },
    {
        Name: 'Given_Name',
        Value: 'Some'
    },
    {
        Name: 'Phone_Number_verified',
        Value: 'True'
    },
        {
        Name: 'Email_verified',
        Value: 'True'
    }

  ],
};

exports.handler = async (event) => {

    cognito.adminCreateUser(params, function(err, data) {
        console.log('hello from inside function');
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
     });
};
</code>```

I received the following error message in Lambda inline editor console:

```<code>Response:
null

Request ID:
"6e50fdb4-e437-4b84-be7b-3caaeb5b0a98"

Function Logs:
    ncCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:391:24)
        at Config.getCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:411:9) {
      code: 'MultipleValidationErrors',
      errors: [
        InvalidParameterType: Expected params.DesiredDeliveryMediums to be an Array
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:99:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validate (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:34:10)
            at Request.VALIDATE_PARAMETERS (/var/runtime/node_modules/aws-sdk/lib/event_listeners.js:126:42)
            at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
            at callNextListener (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:96:12) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        },
        InvalidParameterType: Expected params.UserAttributes[3].Value to be a string
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateString (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:154:32)
            at ParamValidator.validateScalar (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:130:21)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:94:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:103:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        },
        InvalidParameterType: Expected params.UserAttributes[4].Value to be a string
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateString (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:154:32)
            at ParamValidator.validateScalar (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:130:21)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:94:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:103:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        }
      ],
      time: 2020-05-31T21:59:35.173Z
    }
    END RequestId: 6e50fdb4-e437-4b84-be7b-3caaeb5b0a98
    REPORT RequestId: 6e50fdb4-e437-4b84-be7b-3caaeb5b0a98  Duration: 122.82 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 80 MB  Init Duration: 356.12 ms
</code>```

答:
Found this post cognito admin not giving error.  Suggestion by @thopaw solved the issue that I was having.

By changing it to promise() base it works as expected.
Thank you guys for your time.

In case anyone came across this, below is the updated code.

```<code>exports.handler = async (event, context) => {
    console.log('starts');
    var data;
    try {
        const data = await cognito.adminCreateUser(params).promise();
    } catch (error) {
        console.log(error);
    }
};
</code>```

Body:
I created an AWS Lambda function to test new Cognito User Pool account creation but no account was created in user pool and no error shown in console log.  I checked AWS Cloud Watch but no error was reported in cloud watch also.

START RequestId: ..... Version: $LATEST
END RequestId: .....
REPORT RequestId: .....  Duration: 80.12 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 84 MB

I changed my Lambda function to something simpler; describeUserPool.  Still no error was thrown and no user pool info was printed in console.  I added a console.log print within the describeUserPool callback function but that did not print.

The lambda function was created using AWS Console Lambda inline editor.  Lambda function has AmazonESCognitoAccess policy attached (this policy has List/Read/Write access level to Cognito User Pools).

Can anyone shed some lights on what I've gotten wrong?
Thank you very much in advance.

var aws = require('aws-sdk');
aws.config.update({
    accessKeyId: 'access_key_id',
    secretAccessKey: 'secret_access_key',
    region: 'us-east-1',
    apiVersion: '2016-04-18'
});
var cognito = new aws.CognitoIdentityServiceProvider();
var params = {
    UserPoolId: 'us-region-user-pool-id'
};

exports.handler = async (event) => {
    cognito.describeUserPool(params, function(err, data) {
        console.log('hello from inside function');
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
     });
};

If I included an incorrect params in AdminCreateUser it reported error

var aws = require('aws-sdk');
    aws.config.update({
        accessKeyId: 'access_key_id',
        secretAccessKey: 'secret_access_key',
        region: 'us-east-1',
        apiVersion: '2016-04-18'
    });

var cognito = new aws.CognitoIdentityServiceProvider();
var params = {
    UserPoolId: 'us-region-user-pool-id'
    Username: 'someone',
    TemporaryPassword: '11223344',
    DesiredDeliveryMediums: 'EMAIL',
    MessageAction: 'SUPPRESS',
    UserAttributes: [
    {
      Name: 'Email',
      Value: 'someone@example.com'
    },
    {
        Name: 'Family_Name',
        Value: 'One'
    },
    {
        Name: 'Given_Name',
        Value: 'Some'
    },
    {
        Name: 'Phone_Number_verified',
        Value: 'True'
    },
        {
        Name: 'Email_verified',
        Value: 'True'
    }

  ],
};

exports.handler = async (event) => {

    cognito.adminCreateUser(params, function(err, data) {
        console.log('hello from inside function');
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
     });
};

I received the following error message in Lambda inline editor console:

Response:
null

Request ID:
"6e50fdb4-e437-4b84-be7b-3caaeb5b0a98"

Function Logs:
    ncCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:391:24)
        at Config.getCredentials (/var/runtime/node_modules/aws-sdk/lib/config.js:411:9) {
      code: 'MultipleValidationErrors',
      errors: [
        InvalidParameterType: Expected params.DesiredDeliveryMediums to be an Array
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:99:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validate (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:34:10)
            at Request.VALIDATE_PARAMETERS (/var/runtime/node_modules/aws-sdk/lib/event_listeners.js:126:42)
            at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
            at callNextListener (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:96:12) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        },
        InvalidParameterType: Expected params.UserAttributes[3].Value to be a string
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateString (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:154:32)
            at ParamValidator.validateScalar (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:130:21)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:94:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:103:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        },
        InvalidParameterType: Expected params.UserAttributes[4].Value to be a string
            at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
            at ParamValidator.validateType (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:232:10)
            at ParamValidator.validateString (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:154:32)
            at ParamValidator.validateScalar (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:130:21)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:94:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
            at ParamValidator.validateList (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:103:14)
            at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:90:21)
            at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:75:14) {
          code: 'InvalidParameterType',
          time: 2020-05-31T21:59:35.116Z
        }
      ],
      time: 2020-05-31T21:59:35.173Z
    }
    END RequestId: 6e50fdb4-e437-4b84-be7b-3caaeb5b0a98
    REPORT RequestId: 6e50fdb4-e437-4b84-be7b-3caaeb5b0a98  Duration: 122.82 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 80 MB  Init Duration: 356.12 ms

Body:
Found this post cognito admin not giving error.  Suggestion by @thopaw solved the issue that I was having.

By changing it to promise() base it works as expected.
Thank you guys for your time.

In case anyone came across this, below is the updated code.

exports.handler = async (event, context) => {
    console.log('starts');
    var data;
    try {
        const data = await cognito.adminCreateUser(params).promise();
    } catch (error) {
        console.log(error);
    }
};


来源: stackexchange

问:
Error in Bazel Build Installation of Tensorflow From Source
Recently, I have attempted to install the TensorFlow module from source on a MacOS computer. I have, so far, progressed by installing Python 3.6, the TensorFlow pip package dependencies (I have already installed pip) and installing Bazel using the commands given on their website. I configured the source tree, first with Python 3.6 and later with 2.7 after learning of this error. However, soon after, when I entered the command:

```<code>bazel build -config=opt//tensorflow/tools/pip_package:build_pip_package
</code>```

I received this message:

```<code>Starting local Bazel server and connecting to it...
INFO: Invocation ID: 2028ac42-5ccd-4c28-9156-e7d547c89263
ERROR:          /private/var/tmp/_bazel_surengrigorian/c9e5c7de228d990fbf93866f2deac188/external/local_config_cc/BUILD:58:5: in apple_cc_toolchain rule
@local_config_cc//:cc-compiler-watchos_arm64_32: Xcode version must   be specified to use an Apple CROSSTOOL. If your Xcode version has    changed recently, try: "bazel clean --expunge" to re-run Xcode   configuration
ERROR: Analysis of target '//tensorflow/tools/pip_package:build_pip_package' failed; build   aborted: Analysis of target '@local_config_cc//:cc-compiler-   watchos_arm64_32' failed; build aborted
INFO: Elapsed time: 11.538s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (171 packages loaded,    3109 targets\
configured)
    currently loading: tensorflow/core/kernels
    Fetching @swig; fetching 4s
    Fetching @grpc; fetching
</code>```

Thank you for any assistance you can provide as to how to fix this error.

答: Downgrading to Bazel 0.29.1 worked for me. </p>

ContentLicense: CC BY-SA 4.0

Body:
Recently, I have attempted to install the TensorFlow module from source on a MacOS computer. I have, so far, progressed by installing Python 3.6, the TensorFlow pip package dependencies (I have already installed pip) and installing Bazel using the commands given on their website. I configured the source tree, first with Python 3.6 and later with 2.7 after learning of this error. However, soon after, when I entered the command:

bazel build -config=opt//tensorflow/tools/pip_package:build_pip_package

I received this message:

Starting local Bazel server and connecting to it...
INFO: Invocation ID: 2028ac42-5ccd-4c28-9156-e7d547c89263
ERROR:          /private/var/tmp/_bazel_surengrigorian/c9e5c7de228d990fbf93866f2deac188/external/local_config_cc/BUILD:58:5: in apple_cc_toolchain rule
@local_config_cc//:cc-compiler-watchos_arm64_32: Xcode version must   be specified to use an Apple CROSSTOOL. If your Xcode version has    changed recently, try: "bazel clean --expunge" to re-run Xcode   configuration
ERROR: Analysis of target '//tensorflow/tools/pip_package:build_pip_package' failed; build   aborted: Analysis of target '@local_config_cc//:cc-compiler-   watchos_arm64_32' failed; build aborted
INFO: Elapsed time: 11.538s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (171 packages loaded,    3109 targets\
configured)
    currently loading: tensorflow/core/kernels
    Fetching @swig; fetching 4s
    Fetching @grpc; fetching

Thank you for any assistance you can provide as to how to fix this error.


问:
Need Context in WorkManager
I'm using WorkManager 1.0.0-alpha05 to schedule some task to run in the feature that my app may or may not be running. The job I'm going to do requires context so how can I pass context to this?

```<code>class CompressWorker : Worker() {

    override fun doWork(): Result {
        //need context here
        Log.e("alz", "work manager runs")
        return Result.SUCCESS
    }
 }
</code>```

And here is how I initialized the work.

```<code>val oneTimeWork = OneTimeWorkRequestBuilder<CompressWorker>()
        .setInitialDelay(15, TimeUnit.MINUTES)
        .build()

WorkManager.getInstance().enqueue(oneTimeWork)
</code>```

答:
The documentation of the Worker class does not mention that calling getApplicationContext() should be the preferred way of getting the Context. On the other hand, it does explicitly document that the public constructor of Worker takes a Context as the first parameter.

```<code>public Worker (Context context,
            WorkerParameters workerParams)
</code>```

So if you need a context in the Worker class, use the one from its construction.

Title: Need Context in WorkManager

Body:
I'm using WorkManager 1.0.0-alpha05 to schedule some task to run in the feature that my app may or may not be running. The job I'm going to do requires context so how can I pass context to this?

class CompressWorker : Worker() {

    override fun doWork(): Result {
        //need context here
        Log.e("alz", "work manager runs")
        return Result.SUCCESS
    }
 }

And here is how I initialized the work.

val oneTimeWork = OneTimeWorkRequestBuilder<CompressWorker>()
        .setInitialDelay(15, TimeUnit.MINUTES)
        .build()

WorkManager.getInstance().enqueue(oneTimeWork)

Body:
The documentation of the Worker class does not mention that calling getApplicationContext() should be the preferred way of getting the Context. On the other hand, it does explicitly document that the public constructor of Worker takes a Context as the first parameter.

public Worker (Context context,
            WorkerParameters workerParams)

So if you need a context in the Worker class, use the one from its construction.


问:
How to get envelope link
In my application, after user register, it creates a docusign document and send in an envelope to user's email for signature.

My question is how do I also provide a link to the document from my application? I want it to be the same link that user would access in their email. I have tried to construct url from envelope_id which i get from the result of create_envelope, but that seems to be wrong. Is there actually a way to do this? Or the it has to be accessed from user's email?

An envelope uri: envelopes/ids

答:
The flow you might be looking for is called Embedded Signing. With embedded signing, you can redirect your users to sign DocuSign envelopes instead of having them sign via email.

Two steps process:

First, you will create your envelope. Be sure to include clientUserId for each recipient object. This will be used when you want to generate unique signing URLs in the next step.

```<code>POST /accounts/{accountId}/envelopes
{
    "status": "sent",
    "emailSubject": "Envelope with Embedded Signer",
    "documents": [{
        "documentId": "1",
        "name": "contract.pdf",
        "documentBase64": "base64 document bytes...",
    }],
    "recipients": {
        "signers": [{
            "email": "john@email.com",
            "name": "John Doe",
            "recipientId": "1",
            "clientUserId": "1234"
        }]
    }
}
</code>```

Second, you will generate the RecipientViewURL for a given user.

```<code>POST /accounts/{accountId}/envelopes/{envelopeId}/views/recipient
{
    "userName": "John Doe",
    "email": "johndoe@email.com",
    "recipientId": "1",
    "clientUserId": "1234",
    "authenticationMethod": "email",
    "returnUrl": "https://www.docusign.com/devcenter"
}
</code>```

Here is a guide that provides a more thorough background on the feature.

Title: How to get envelope link

Body:
The flow you might be looking for is called Embedded Signing. With embedded signing, you can redirect your users to sign DocuSign envelopes instead of having them sign via email.

Two steps process:

First, you will create your envelope. Be sure to include clientUserId for each recipient object. This will be used when you want to generate unique signing URLs in the next step.

POST /accounts/{accountId}/envelopes
{
    "status": "sent",
    "emailSubject": "Envelope with Embedded Signer",
    "documents": [{
        "documentId": "1",
        "name": "contract.pdf",
        "documentBase64": "base64 document bytes...",
    }],
    "recipients": {
        "signers": [{
            "email": "john@email.com",
            "name": "John Doe",
            "recipientId": "1",
            "clientUserId": "1234"
        }]
    }
}

Second, you will generate the RecipientViewURL for a given user.

POST /accounts/{accountId}/envelopes/{envelopeId}/views/recipient
{
    "userName": "John Doe",
    "email": "johndoe@email.com",
    "recipientId": "1",
    "clientUserId": "1234",
    "authenticationMethod": "email",
    "returnUrl": "https://www.docusign.com/devcenter"
}

Here is a guide that provides a more thorough background on the feature.


问:
Where should I set the '--insecure-registry' flag on Mac OS?
I am using OS X 10.10. When trying to communicate with our team's private docker registry, it keeps giving me errors like this:

```<code>Error: Invalid registry endpoint https://registry.xxx.xxx/v1/: Get
https://registry.af-sys.com/v1/_ping: dial tcp xx.xxx.xxx.xxx:xxx: i/o timeout.
If this private registry supports only HTTP or HTTPS with an unknown CA
certificate, please add --insecure-registry...
</code>```

On Ubuntu system this error can be resolved by adding DOCKER_OPTS into the /etc/default/docker configuration file like this:

```<code>DOCKER_OPTS="$DOCKER_OPTS --insecure-registry myregistry:5000"
</code>```

Does Mac OS have a similar configuration file where I can add the DOCKER_OPTS option?

答:
As of Docker 2.3.0.3, it must be in host:port format, i.e you have to remove http/https. Sample configuration

```<code>"insecure-registries": [
    "registry.com:443",
    "registry-2.net:80"
  ]
</code>```

Body:
I am using OS X 10.10. When trying to communicate with our team's private docker registry, it keeps giving me errors like this:

Error: Invalid registry endpoint https://registry.xxx.xxx/v1/: Get
https://registry.af-sys.com/v1/_ping: dial tcp xx.xxx.xxx.xxx:xxx: i/o timeout.
If this private registry supports only HTTP or HTTPS with an unknown CA
certificate, please add --insecure-registry...

On Ubuntu system this error can be resolved by adding DOCKER_OPTS into the /etc/default/docker configuration file like this:

DOCKER_OPTS="$DOCKER_OPTS --insecure-registry myregistry:5000"

Does Mac OS have a similar configuration file where I can add the DOCKER_OPTS option?

Body:
As of Docker 2.3.0.3, it must be in host:port format, i.e you have to remove http/https. Sample configuration

"insecure-registries": [
    "registry.com:443",
    "registry-2.net:80"
  ]


问:
I can't change xampp apache default port number
I changed the httpd.conf file lines:

Listen 80 TO Listen 8012

servername localhost  TO servername localhost:8012

And still it trys to start apache at port 80, but can't because a system process is using it.

EDIT
No my question is still different because I already followed those steps listed in the possible duplicate question: How to change the port number of Apache in Xampp

答: you need to run xampp as an Administrator. it will fix it.</p>

ContentLicense: CC BY-SA 3.0


问:
Beginner Javascript errors 'Line is longer than 80 characters', 'unexpected var' and 'use space not tabs'
Having trouble with a combined file of html, CSS and javascript  that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.</p>

```<code>"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html"
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = function cancelBooking()

}

window.onload = init;

</code>```

答:
it's common rule of eslint, if you want to ignore these error on you code, you can use eslint-disable on top of your js code

```<code>/* eslint-disable */

alert('foo');
</code>```

Body:
Having trouble with a combined file of html, CSS and javascript  that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.

"use strict";

//validate form inputs from payment.html
function validate() {

    var errMsg = "";
    var result = true;      //assumes no errors

    //assign elements to variables
    var mastercard_check = document.getElementById("mastercard").checked;
    var visa_check = document.getElementById("visa").checked;
    var express_check = document.getElementById("express").checked;
    var credit_name = document.getElementById("credit_name").value;
    var credit_number = document.getElementById("credit_number").value;
    var credit_expiry = document.getElementById("credit_expiry").value;
    var credit_vv = document.getElementById("credit_vv").value;

    //validations for form
    if (!(mastercard_check || visa_check || express_check)) {
        errMsg += "Please choose a card type\n";
        result = false;
    }

    if (credit_name.length > 40) {
        errMsg += "Please enter a name for your credit card between 1-40 characters\n";
        result = false;
    }
    else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
        errMsg += "Credit card name can only contain alpha characters\n";
        result = false;
    }

    if (isNaN(credit_number)) {
        errMsg = errMsg + "Credit card number must contain digits only\n";
        result = false;
    }
    else if (credit_number.length < 15 || credit_number.length > 16){
        errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
        result = false;
    }
    else {
        var tempMsg = checkCardNumber(credit_number);
        if (tempMsg != "") {
            errMsg += tempMsg;
            result = false;
        }
    }

    if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
        errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
        result = false;
    }

    if (!credit_vv) {
        errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
        result = false;
    }

    if (errMsg != "") {
        alert(errMsg);
    }

    return result;
}

//obtain the credit card type
function getCardType() {

    var cardType = "Unknown";
    var cardArray = document.getElementById("credit_type").getElementsByTagName("input");

    for(var i = 0; i < cardArray.length; i++) {
        if (cardArray[i].checked) {
            cardType = cardArray[i].value;
        }
    }
    return cardType

}

//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
    var errMsg = "";
    var card = getCardType();
    switch(card) {
        case "visa":
            if (!(credit_number.length == 16)) {
                errMsg = "Visa number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(4).*$/)) {
                errMsg = "Visa number must start with a 4. \n";
            }
            break;
        case "mastercard":
            if (!(credit_number.length == 16)) {
                errMsg = "Mastercard number must contian 16 digits\n";
            }
            else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
                errMsg = "Mastercard number must start with digits 51 through 55. \n";
            }
            break;
        case "express":
            if (!(credit_number.length == 15)) {
                errMsg = "American Express number must contian 15 digits\n";
            }
            else if (!credit_number.match(/^(34|37).*$/)) {
                errMsg = "American Express number must start with 34 or 37. \n";
            }
            break;
    }
    return errMsg;
}

//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
    var cost = 0;
    if (size.search("three") != -1) cost = 100;
    if (size.search("four")!= -1) cost += 150;
    if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
    var cost = 0;
    if(sessionStorage.firstname != undefined){
        document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;

    document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;

    document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;

    document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;

    document.getElementById("confirm_package").textContent = sessionStorage.package;

    document.getElementById("confirm_size").textContent = sessionStorage.size;

    document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
        cost = calcCost(sessionStorage.size, sessionStorage.quantity);

        document.getElementById("firstname").value = sessionStorage.firstname;
    document.getElementById("lastname").value = sessionStorage.lastname;
    document.getElementById("street").value = sessionStorage.street;
      document.getElementById("suburb").value = sessionStorage.suburb;
      document.getElementById("state").value = sessionStorage.state;
      document.getElementById("postcode").value = sessionStorage.postcode;
      document.getElementById("phone").value = sessionStorage.phone;
      document.getElementById("email").value = sessionStorage.email;
      document.getElementById("preferred").value = sessionStorage.preferred;
      document.getElementById("deal").value = sessionStorage.deal;
      document.getElementById("quality").value = sessionStorage.quality;
      document.getElementById("quantity").value = sessionStorage.quantity;
      document.getElementById("extrabags").value = sessionStorage.extrabags;
      document.getElementById("accomodation").value = sessionStorage.accomodation;
      document.getElementById("travel").value = sessionStorage.travel;
    document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
    document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
    }

}

function cancelBooking() {
window.location = "index.html"
}

function init() {

    getInfo();
    var payment = document.getElementById("payment");
    payment.onsubmit = function() {validate()};
    var cancel = document.getElementById("cancel");
    cancel.onclick = function cancelBooking()

}

window.onload = init;

Body:
it's common rule of eslint, if you want to ignore these error on you code, you can use eslint-disable on top of your js code

/* eslint-disable */

alert('foo');


问:
Oracle SQL Lead Lag across group for historical data
I asked a similar question here. Suppose I have below table structure. P1, P2, P3 those 3 attributes represent as a key. I want to compare each key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

```<code>P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc
</code>```

I am thinking to generate a result set which has start / end date to track history. The expected result set:

```<code>P1  P2  P3      KEY  STARTTIME  ENDTIME

a   b   c       abc     1         2
a   b   e       abe     2         5
a   b   y       aby     2         5
a   b   x       abx     5        NULL
a   b   c       abc     5        NULL
</code>```

Thanks for providing help for my previous post. I modified one of the answers as below to get add/remove result set but still not able to convert to above start/end time model.

```<code>with base as (
select
    'a' as p1,
    'b' as p2,
    'c' as p3,
    1 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'y' as p3,
    2 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'e' as p3,
    2 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'x' as p3,
    5 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'c' as p3,
    5 as day
from dual
),
calendar as (
select
    day,
    lead(day) over (order by day asc) as nextday,
    lag(day) over (order by day asc) as prevday
from
    (select distinct day from base)
),
data as (
    select
        p1,
        p2,
        p3,
        base.day,
        lead(base.day) over (partition by p1, p2, p3 order by base.day asc) as nextrow,
        lag(base.day) over (partition by p1, p2, p3 order by base.day asc) as prevrow,
        calendar.nextday,
        calendar.prevday
    from
        base
    left join
        calendar
            on calendar.day = base.day
)
select * from data
/

select
    d1.p1,
    d1.p2,
    d1.p3,
    d1.day,
    d1.nextrow,
    d1.prevrow,
    'ADD' as op,
    d1.day as d
from
    data d1
where
    prevrow is null or prevrow <> prevday
union
select
    d2.p1,
    d2.p2,
    d2.p3,
    d2.day,
    d2.nextrow,
    d2.prevrow,
    'REMOVE' as op,
    nextday
from
    data d2
where
    nextrow is null or nextrow <> nextday
order by
    d, op asc
</code>```

答:
I understand this as a gaps-and-island problem. You can use the difference between row numbers to identify groups of adjacent records. To compute the end_day, a little more logic is needed, since days are not sequential: I used a window sum() that increases when the date changes and first_value() to get the actual "next" date:

```<code>select
    p1,
    p2,
    p3,
    min(day) over(partition by p1, p2, p3, rn1 - rn2 order by day) start_day,
    case
        when min(day) over(partition by p1, p2, p3, rn1 - rn2 order by day)
            <> max(lead_day) over()
        then max(lead_day) over(partition by day_grp)
    end end_day
from (
    select
        t.*,
        sum(case when day = lead_day then 0 else 1 end) over(order by day) day_grp
    from (
    select
        t.*,
        row_number() over(order by day) rn1,
        row_number() over(partition by p1, p2, p3 order by day) rn2,
        lead(day) over(order by day) lead_day
    from mytable t
    ) t
) t
</code>```

Demo on DB Fiddlde:

```
P1 | P2 | P3 | START_DAY | END_DAY
:- | :- | :- | --------: | ------:
a  | b  | c  |         1 |       2
a  | b  | e  |         2 |       5
a  | b  | y  |         2 |       5
a  | b  | x  |         5 |    <em>null</em>
a  | b  | c  |         5 |    <em>null</em>
```

Body:
I asked a similar question here. Suppose I have below table structure. P1, P2, P3 those 3 attributes represent as a key. I want to compare each key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc

I am thinking to generate a result set which has start / end date to track history. The expected result set:

P1  P2  P3      KEY  STARTTIME  ENDTIME

a   b   c       abc     1         2
a   b   e       abe     2         5
a   b   y       aby     2         5
a   b   x       abx     5        NULL
a   b   c       abc     5        NULL

Thanks for providing help for my previous post. I modified one of the answers as below to get add/remove result set but still not able to convert to above start/end time model.

with base as (
select
    'a' as p1,
    'b' as p2,
    'c' as p3,
    1 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'y' as p3,
    2 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'e' as p3,
    2 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'x' as p3,
    5 as day
from dual
union
select
    'a' as p1,
    'b' as p2,
    'c' as p3,
    5 as day
from dual
),
calendar as (
select
    day,
    lead(day) over (order by day asc) as nextday,
    lag(day) over (order by day asc) as prevday
from
    (select distinct day from base)
),
data as (
    select
        p1,
        p2,
        p3,
        base.day,
        lead(base.day) over (partition by p1, p2, p3 order by base.day asc) as nextrow,
        lag(base.day) over (partition by p1, p2, p3 order by base.day asc) as prevrow,
        calendar.nextday,
        calendar.prevday
    from
        base
    left join
        calendar
            on calendar.day = base.day
)
select * from data
/

select
    d1.p1,
    d1.p2,
    d1.p3,
    d1.day,
    d1.nextrow,
    d1.prevrow,
    'ADD' as op,
    d1.day as d
from
    data d1
where
    prevrow is null or prevrow <> prevday
union
select
    d2.p1,
    d2.p2,
    d2.p3,
    d2.day,
    d2.nextrow,
    d2.prevrow,
    'REMOVE' as op,
    nextday
from
    data d2
where
    nextrow is null or nextrow <> nextday
order by
    d, op asc

Body:
I understand this as a gaps-and-island problem. You can use the difference between row numbers to identify groups of adjacent records. To compute the end_day, a little more logic is needed, since days are not sequential: I used a window sum() that increases when the date changes and first_value() to get the actual "next" date:

select
    p1,
    p2,
    p3,
    min(day) over(partition by p1, p2, p3, rn1 - rn2 order by day) start_day,
    case
        when min(day) over(partition by p1, p2, p3, rn1 - rn2 order by day)
            <> max(lead_day) over()
        then max(lead_day) over(partition by day_grp)
    end end_day
from (
    select
        t.*,
        sum(case when day = lead_day then 0 else 1 end) over(order by day) day_grp
    from (
    select
        t.*,
        row_number() over(order by day) rn1,
        row_number() over(partition by p1, p2, p3 order by day) rn2,
        lead(day) over(order by day) lead_day
    from mytable t
    ) t
) t

Demo on DB Fiddlde:

P1 | P2 | P3 | START_DAY | END_DAY
:- | :- | :- | --------: | ------:
a  | b  | c  |         1 |       2
a  | b  | e  |         2 |       5
a  | b  | y  |         2 |       5
a  | b  | x  |         5 |    null
a  | b  | c  |         5 |    null


问:
Problem creating compound index in Spring Data MongoDB
Creating index via MongoShell

```<code>db.car.createIndex({brand:1 , model:1 , colour:1 ,fuelTypes:1},{unique:true})
</code>```

Creating CompoundIndex via spring application

```<code>@Document
@CompoundIndex(def = "{ 'brand':1 , 'model':1 , 'colour':1 , 'fuelTypes':1 }",unique = true)
public class Car {

    private String brand;
    private String model;
    private List<FuelType> fuelTypes;
    private String colour;
}
</code>```

I was able to create via Mongo shell but not thourgh spring application.What's wrong in the above code?Are n't they equivalent?
I checked After inserting atleast one document.

Thanks in advance.

答:
Here is a working example I tried (creates a new collection, document and the compound index):

The Car POJO class:

```<code>@CompoundIndex(name = "car-cmp-idx", def = "{'brand': 1, 'model': 1}", unique = true)
@Document
public class Car {

    private String brand;
    private String model;
    private String colour;

    public Car() {

    }
    public Car(String brand, String model, String colour) {
        this.brand = brand;
        this.model = model;
        this.colour = colour;
    }

    // get/set methods. etc...
}
</code>```

The application code to create a document in the (new) car: collection:

```<code>MongoOperations ops = new MongoTemplate(MongoClients.create(), "test");
Car car = new Car("Ford", "Model T", "Black");
ops.insert(car);
</code>```

The result document verified from the mongo shell:

```<code>{
        "_id" : ObjectId("5ed46f4960c3f13e5edf43b6"),
        "brand" : "Ford",
        "model" : "Model T",
        "colour" : "Black",
        "_class" : "com.example.demo.Car"
}
</code>```

The indexes:

```<code>[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.car"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "brand" : 1,
                        "model" : 1
                },
                "name" : "car-cmp-idx",
                "ns" : "test.car"
        }
]
</code>```

Body:
Creating index via MongoShell

db.car.createIndex({brand:1 , model:1 , colour:1 ,fuelTypes:1},{unique:true})

Creating CompoundIndex via spring application

@Document
@CompoundIndex(def = "{ 'brand':1 , 'model':1 , 'colour':1 , 'fuelTypes':1 }",unique = true)
public class Car {

    private String brand;
    private String model;
    private List<FuelType> fuelTypes;
    private String colour;
}

I was able to create via Mongo shell but not thourgh spring application.What's wrong in the above code?Are n't they equivalent?
I checked After inserting atleast one document.

Thanks in advance.

Body:
Here is a working example I tried (creates a new collection, document and the compound index):

The Car POJO class:

@CompoundIndex(name = "car-cmp-idx", def = "{'brand': 1, 'model': 1}", unique = true)
@Document
public class Car {

    private String brand;
    private String model;
    private String colour;

    public Car() {

    }
    public Car(String brand, String model, String colour) {
        this.brand = brand;
        this.model = model;
        this.colour = colour;
    }

    // get/set methods. etc...
}

The application code to create a document in the (new) car: collection:

MongoOperations ops = new MongoTemplate(MongoClients.create(), "test");
Car car = new Car("Ford", "Model T", "Black");
ops.insert(car);

The result document verified from the mongo shell:

{
        "_id" : ObjectId("5ed46f4960c3f13e5edf43b6"),
        "brand" : "Ford",
        "model" : "Model T",
        "colour" : "Black",
        "_class" : "com.example.demo.Car"
}

The indexes:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.car"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "brand" : 1,
                        "model" : 1
                },
                "name" : "car-cmp-idx",
                "ns" : "test.car"
        }
]


问:
How to compile a linux kernel with SSE enabled?
I am in the following situation:

I am adding a float point based algorithm to Linux kernel. I know I shouldn't do that, but I want to give it a try and see how bad it can be.

kernel_fpu_begin/kernel_fpu_end is used at every float point calculation blocks.

When I run make to compile the kernel code I get this error: SSE register return with SSE disabled, the corresponding line is input[3] = (float)util / (float)max;

Here are my questions:

I didn't find -mno-sse -mno-sse2 in the Makefile, what can I do to enable the SSE?

When I declare some float point variables, for example, float x[10], should I use kernel_fpu_begin/kernel_fpu_end?

Thanks!

答:
You need to stop the compiler from using SSE to e.g. copy a 16 byte struct before kernel_fpu_begin or after end.  So you can't just use a block inside a function in a file compiled with -msse2.

You might be able to put your FP code in a separate function and use __attribute__((target("sse2"))) or "avx" on that function, to enable it without command-line options, for x86 specifically.

Obviously that function can't return a float by value because the standard calling convention returns in XMM0, and you need the caller compiled without.


问:
Instance variables in Java
Please explain the following behaviour.

```<code>class Base
{
    public int num = 3;

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

class child
    extends Base
{
    public int num = 4;

    public child()
    {

    }

    public child(int i)
    {
        this.num = i;
    }

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

public class Main
{

   public static void main(String[] args)
   {

        Base obj2 = new child();
        System.out.println(obj2.num);
        System.out.println(obj2.getNum());

        Base obj3 = new child(10);
        System.out.println(obj3.num);
        System.out.println(obj3.getNum());
    }
}
</code>```

Output :
3
4
3
10

Here how obj2.num and obj3.num still point to the value 3 which is assigned in the Base class instance variable. Wont it get overidded like the obj2.getNum() and obj3.getNum().

Thanks in advance.

答:
Because the objects are declared with super class type, you get the super member variable value.

If the object was declared with sub class type, the value would be overridden value.

If the  Base obj3 = new child(10); is modified to child obj3 = new child(10); the output would be 3 4 10 10

This is well explained here

Title: Instance variables in Java

Body:
Please explain the following behaviour.

class Base
{
    public int num = 3;

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

class child
    extends Base
{
    public int num = 4;

    public child()
    {

    }

    public child(int i)
    {
        this.num = i;
    }

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

public class Main
{

   public static void main(String[] args)
   {

        Base obj2 = new child();
        System.out.println(obj2.num);
        System.out.println(obj2.getNum());

        Base obj3 = new child(10);
        System.out.println(obj3.num);
        System.out.println(obj3.getNum());
    }
}

Output :
3
4
3
10

Here how obj2.num and obj3.num still point to the value 3 which is assigned in the Base class instance variable. Wont it get overidded like the obj2.getNum() and obj3.getNum().

Thanks in advance.


问:
Getting error "Insufficient privileges to complete the operation" while pulling application list using azure-python-sdk
I'm using a service principle with permissions Application.Read.All and Directory.Read.All of Application type to authenticate to Azure and using following code to pull list of Applications in the tenant.

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
from config import app

credentials = ServicePrincipalCredentials(
    client_id = app["CLIENT"],
    secret = app["KEY"],
    tenant = app["TENANT_ID"],
    resource="https://graph.windows.net"
)

graphrbac_client = GraphRbacManagementClient(credentials, app["TENANT"])

for app in graphrbac_client.applications.list():
    print("\nApp:")
    print(app)
print("******\n")
</code>```

Any help is much appreciated

答:
From your description, I suppose you added the application permission Application.Read.All and Directory.Read.All of Microsoft Graph, because what you need is Azure Active Directory Graph, which does not have the Application.Read.All permission.

In your code, it uses the resource="https://graph.windows.net", which means your code calls the Azure Active Directory Graph, not Microsoft Graph, to solve the issue, just add the application permission Directory.Read.All of Azure Active Directory Graph like below.

Note : After adding the permission, don't forget to click the Grant admin consent for xxx button, otherwise your service principal will not get the permission.

There may be some delay, after half an hour, test the code, it works fine.

Body:
I'm using a service principle with permissions Application.Read.All and Directory.Read.All of Application type to authenticate to Azure and using following code to pull list of Applications in the tenant.

from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
from config import app

credentials = ServicePrincipalCredentials(
    client_id = app["CLIENT"],
    secret = app["KEY"],
    tenant = app["TENANT_ID"],
    resource="https://graph.windows.net"
)

graphrbac_client = GraphRbacManagementClient(credentials, app["TENANT"])

for app in graphrbac_client.applications.list():
    print("\nApp:")
    print(app)
print("******\n")

Any help is much appreciated


问:
How to Make Transition Left Only with CSS
Hello I have a search arrow on my website and right it transitions on both left and right.
Because the arrow is on the right side of my website I want it to only transition left only.

In other words I want the search icon to stay in place and not move and input to transition to the left only so you can type in the input. I hope this makes sense.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search">

    <i class="fas fa-search"></i>

</div></code>```

答:
Just add some focus and valid check in your css. and if you only want the input to slide left from where it is, just let me know, I will change the code

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt , .search-txt:focus, .search-txt:valid {
  width: 240px;
  padding: 0 6px 0 50px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  position: absolute;
  color: lightblue;
  left: 10px;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search" required>

    <i class="fas fa-search"></i>

</div></code>```

Body:
Hello I have a search arrow on my website and right it transitions on both left and right.
Because the arrow is on the right side of my website I want it to only transition left only.

In other words I want the search icon to stay in place and not move and input to transition to the left only so you can type in the input. I hope this makes sense.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}

  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

  <input class="search-txt" type="text" name="" placeholder="Type to Search">

Body:
Just add some focus and valid check in your css. and if you only want the input to slide left from where it is, just let me know, I will change the code

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt , .search-txt:focus, .search-txt:valid {
  width: 240px;
  padding: 0 6px 0 50px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  position: absolute;
  color: lightblue;
  left: 10px;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 40px;
}

<head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search" required>
  <a class="search-btn" href="#">
    <i class="fas fa-search"></i>
  </a>
</div>


问:
Is there a way to print csv file data to console if the data matches another csv file?
I want to be able to check one csv file with another csv file. If the first column of data in file1 matches the first column of data in file2 only print the rows that match and not the rest of them. I know how to print a csv file to the console but was wondering if there's a way to do this.. There is code below of what i have done so far but i don't think it is the right way to go about it. Any help would be appreciated. Thanks</p>

```<code>operands = new ArrayList();

string[] file1 = file.ReadAllLines(@"..\..\data1.csv").Split(',');
string[] file2 = file.ReadAllLines(@"..\..\data2.csv").Split(',');

foreach (var line in file1)
{
 if (line.Split(',')[0].Equals(file2[0])
 {
   operands.AddRange(file1);
}
}

</code>```

答:
You need to check first column of each line of file1 with each line of file2,

you can try below

```<code>using System;
using System.Linq;
using System.Collection.Generic;
...

//ReadAllLines() returns string[], you can't split string array, you need split individual element
string[] file1 = file.ReadAllLines(@"..\..\data1.csv");
string[] file2 = file.ReadAllLines(@"..\..\data2.csv");
List<string> operands = new List<string>();
for(int i = 0; i < Math.Min(file1.Length, file2.Length); i ++)
{
    if(file1[i].Split(',').First().Equals(file2[i].Split(',').First()))
    {                                  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This was missing
        Console.WriteLine($"Line {i+1} matches first column data");
        operands.Add(file1[i]);

        //If you want to use ArrayList, then
        //operands.Add(file1[i]); //You were missing index i.e [i]
    }
}
</code>```

From your updated code, I would suggest use List<string> instead of ArrayList and store  entire row to it.

Body:
I want to be able to check one csv file with another csv file. If the first column of data in file1 matches the first column of data in file2 only print the rows that match and not the rest of them. I know how to print a csv file to the console but was wondering if there's a way to do this.. There is code below of what i have done so far but i don't think it is the right way to go about it. Any help would be appreciated. Thanks

operands = new ArrayList();

string[] file1 = file.ReadAllLines(@"..\..\data1.csv").Split(',');
string[] file2 = file.ReadAllLines(@"..\..\data2.csv").Split(',');

foreach (var line in file1)
{
 if (line.Split(',')[0].Equals(file2[0])
 {
   operands.AddRange(file1);
}
}

Body:
You need to check first column of each line of file1 with each line of file2,

you can try below

using System;
using System.Linq;
using System.Collection.Generic;
...

//ReadAllLines() returns string[], you can't split string array, you need split individual element
string[] file1 = file.ReadAllLines(@"..\..\data1.csv");
string[] file2 = file.ReadAllLines(@"..\..\data2.csv");
List<string> operands = new List<string>();
for(int i = 0; i < Math.Min(file1.Length, file2.Length); i ++)
{
    if(file1[i].Split(',').First().Equals(file2[i].Split(',').First()))
    {                                  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This was missing
        Console.WriteLine($"Line {i+1} matches first column data");
        operands.Add(file1[i]);

        //If you want to use ArrayList, then
        //operands.Add(file1[i]); //You were missing index i.e [i]
    }
}

From your updated code, I would suggest use List<string> instead of ArrayList and store  entire row to it.


问:
How do you create a button that works in javascript?
EDIT: So a few solutions work. Thing is, they work in codepen.io. But when I try to reload the actual HTML page from my computer to Chrome, the button clicks and shows nothing. Chrome is saying: 'dice.js:12 Uncaught TypeError: Cannot set property 'onclick' of null
    at dice.js:12.' How do I fix that?

I've looked at multiple similar questions that have different answers, and none of the answers I've tried has worked. I was able to make a random dice roll with the below code:

```<code>const min = 1;
const max = 7;

function diceRoll(random) {
    random = 0;
    while (random <= 0) {
        random = Math.floor(Math.random() * (max - min) + min);
        document.write('Dice # ' + random);
    }
}
</code>```

My html is:

```<code><button id="roll">Throw Dice</button>
</code>```

I haven't learned how to make buttons work, or how to start the javascript (other than writing it in the console. Can anyone help with how to create a button to make it work so I don't have to use the console? See below for what I've tried:

```<code>let button = document.getElementById('roll');

button.onclick = function() {
    let result = diceRoll();
    printNumber(result);
};
</code>```

Another try:

```<code> document.getElementById("roll").onclick = diceRoll();
</code>```

And another:

```<code>document.getElementById("roll").onclick = function() {
    diceRoll();
};
</code>```

答:
Try this

<!DOCTYPE html>

        <form onsubmit='diceRoll()'>
            <button>Throw Dice</button>
        </form>

```

Body:
EDIT: So a few solutions work. Thing is, they work in codepen.io. But when I try to reload the actual HTML page from my computer to Chrome, the button clicks and shows nothing. Chrome is saying: 'dice.js:12 Uncaught TypeError: Cannot set property 'onclick' of null
    at dice.js:12.' How do I fix that?

I've looked at multiple similar questions that have different answers, and none of the answers I've tried has worked. I was able to make a random dice roll with the below code:

const min = 1;
const max = 7;

function diceRoll(random) {
    random = 0;
    while (random <= 0) {
        random = Math.floor(Math.random() * (max - min) + min);
        document.write('Dice # ' + random);
    }
}

My html is:

<button id="roll">Throw Dice</button>

I haven't learned how to make buttons work, or how to start the javascript (other than writing it in the console. Can anyone help with how to create a button to make it work so I don't have to use the console? See below for what I've tried:

let button = document.getElementById('roll');

button.onclick = function() {
    let result = diceRoll();
    printNumber(result);
};

Another try:

 document.getElementById("roll").onclick = diceRoll();

And another:

document.getElementById("roll").onclick = function() {
    diceRoll();
};

Body:
Try this

<!DOCTYPE html>

<html lang="en">
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll(random) {
                random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }
        </script>
    </head>
    <body>
        <form onsubmit='diceRoll()'>
            <button>Throw Dice</button>
        </form>
    </body>
</html>


问:
Changing the Window size of the new Windows Terminal
As you've heard, the new Windows Terminal has been released. What I can't find is how to adjust the window size. In the old consoles, if you wanted to change the settings, it would give you a GUI, but with the new console, you need JSON commands. I've tried a couple of commands which were initialCols and initialRows but they didn't work for me, and I have tried to search for a solution for a while. Is there another way for me to adjust the window size or is it just not possible as in this point in time?

答:
Open Terminal's settings.json file in a text editor (e.g. notepad), either from the Settings menu or from disk at %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState and add the following two lines (with the numbers you want to set instead of 92x60).

```<code>    "initialCols": 92,
    "initialRows": 60,
</code>```

As noted in the Global settings in Windows Terminal documentation, those two lines should go under the root of the settings.json file, for example right above profiles.

```<code>    // A profile specifies a command to execute paired with ...
    "profiles":
    {
    ...
    }
</code>```

Body:
Open Terminal's settings.json file in a text editor (e.g. notepad), either from the Settings menu or from disk at %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState and add the following two lines (with the numbers you want to set instead of 92x60).

    "initialCols": 92,
    "initialRows": 60,

As noted in the Global settings in Windows Terminal documentation, those two lines should go under the root of the settings.json file, for example right above profiles.

    // A profile specifies a command to execute paired with ...
    "profiles":
    {
    ...
    }


问:
Understanding conditional locking
My challenge is this:

I want my cells in columns E - G and I-j to be automatically locked in the protected sheet. When I enter a figure into column B, figures in E - G and I - J should auto populate, though painfully some will not.

For those corresponding columns which do not auto populate, I want their locked status to be removed, based on the fact that they have no data, despite there being data in column B.

Here's another part to the trick. If data is not entered in column B but instead columns C & D, I want all the corresponding locked cells in those rows to be unlocked.

For me, communicating the logic is so much easier than doing the actual work. Fuelled by my desire to solve problems I've read it all and now I come to you, Stackoverflow, to advise me on how to proceed with all of this. I would really appreciate all the help I can get.

Thank you so much for reading.

答:
I'm trying to give you a generalised answer here.

To lock ranges on a sheet use the Locked property. Note that the sheet must be protected for the lock to work.

```<code>Worksheets("Sheet1").Range("E1:G1").Locked = True
Worksheets("Sheet1").Protect "password"

</code>```

To unlock ranges on a sheet

```<code>Worksheets("Sheet1").Range("E1:G1").Locked = False

</code>```

To loop over a range

```<code>Set rng = Range("A1:A3")

For Each cell In rng
  ''do something
Next cell

</code>```

To make your code run at the point when data is entered you need to use the Worksheet_Change method. It is triggered every time the sheet changes and the target is the cell value that has changed

```<code>Private Sub Worksheet_Change(ByVal Target as Range)
    ''write the logic in this method
End Sub

</code>```

Put all of these together to suit your logic.

Title: Understanding conditional locking

Body:
I'm trying to give you a generalised answer here.

To lock ranges on a sheet use the Locked property. Note that the sheet must be protected for the lock to work.

Worksheets("Sheet1").Range("E1:G1").Locked = True
Worksheets("Sheet1").Protect "password"

To unlock ranges on a sheet

Worksheets("Sheet1").Range("E1:G1").Locked = False

To loop over a range

Set rng = Range("A1:A3")

For Each cell In rng
  ''do something
Next cell

To make your code run at the point when data is entered you need to use the Worksheet_Change method. It is triggered every time the sheet changes and the target is the cell value that has changed

Private Sub Worksheet_Change(ByVal Target as Range)
    ''write the logic in this method
End Sub

Put all of these together to suit your logic.


问:
how to insert javascript variable into json object
here is the function

```<code>function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { _id:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');
</code>```

Result :

```<code>[
_id:{temp:'20C',
     battery:'60%'
    }
]
</code>```

Expected Result:

```<code>[
Thermometer1:{temp:'20C',
     battery:'60%'
    }
]
</code>```

ignore the text below :v

it looks like your post is mostly code; please add more detail,

i don't know what to write so here is a guitar tab

0 - 3 - 5

0 - 3 - 6 - 5

0 - 3 - 5 - 3 - 0

答:
Brackets around _id: </p>

```<code>function createData(_id){
  var _temp = '20C';
  var _battery = '60%';
  var _data = { [_id]:{temp:_temp,battery:_battery} };
  console.log(_data);
}
createData('Thermometer1');
</code>```

<p>Edit:
You can use a string to define a property of an object anywhere: </p>

```<code>let obj = { ['prop']: 42 }
console.log(obj.prop)
console.log(obj['prop'])
</code>```

Body:
here is the function

function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { _id:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');

Result :

[
_id:{temp:'20C',
     battery:'60%'
    }
]

Expected Result:

[
Thermometer1:{temp:'20C',
     battery:'60%'
    }
]

ignore the text below :v

it looks like your post is mostly code; please add more detail,

i don't know what to write so here is a guitar tab

0 - 3 - 5

0 - 3 - 6 - 5

0 - 3 - 5 - 3 - 0

Body:
Brackets around _id:

function createData(_id){
  var _temp = '20C';
  var _battery = '60%';
  var _data = { [_id]:{temp:_temp,battery:_battery} };
  console.log(_data);
}
createData('Thermometer1');

Edit:
You can use a string to define a property of an object anywhere:

let obj = { ['prop']: 42 }
console.log(obj.prop)
console.log(obj['prop'])


问:
SwiftUI, Fatal error: Unexpectedly found nil while unwrapping an Optional value
```<code>func loadImageFromUrl() {

        guard let urlString = self.urlString else {
        return
    }

    let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: self.getImageFromResponse(data:response:error:))
        task.resume()
}
</code>```

I keep on getting this fatal error (mentioned in title) for let url = URL(string: urlString)!, even if I have tried to guard it in previous lines. Also, when I move my cursor over urlString, it indeed shows a highlight of my intended url from the API.

答:
url could still be nil, if urlString doesn't represent a valid URL. You haven't guarded against that; you've only guarded against urlString not being nil.

You need to guard against both possible outcomes:

```<code>func loadImageFromUrl() {

   guard let url = URL(string: self.urlString) else {
      print("Invalid url string: \(self.urlString)")
      return
   }

   let task = URLSession.shared.dataTask(with: url, ....

   // rest of your code
}
</code>```

Of course, that doesn't solve the underlying problem that urlString is indeed broken. You need to see what's going on there.

Since you're visually seeing that it's correct, it's possible that it contains some whitespace at the beginning or the end. If it's not a urlString that you control, you can trim it:

```<code>let trimmedUrlStr = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)
</code>```

Body:
func loadImageFromUrl() {

        guard let urlString = self.urlString else {
        return
    }

    let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: self.getImageFromResponse(data:response:error:))
        task.resume()
}

I keep on getting this fatal error (mentioned in title) for let url = URL(string: urlString)!, even if I have tried to guard it in previous lines. Also, when I move my cursor over urlString, it indeed shows a highlight of my intended url from the API.

Body:
url could still be nil, if urlString doesn't represent a valid URL. You haven't guarded against that; you've only guarded against urlString not being nil.

You need to guard against both possible outcomes:

func loadImageFromUrl() {

   guard let url = URL(string: self.urlString) else {
      print("Invalid url string: \(self.urlString)")
      return
   }

   let task = URLSession.shared.dataTask(with: url, ....

   // rest of your code
}

Of course, that doesn't solve the underlying problem that urlString is indeed broken. You need to see what's going on there.

Since you're visually seeing that it's correct, it's possible that it contains some whitespace at the beginning or the end. If it's not a urlString that you control, you can trim it:

let trimmedUrlStr = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)


问:
Xcode is saying my array is out of range but I can confirm that my array is not out of range
I have an array I am using for my TableView Cell similar to a Facebook Feed. I successfully have been able to have my app's version of the Feed successfully show date of when the user made a post, show the user's email that created a post, show a photo uploaded with post but I can't seem to figure out how to make an array to their user Profile. All information is pulled from Firebase.

Below you can see a screen shot of my database structure.

Here you can see my Posts structure where I store the posts information.

Posts > DocumentID > PostInformation (date, uploaded image url as string, poster email, like count as Int)

Posts Database Struture

tableview

I am trying to pull the user's profile from a different collection called Public.

Public > UserEmail (test@gmail.com) > User's information (name, date, profile photo url)

Public Database Structure

I got the post information from getting the information a Firestore Database and threw everything into an array.

Then I loaded everything into a tableview cell.

//post variables
      var userCommentArray = String

```<code>var likeArray = [Int]()

var userPostImageArray = [String]()

var userProfilePhotoArray = [String]()

var userPostDescription = [String]()

var PosterEmail = [String]()

var postDate = [String]()

var documentIDArray = [String]()
</code>```

Above is my post variables

Below is my cell and the arrays used to load their information.

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let Cell = tableView.dequeueReusableCell(withIdentifier: "VidaFeed", for: indexPath) as! FeedCell
    print("Posteremail count = \(PosterEmail.count)")

   >> //Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))
    Cell.FeedCellUserNameLabel.text = PosterEmail[indexPath.row]
    Cell.dateFeedCellLabel.text = "test"
    Cell.likeCountFeedCellLabel.text = String(likeArray[indexPath.row])
    Cell.postImageFeedCellLabel.sd_setImage(with: URL(string: self.userPostImageArray[indexPath.row]))
    Cell.postDescriptionLabel.text = userPostDescription[indexPath.row]

    if userPostImageArray[indexPath.row] == ""{
        Cell.postImageFeedCellLabel.isHidden = true
    }

    if userPostImageArray[indexPath.row] != "" {
        Cell.postImageFeedCellLabel.isHidden = false
    }

    return Cell
</code>```

//Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))

If I only comment out the profile cell then my app runs successfully, but it crashes whenever I add it back.

Below you can see where I tried to make sure my var userProfilePhotoArray wouldn't be out of my index range because I set it equal to a variable to limit going over the array range.

```<code>      if self.profilecount <= self.PosterEmail.count{
</code>```

                            self.profilecount = self.profilecount + 1

```<code>       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return PosterEmail.count
}
</code>```

```<code>    func getDatFromFirestore() {

let firestoreDatabase = Firestore.firestore()

    firestoreDatabase.collection("Posts").order(by: "Date" , descending : true).addSnapshotListener { (snapshot, error) in
        if error != nil {
            print(error?.localizedDescription ?? "Connection Error")
        } else {
            self.userPostImageArray.removeAll(keepingCapacity: false)
            self.userCommentArray.removeAll(keepingCapacity: false)
            self.userCommentArray.removeAll(keepingCapacity: false)
            self.likeArray.removeAll(keepingCapacity: false)
            self.PosterEmail.removeAll(keepingCapacity: false)
            self.userProfilePhotoArray.removeAll(keepingCapacity: false)

            for document in snapshot!.documents {

                self.dbread = self.dbread + 1

                print(self.dbread)

                let documentID = document.documentID

                self.documentIDArray.append(documentID)

                self.getUserProfilePhoto()

                if let postedBy = document.get("postedBy") as? String {

                    self.PosterEmail.append(postedBy)

                    let db = Firestore.firestore()

                    let docRef = db.collection("Public").document(postedBy)

                    docRef.getDocument { (document, error) in
                        if self.profilecount <= self.PosterEmail.count{
                        self.profilecount = self.profilecount + 1
                        print("Profile count is \(self.profilecount)")
                        if let document = document, document.exists {
                            print(document)
                            if let userProfile = document.get("imageUrl") as? String {

                                self.userProfilePhotoArray.append(userProfile)

                                print("time = \(Date.self), \(self.userProfilePhotoArray).")

                        }
                    }
                }
            }

                if let postDescription = document.get("PostDescription") as? String {
                    self.userPostDescription.append(postDescription)
                }

                if let imageUrl = document.get("imageUrl") as? String {
                    self.userPostImageArray.append(imageUrl)
                }

                if let PostLikes = document.get("Likes") as? Int {
                    self.likeArray.append(PostLikes)
                }

                if let timeStamp = document.get("Date") as? Date {

                    let formatter = DateFormatter()
                    formatter.dateFormat = "MM/dd/yyyy"
                    let dateString = formatter.string(from: timeStamp)

                    let timeStampAsString = dateString

                    self.postDate.append(timeStampAsString)
                }

            }
            self.VidaFeed.reloadData()
        }

    }
}
</code>```

Below is the output and I can clearly see that the array is equal to my PosterEmail array count and is it not going over but the app crashes whenever re add the cell for the user's profile image.

```<code>Posteremail count = 1
Profile count is 1
<FIRDocumentSnapshot: 0x6000001a2850>
time = 2020-06-01 03:00:28 +0000, "https://firebasestorage.googleapis.com/v0/b/vida-clock-11690.appspot.com/o/UserProfilePhotos%2F8C2ADEC6-C108-4C70-8CDA-ADBFCC56B4E2?alt=media&token=1c2178b8-b35b-4e2a-bbc0-c7747843b673"].
</code>```

I'm just stuck and nothing I have tired has worked so far. Any suggestions?

答:
A Firebase document will be fetched over network connection or a local disk cache, which means there are no guarantees on how long each API call takes. So, the Firebase API calls are always asynchronous. The first API call you have will fetch the Posts collection ordered by date, iterate through all the documents and append data into the PosterEmail array. It also appends data into userProfilePhotoArray array, but note that this is done through a different API call, which means it is done asynchronously. However, you are calling reloadData() method on VidaFeed before the second asynchronous call is completed - the one that populates userProfilePhotoArray - which means the count in PosterEmail and userProfilePhotoArray are not the same.

One way to solve this is by adding self.VidaFeed.reloadData() within the docRef.getDocument { (document, error) in ... } as well:

```<code>        docRef.getDocument { (document, error) in
          if self.profilecount <= self.PosterEmail.count{
            self.profilecount = self.profilecount + 1
            print("Profile count is \(self.profilecount)")
            if let document = document, document.exists {
              print(document)
              if let userProfile = document.get("imageUrl") as? String {

                self.userProfilePhotoArray.append(userProfile)

                print("time = \(Date.self), \(self.userProfilePhotoArray).")

                // Add this line.
                self.VidaFeed.reloadData()
              }
            }
          }
        }
</code>```

This ensures that the VidaFeed will be notified every time a new item is added to userProfilePhotoArray.

Now, in cellForRowAt method, replace

```<code>Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))
</code>```

with

```<code>if indexPath.row < self.userProfilePhotoArray.count {
    Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))
}
</code>```

Body:
I have an array I am using for my TableView Cell similar to a Facebook Feed. I successfully have been able to have my app's version of the Feed successfully show date of when the user made a post, show the user's email that created a post, show a photo uploaded with post but I can't seem to figure out how to make an array to their user Profile. All information is pulled from Firebase.

Below you can see a screen shot of my database structure.

Here you can see my Posts structure where I store the posts information.

Posts > DocumentID > PostInformation (date, uploaded image url as string, poster email, like count as Int)

Posts Database Struture

tableview

I am trying to pull the user's profile from a different collection called Public.

Public > UserEmail (test@gmail.com) > User's information (name, date, profile photo url)

Public Database Structure

I got the post information from getting the information a Firestore Database and threw everything into an array.

Then I loaded everything into a tableview cell.

//post variables
      var userCommentArray = String

var likeArray = [Int]()

var userPostImageArray = [String]()

var userProfilePhotoArray = [String]()

var userPostDescription = [String]()

var PosterEmail = [String]()

var postDate = [String]()

var documentIDArray = [String]()

Above is my post variables

Below is my cell and the arrays used to load their information.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let Cell = tableView.dequeueReusableCell(withIdentifier: "VidaFeed", for: indexPath) as! FeedCell
    print("Posteremail count = \(PosterEmail.count)")

   >> //Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))
    Cell.FeedCellUserNameLabel.text = PosterEmail[indexPath.row]
    Cell.dateFeedCellLabel.text = "test"
    Cell.likeCountFeedCellLabel.text = String(likeArray[indexPath.row])
    Cell.postImageFeedCellLabel.sd_setImage(with: URL(string: self.userPostImageArray[indexPath.row]))
    Cell.postDescriptionLabel.text = userPostDescription[indexPath.row]

    if userPostImageArray[indexPath.row] == ""{
        Cell.postImageFeedCellLabel.isHidden = true
    }

    if userPostImageArray[indexPath.row] != "" {
        Cell.postImageFeedCellLabel.isHidden = false
    }

    return Cell

//Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))

If I only comment out the profile cell then my app runs successfully, but it crashes whenever I add it back.

Below you can see where I tried to make sure my var userProfilePhotoArray wouldn't be out of my index range because I set it equal to a variable to limit going over the array range.

      if self.profilecount <= self.PosterEmail.count{

                            self.profilecount = self.profilecount + 1

       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return PosterEmail.count
}

    func getDatFromFirestore() {

let firestoreDatabase = Firestore.firestore()

    firestoreDatabase.collection("Posts").order(by: "Date" , descending : true).addSnapshotListener { (snapshot, error) in
        if error != nil {
            print(error?.localizedDescription ?? "Connection Error")
        } else {
            self.userPostImageArray.removeAll(keepingCapacity: false)
            self.userCommentArray.removeAll(keepingCapacity: false)
            self.userCommentArray.removeAll(keepingCapacity: false)
            self.likeArray.removeAll(keepingCapacity: false)
            self.PosterEmail.removeAll(keepingCapacity: false)
            self.userProfilePhotoArray.removeAll(keepingCapacity: false)

            for document in snapshot!.documents {

                self.dbread = self.dbread + 1

                print(self.dbread)

                let documentID = document.documentID

                self.documentIDArray.append(documentID)

                self.getUserProfilePhoto()

                if let postedBy = document.get("postedBy") as? String {

                    self.PosterEmail.append(postedBy)

                    let db = Firestore.firestore()

                    let docRef = db.collection("Public").document(postedBy)

                    docRef.getDocument { (document, error) in
                        if self.profilecount <= self.PosterEmail.count{
                        self.profilecount = self.profilecount + 1
                        print("Profile count is \(self.profilecount)")
                        if let document = document, document.exists {
                            print(document)
                            if let userProfile = document.get("imageUrl") as? String {

                                self.userProfilePhotoArray.append(userProfile)

                                print("time = \(Date.self), \(self.userProfilePhotoArray).")

                        }
                    }
                }
            }

                if let postDescription = document.get("PostDescription") as? String {
                    self.userPostDescription.append(postDescription)
                }

                if let imageUrl = document.get("imageUrl") as? String {
                    self.userPostImageArray.append(imageUrl)
                }

                if let PostLikes = document.get("Likes") as? Int {
                    self.likeArray.append(PostLikes)
                }

                if let timeStamp = document.get("Date") as? Date {

                    let formatter = DateFormatter()
                    formatter.dateFormat = "MM/dd/yyyy"
                    let dateString = formatter.string(from: timeStamp)

                    let timeStampAsString = dateString

                    self.postDate.append(timeStampAsString)
                }

            }
            self.VidaFeed.reloadData()
        }

    }
}

Below is the output and I can clearly see that the array is equal to my PosterEmail array count and is it not going over but the app crashes whenever re add the cell for the user's profile image.

Posteremail count = 1
Profile count is 1
<FIRDocumentSnapshot: 0x6000001a2850>
time = 2020-06-01 03:00:28 +0000, "https://firebasestorage.googleapis.com/v0/b/vida-clock-11690.appspot.com/o/UserProfilePhotos%2F8C2ADEC6-C108-4C70-8CDA-ADBFCC56B4E2?alt=media&token=1c2178b8-b35b-4e2a-bbc0-c7747843b673"].

I'm just stuck and nothing I have tired has worked so far. Any suggestions?

Body:
A Firebase document will be fetched over network connection or a local disk cache, which means there are no guarantees on how long each API call takes. So, the Firebase API calls are always asynchronous. The first API call you have will fetch the Posts collection ordered by date, iterate through all the documents and append data into the PosterEmail array. It also appends data into userProfilePhotoArray array, but note that this is done through a different API call, which means it is done asynchronously. However, you are calling reloadData() method on VidaFeed before the second asynchronous call is completed - the one that populates userProfilePhotoArray - which means the count in PosterEmail and userProfilePhotoArray are not the same.

One way to solve this is by adding self.VidaFeed.reloadData() within the docRef.getDocument { (document, error) in ... } as well:

        docRef.getDocument { (document, error) in
          if self.profilecount <= self.PosterEmail.count{
            self.profilecount = self.profilecount + 1
            print("Profile count is \(self.profilecount)")
            if let document = document, document.exists {
              print(document)
              if let userProfile = document.get("imageUrl") as? String {

                self.userProfilePhotoArray.append(userProfile)

                print("time = \(Date.self), \(self.userProfilePhotoArray).")

                // Add this line.
                self.VidaFeed.reloadData()
              }
            }
          }
        }

This ensures that the VidaFeed will be notified every time a new item is added to userProfilePhotoArray.

Now, in cellForRowAt method, replace

Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))

with

if indexPath.row < self.userProfilePhotoArray.count {
    Cell.userProfilePhotoFeedCellLabel.sd_setImage(with: URL(string: self.userProfilePhotoArray[indexPath.row]))
}


问:
pods not get the correct coredns ip address
I am deploy coredns(v1.6.7) in my kuberntes cluster(v1.15.2),now the pod's /etc/resolv.conf:

```<code> nameserver 10.96.0.10
    search default.svc.cluster.local svc.cluster.local cluster.local
    options ndots:5
</code>```

but my codedns's ip is 10.96.0.2,how to make it using my cluster's coredns ip? This is the dns config:

```<code>dnsPolicy: ClusterFirst
</code>```

答:
but my codedns's ip is 10.96.0.2,how to make it using my cluster's coredns ip?

You didn't mention how you start cluster. But I guess your are using kubedns. Deploy coredns didn't mean use it. You will need to configure default kubernetes behavior.

Solution

ref: https://github.com/coredns/deployment/tree/master/kubernetes

CoreDNS can run in place of the standard Kube-DNS in Kubernetes. Using the kubernetes plugin, CoreDNS will read zone data from a Kubernetes cluster. It implements the spec defined for Kubernetes DNS-Based service discovery:

In the best case scenario, all that's needed to replace Kube-DNS are these commands:

```<code>$ ./deploy.sh | kubectl apply -f -
$ kubectl delete --namespace=kube-system deployment kube-dns
</code>```

Body:
I am deploy coredns(v1.6.7) in my kuberntes cluster(v1.15.2),now the pod's /etc/resolv.conf:

 nameserver 10.96.0.10
    search default.svc.cluster.local svc.cluster.local cluster.local
    options ndots:5

but my codedns's ip is 10.96.0.2,how to make it using my cluster's coredns ip? This is the dns config:

dnsPolicy: ClusterFirst

Body:
but my codedns's ip is 10.96.0.2,how to make it using my cluster's coredns ip?

You didn't mention how you start cluster. But I guess your are using kubedns. Deploy coredns didn't mean use it. You will need to configure default kubernetes behavior.

Solution

ref: https://github.com/coredns/deployment/tree/master/kubernetes

CoreDNS can run in place of the standard Kube-DNS in Kubernetes. Using the kubernetes plugin, CoreDNS will read zone data from a Kubernetes cluster. It implements the spec defined for Kubernetes DNS-Based service discovery:

In the best case scenario, all that's needed to replace Kube-DNS are these commands:

$ ./deploy.sh | kubectl apply -f -
$ kubectl delete --namespace=kube-system deployment kube-dns


问:
finding out vertical pinch out in UIPinchgestureRecogniser?
I want to increase width of UIView,when pinching out horizontally and also height only when pinching out vertically? is it possible in UIPinchGestureRecogniser?</p>

答: Not directly possible but if you were to maintain state yes. You can get the touch points using locationOfTouch:inView. Track them as he pinches and see which direction they are in. Update accordingly.