问:
No Coverage for Moles Tests on x64 Windows Server 2003
For some reason OpenCover is not covering tests using moles on Windows Server 2003 (64bit). I raised a similar question which solved it on my 32bit Windows 7 machine, but for some reason setting the Environment Variable on the Windows Server machine doesn't make a difference.

```<code>CLRMONITOR_EXTERNAL_PROFILERS: 1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8
</code>```

Is there a different CLSID for the x64 profiler? Or could this be another problem?

Steps to reproduce

Create a new project in visual studio with three methods:

```<code>public int method1()
{
    return 1;
}

public int method2()
{
    return 2;
}

public int method3()
{
    return 3;
}
</code>```

Next create a test project like so:

```<code>[TestMethod()]
public void method1Test()
{
    // Test without moles
    Program target = new Program();
    int expected = 1;
    int actual = target.method1();
    Assert.AreEqual(expected, actual);
}

[TestMethod()]
[HostType("Moles")]
public void method2Test()
{
    // Test using moles
    ConsoleApplication2.Moles.MProgram.AllInstances.method2 = (instance) => { return 3; };
    Program target = new Program();

    // method3 is only called in this test
    int check = target.method3();
    int actual = target.method2();
    Assert.AreEqual(3, actual);
    Assert.AreEqual(3, check);
}
</code>```

So that the above compiles, you will need to "Add a Moles Assembly" by right clicking on the ConsoleApplication2 reference and selecting "Add Moles Assembly".

Run OpenCover with the following command:

```<code>C:\Program Files\OpenCover>OpenCover.Console.exe
-target:"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"
-targetdir:"S:\Work\ConsoleApplication2"
-targetargs:"/testcontainer:\"TestProject1\bin\Debug\TestProject1.dll\""
-filter:"+[*]*"
-output:results.xml
-mergebyhash
</code>```

The 64bit machine equivalent:

```<code>C:\Program Files (x86)\OpenCover>OpenCover.Console.exe"
-target:"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"
-targetdir:"S:\Work\ConsoleApplication2"
-targetargs:"/testcontainer:\"TestProject1\bin\Debug\TestProject1.dll\""
-filter:"+[*]*"
-output:results.xml
-mergebyhash
</code>```

Run ReportGenerator on the results.xml file.

Expected Results

If successful (as on my 32bit Windows 7 machine) the report should show method3 as covered (it is called in method2Test), and look like this:

However when run on the 64bit Windows Server, the results look like this:

In both cases all tests pass, but no coverage information is being picked up for the test using Moles on the 64bit Windows Server.

I hope this gives a more clear explanation of the problem - let me know if you need any more information.

Thanks, Jack

答:
I followed your instructions and I got your results when I used

set CLRMONITOR_EXTERNAL_PROFILERS=1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8

but I got required coverage results when I changed this to

set CLRMONITOR_EXTERNAL_PROFILERS={1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}

NOTE: used braces - which is the usual way of expressing a GUID

Body:
For some reason OpenCover is not covering tests using moles on Windows Server 2003 (64bit). I raised a similar question which solved it on my 32bit Windows 7 machine, but for some reason setting the Environment Variable on the Windows Server machine doesn't make a difference.

CLRMONITOR_EXTERNAL_PROFILERS: 1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8

Is there a different CLSID for the x64 profiler? Or could this be another problem?

Steps to reproduce

Create a new project in visual studio with three methods:

public int method1()
{
    return 1;
}

public int method2()
{
    return 2;
}

public int method3()
{
    return 3;
}

Next create a test project like so:

[TestMethod()]
public void method1Test()
{
    // Test without moles
    Program target = new Program();
    int expected = 1;
    int actual = target.method1();
    Assert.AreEqual(expected, actual);
}

[TestMethod()]
[HostType("Moles")]
public void method2Test()
{
    // Test using moles
    ConsoleApplication2.Moles.MProgram.AllInstances.method2 = (instance) => { return 3; };
    Program target = new Program();

    // method3 is only called in this test
    int check = target.method3();
    int actual = target.method2();
    Assert.AreEqual(3, actual);
    Assert.AreEqual(3, check);
}

So that the above compiles, you will need to "Add a Moles Assembly" by right clicking on the ConsoleApplication2 reference and selecting "Add Moles Assembly".

Run OpenCover with the following command:

C:\Program Files\OpenCover>OpenCover.Console.exe
-target:"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"
-targetdir:"S:\Work\ConsoleApplication2"
-targetargs:"/testcontainer:\"TestProject1\bin\Debug\TestProject1.dll\""
-filter:"+[*]*"
-output:results.xml
-mergebyhash

The 64bit machine equivalent:

C:\Program Files (x86)\OpenCover>OpenCover.Console.exe"
-target:"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"
-targetdir:"S:\Work\ConsoleApplication2"
-targetargs:"/testcontainer:\"TestProject1\bin\Debug\TestProject1.dll\""
-filter:"+[*]*"
-output:results.xml
-mergebyhash

Run ReportGenerator on the results.xml file.

Expected Results

If successful (as on my 32bit Windows 7 machine) the report should show method3 as covered (it is called in method2Test), and look like this:

However when run on the 64bit Windows Server, the results look like this:

In both cases all tests pass, but no coverage information is being picked up for the test using Moles on the 64bit Windows Server.

I hope this gives a more clear explanation of the problem - let me know if you need any more information.

Thanks, Jack


来源: stackexchange

问:
AWS CDK: Lambda resource based policy for a function with an alias
I am using CDK to create a lambda, a new version of the lambda, and point the "live" alias to the newest version of the lambda like so

        const func = new lambda.Function(this, 'lambdaName', {
            // Other properties
            description: `Generated on: ${new Date().toISOString()}`,
        });

        const version = func.addVersion(new Date().toISOString());

        const alias = new lambda.Alias(this, 'lambdaName-alias', {
            aliasName: 'live',
            version: version,
        });
```
<p>Now, I want to add resource based permission to the alias <code>live</code> and not just the main lambda function.</p>
<p>I assumed that this would work but it doesn't create any resource based permissions at all:</p>
<pre class="lang-js prettyprint-override"><code>     alias.addPermission('CrossAccountAccessId', {
       action: 'lambda:InvokeFunction',
       principal: new ArnPrincipal('ACOUNT_NUMBER_XXX')
     });
</code>```

How to add permissions to an alias using AWS CDK?

I referred to this for resource based alias permission-ing:     https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#versioning-permissions-alias

For the CDK docs, I read this: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Alias.html#addwbrpermissionid-permission

I think it might be related to a bug in AWS CDK where adding resource based policy on a lambda version fails as mentioned here: AWS CDK: Resource Policies are not being granted for Lambda Version but I'm not sure if aliases also have the same problem as that of versions.

答:
The following generates the expected cross-account lambda permission for the alias.  I use CDK v2, although the v1 will work, too.

The addVersion method is deprecated and is removed completely in v2. "Instead, use this.currentVersion to obtain a reference to a version resource that gets automatically recreated when the function configuration (or code) changes".

const alias = func.currentVersion.addAlias('live');

// `iam.ArnPrincipal` will work (cdk does not validate the format), but, `iam.AccountPrincipal` is semantically correct in your case.
const principal = new iam.AccountPrincipal('123456789012');
```
<p>These 3 permission methods are equivalent:</p>
<pre class="lang-js prettyprint-override"><code>this.alias.grantInvoke(principal);

this.alias.addPermission('CrossAccountPermission', { principal });

this.alias.addPermission('CrossAccountPermission', {
  action: 'lambda:InvokeFunction', // this is the default value
  principal,
});
</code>```

The permission is created as expected. This test passes with any of the above 3 methods:

// MyStack.test.ts
const cfnAlias = stack.alias.node.defaultChild as lambda.CfnAlias;

template.hasResourceProperties('AWS::Lambda::Permission', {
  Action: 'lambda:InvokeFunction',
  FunctionName: { Ref: stack.resolve(cfnAlias.logicalId) },
  Principal: '123456789012',
});
```

ContentLicense: CC BY-SA 4.0

Body:
I am using CDK to create a lambda, a new version of the lambda, and point the "live" alias to the newest version of the lambda like so

        const func = new lambda.Function(this, 'lambdaName', {
            // Other properties
            description: `Generated on: ${new Date().toISOString()}`,
        });

        const version = func.addVersion(new Date().toISOString());

        const alias = new lambda.Alias(this, 'lambdaName-alias', {
            aliasName: 'live',
            version: version,
        });

Now, I want to add resource based permission to the alias live and not just the main lambda function.

I assumed that this would work but it doesn't create any resource based permissions at all:

     alias.addPermission('CrossAccountAccessId', {
       action: 'lambda:InvokeFunction',
       principal: new ArnPrincipal('ACOUNT_NUMBER_XXX')
     });

How to add permissions to an alias using AWS CDK?

I referred to this for resource based alias permission-ing:     https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#versioning-permissions-alias

For the CDK docs, I read this: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Alias.html#addwbrpermissionid-permission

I think it might be related to a bug in AWS CDK where adding resource based policy on a lambda version fails as mentioned here: AWS CDK: Resource Policies are not being granted for Lambda Version but I'm not sure if aliases also have the same problem as that of versions.

Body:
The following generates the expected cross-account lambda permission for the alias.  I use CDK v2, although the v1 will work, too.

The addVersion method is deprecated and is removed completely in v2. "Instead, use this.currentVersion to obtain a reference to a version resource that gets automatically recreated when the function configuration (or code) changes".

const alias = func.currentVersion.addAlias('live');

// `iam.ArnPrincipal` will work (cdk does not validate the format), but, `iam.AccountPrincipal` is semantically correct in your case.
const principal = new iam.AccountPrincipal('123456789012');

These 3 permission methods are equivalent:

this.alias.grantInvoke(principal);

this.alias.addPermission('CrossAccountPermission', { principal });

this.alias.addPermission('CrossAccountPermission', {
  action: 'lambda:InvokeFunction', // this is the default value
  principal,
});

The permission is created as expected. This test passes with any of the above 3 methods:

// MyStack.test.ts
const cfnAlias = stack.alias.node.defaultChild as lambda.CfnAlias;

template.hasResourceProperties('AWS::Lambda::Permission', {
  Action: 'lambda:InvokeFunction',
  FunctionName: { Ref: stack.resolve(cfnAlias.logicalId) },
  Principal: '123456789012',
});


问:
I have a select option dropdown and it contains 50 options, but I need to restrict the option selecting to 5 options using Vue JS
```<code><div class="col-lg-4 col-md-4 col-sm-12">
 <label>Indicators (<span class="options">{{indicators}}</span>)</label>

   <select class="select" multiple data-live-search="true" data-none-selected-text="Select">
        <option v-for="in option" :max="3">{{indicator}}</option>
   </select>
   <label v-if="error" style="color: red;">you can select only 6 options</label>
</div>
</code>```

I have a select option dropdown which consist 50 options but I need to limit the option selection to 5 options only

答:
You can make method and on @change event of select slice only needed items:

new Vue({
  el: "#demo",
  data() {
    return {
      indicators: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],
      selected: [],
      error: false,
      nrOfOptions: 5
    }
  },
  methods: {
    selNr() {
      this.error = false
      if(this.selected.length > this.nrOfOptions) {
        this.error = true
        this.selected = this.selected.slice(0, this.nrOfOptions)
      }
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code><span class="options">{{indicators}}</span></code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  Indicators ()
  <select class="select" multiple data-live-search="true" data-none-selected-text="Select"
          v-model="selected"
          @change="selNr"
  >
    <option v-for="indicator in indicators" :max="3">{{ indicator }}</option>
  </select>
  you can select only {{ nrOfOptions }} options
   {{ selected }}

```

Body:
 Indicators ({{indicators}})

   <select class="select" multiple data-live-search="true" data-none-selected-text="Select">
        <option v-for="in option" :max="3">{{indicator}}</option>
   </select>
   you can select only 6 options

I have a select option dropdown which consist 50 options but I need to limit the option selection to 5 options only

Body:
You can make method and on @change event of select slice only needed items:

new Vue({
  el: "#demo",
  data() {
    return {
      indicators: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],
      selected: [],
      error: false,
      nrOfOptions: 5
    }
  },
  methods: {
    selNr() {
      this.error = false
      if(this.selected.length > this.nrOfOptions) {
        this.error = true
        this.selected = this.selected.slice(0, this.nrOfOptions)
      }
    }
  }
})

<span class="options">{{indicators}}</span>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<div id="demo">
  <div class="col-lg-4 col-md-4 col-sm-12">
  <label>Indicators ()</label>
  <select class="select" multiple data-live-search="true" data-none-selected-text="Select"
          v-model="selected"
          @change="selNr"
  >
    <option v-for="indicator in indicators" :max="3">{{ indicator }}</option>
  </select>
  <label v-if="error" style="color: red;">you can select only {{ nrOfOptions }} options</label>
   {{ selected }}
</div>
</div>


问:
How to set multiline string as value to json object
i want to add the multiline string posted below as a value to json.loads(self.payload)as follows

```<code>json.loads(self.payload)['evalscript']=self.evalScript
</code>```

i tried after that to display the contents of the added value as follows:

```<code>        logger.debug("self.payload:",json.dumps(self.payload))
</code>```

but the key and value i tried to add are not included in the object

how that can be achieved

multiline string

```<code>self.evalScript="""
        //VERSION=3
        function setup() {
        return {
            input: ["B02"],
            output: { id: 'default',
                    bands: 3 }
        };
        }

        function evaluatePixel(sample) {
        return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
        }
    """
</code>```

答:
You didn't assign parsed JSON to any variable. json.loads parses a JSON string and returns an object.

d = json.loads(self.payload)       # assign object
d['evalscript'] = self.evalScript  # modify key
self.payload = json.dumps(d)       # to JSON string
```

Body:
i want to add the multiline string posted below as a value to json.loads(self.payload)as follows

json.loads(self.payload)['evalscript']=self.evalScript

i tried after that to display the contents of the added value as follows:

        logger.debug("self.payload:",json.dumps(self.payload))

but the key and value i tried to add are not included in the object

how that can be achieved

multiline string

self.evalScript="""
        //VERSION=3
        function setup() {
        return {
            input: ["B02"],
            output: { id: 'default',
                    bands: 3 }
        };
        }

        function evaluatePixel(sample) {
        return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
        }
    """


问:
How to get the name of the domain that is assigned to a specific field/column of a table?
I use a select from StackOverflow: How can I get the table description (fields and types) from Firebird with dbExpress to get schema-data of Firebird databases.

However, this select does not show the name of the domain that is assigned to a field/column.

Does anybody know the syntax to get the domain-name, too?

答:
The column RDB$FIELD_SOURCE in the table RDB$RELATION_FIELDS hold the the field domain name. (@Marcodor)

Syntax:
RF.RDB$FIELD_SOURCE AS FIELD_DOMAIN,


问:
Unable to combine and generate reports on cypress
I am unable to combine and generate reports of the CLI run on cypress, but when I run the script manually it saves the report

package.json
 scripts" />

 dependencies" />

config.json

答:
As Example dependencies should be installed and your package.json file

```<code>"dependencies": {
  "cypress-multi-reporters": "^1.4.0",
  "mocha": "^8.3.2",
  "mochawesome": "^6.2.2",
  "mochawesome-merge": "^4.2.0",
  "mochawesome-report-generator": "^5.2.0"
}
</code>```

Add reporter settings in cypress.json

```<code>{
  "reporter": "cypress-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "mochawesome",
    "mochawesomeReporterOptions": {
      "reportDir": "cypress/reports/mocha",
      "quite": true,
      "overwrite": false,
      "html": false,
      "json": true
    }
  }
}
</code>```

Add scripts in package.json file
For Windows -

```<code>"scripts": {
    "clean:reports": "if exist cypress\\reports rmdir /s/q cypress\\reports && mkdir cypress\\reports mkdir cypress\\reports\\mochareports",

    "pretest": "npm run clean:reports",
    "scripts": "cypress run",
    "combine-reports": "mochawesome-merge cypress/reports/mocha/*.json > cypress/reports/mochareports/report.json",
"generate-report": "marge cypress/reports/mochareports/report.json -f report -o cypress/reports/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test" : "npm run scripts || npm run posttest"
 }
</code>```

For macOS/ Linux

```<code>"scripts": {
    "clean:reports": "rm -R -f cypress/reports && mkdir cypress/reports && mkdir cypress/reports/mochareports ",
    "pretest": "npm run clean:reports",
    "scripts": "cypress run",
    "combine-reports": "mochawesome-merge cypress/reports/mocha/*.json > cypress/reports/mochareports/report.json",
"generate-report": "marge cypress/reports/mochareports/report.json -f report -o cypress/reports/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test" : "npm run scripts || npm run posttest"
  }
</code>```

You can find more details in https://medium.com/tech-learn-share/attach-screenshot-into-mochawesome-html-report-in-cypress-ca3792081474

Body:
As Example dependencies should be installed and your package.json file

"dependencies": {
  "cypress-multi-reporters": "^1.4.0",
  "mocha": "^8.3.2",
  "mochawesome": "^6.2.2",
  "mochawesome-merge": "^4.2.0",
  "mochawesome-report-generator": "^5.2.0"
}

Add reporter settings in cypress.json

{
  "reporter": "cypress-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "mochawesome",
    "mochawesomeReporterOptions": {
      "reportDir": "cypress/reports/mocha",
      "quite": true,
      "overwrite": false,
      "html": false,
      "json": true
    }
  }
}

Add scripts in package.json file
For Windows -

"scripts": {
    "clean:reports": "if exist cypress\\reports rmdir /s/q cypress\\reports && mkdir cypress\\reports mkdir cypress\\reports\\mochareports",

    "pretest": "npm run clean:reports",
    "scripts": "cypress run",
    "combine-reports": "mochawesome-merge cypress/reports/mocha/*.json > cypress/reports/mochareports/report.json",
"generate-report": "marge cypress/reports/mochareports/report.json -f report -o cypress/reports/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test" : "npm run scripts || npm run posttest"
 }

For macOS/ Linux

"scripts": {
    "clean:reports": "rm -R -f cypress/reports && mkdir cypress/reports && mkdir cypress/reports/mochareports ",
    "pretest": "npm run clean:reports",
    "scripts": "cypress run",
    "combine-reports": "mochawesome-merge cypress/reports/mocha/*.json > cypress/reports/mochareports/report.json",
"generate-report": "marge cypress/reports/mochareports/report.json -f report -o cypress/reports/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test" : "npm run scripts || npm run posttest"
  }

You can find more details in https://medium.com/tech-learn-share/attach-screenshot-into-mochawesome-html-report-in-cypress-ca3792081474


问:
Cannot generate histogram with OpenMP locks
I am trying to learn how to use OpenMP locks, for which I am testing it on a program that generates a histogram, given some data.

I generate some random numbers with the following:

```<code>unsigned long seed = 9876543210 ;

std::mt19937_64 gen {seed} ;

float mu    = 5.0 ;
float sigma = 1.0 ;

std::normal_distribution<float> dist {mu, sigma} ;

int N = 5000 ;

float array[N] ;

for( int i=0; i<N; ++i ) array[i] = dist( gen ) ; // store random numbers
</code>```

To generate histogram (within a range [min, max]) with OpenMP locks, I do the following:

```<code>int bins = 5  ;
int hist[bins] ;
int ival ;

for( ival=0; ival<bins; ++ival ) hist[ival] = 0 ;

omp_lock_t locks[bins] ;

for( ival=0; ival<bins; ++ival ) omp_init_lock(&locks[ival]) ;

float min   = mu - 3*sigma       ;
float max   = mu + 3*sigma       ;
float scale = (max - min) / bins ;

int i ;

#pragma omp parallel for num_threads( 4 )
for( i=0; i<N; ++i ) {

ival = (int) floorf( (array[i] - min) / scale ) ; // bin index

if( ival < 0 || ival >= bins ) continue ;

omp_set_lock(&locks[ival]) ;
hist[ival]++ ;
omp_unset_lock(&locks[ival]) ;

}

for( ival=0; ival<bins; ++ival ) omp_destroy_lock(&locks[ival]) ;
</code>```

This program takes exceedingly long to run, so I had to quit it before it could finish. The serial version takes an instant and runs just fine.

What am I doing wrong here?

The compilation is done with g++ using the flags:

```<code>-std=c++11 -O2 -fopenmp
</code>```

Thanks in advance.

答:
Your use of locks is technically correct in the sense that they do what you intend them to do. However, locks are extremely slow when used in this manner. Highly contested locks like these are always slow. Even when not contested, they require at least one atomic instruction to lock and one to unlock. Those run at a throughput of 1 every 20 cycles or so. Your normal histogram may run at 1 per cycle or one every few cycles (due to load-store-forwarding).

The solution is to use one partial histogram per thread. Then accumulate all histograms at the end. This is described in many answers on SO. See for example

OpenMP parallelize grouped array sum using pointers

Calculate the histogram with OpenMP

Fill histograms (array reduction) in parallel with OpenMP without using a critical section

Body:
I am trying to learn how to use OpenMP locks, for which I am testing it on a program that generates a histogram, given some data.

I generate some random numbers with the following:

unsigned long seed = 9876543210 ;

std::mt19937_64 gen {seed} ;

float mu    = 5.0 ;
float sigma = 1.0 ;

std::normal_distribution<float> dist {mu, sigma} ;

int N = 5000 ;

float array[N] ;

for( int i=0; i<N; ++i ) array[i] = dist( gen ) ; // store random numbers

To generate histogram (within a range [min, max]) with OpenMP locks, I do the following:

int bins = 5  ;
int hist[bins] ;
int ival ;

for( ival=0; ival<bins; ++ival ) hist[ival] = 0 ;

omp_lock_t locks[bins] ;

for( ival=0; ival<bins; ++ival ) omp_init_lock(&locks[ival]) ;

float min   = mu - 3*sigma       ;
float max   = mu + 3*sigma       ;
float scale = (max - min) / bins ;

int i ;

#pragma omp parallel for num_threads( 4 )
for( i=0; i<N; ++i ) {

ival = (int) floorf( (array[i] - min) / scale ) ; // bin index

if( ival < 0 || ival >= bins ) continue ;

omp_set_lock(&locks[ival]) ;
hist[ival]++ ;
omp_unset_lock(&locks[ival]) ;

}

for( ival=0; ival<bins; ++ival ) omp_destroy_lock(&locks[ival]) ;

This program takes exceedingly long to run, so I had to quit it before it could finish. The serial version takes an instant and runs just fine.

What am I doing wrong here?

The compilation is done with g++ using the flags:

-std=c++11 -O2 -fopenmp

Thanks in advance.


问:
Graph API Facebook
Is Facebook graph API enough secure to store and retrieve data? Apparently, it's quite easy to access information of some unknown person with appropriate query. I would like to know is there any security threat of making personal information public? If anyone has any idea please share.</p>

答:
All depends on the permission.Here is the link for facebook app permission.

Permissions

It works.

Thanks

ContentLicense: CC BY-SA 3.0

Title: Graph API Facebook


问:
How to get all table counts from database in JSON output in TSQL script
I would like to have a TSQL script to output all table counts from a SQL Server database to a JSON file. Getting the table counts is not the problem, but outputting this to JSON is the issue. I can't get it to work.

This is what I have to get the table counts:

```<code>USE databasename
GO

SELECT
      QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName]
      , SUM(sPTN.Rows) AS [RowCount]
FROM
      sys.objects AS sOBJ
      INNER JOIN sys.partitions AS sPTN
            ON sOBJ.object_id = sPTN.object_id
WHERE
      sOBJ.type = 'U'
      AND sOBJ.is_ms_shipped = 0x0
      AND index_id < 2 -- 0:Heap, 1:Clustered
GROUP BY
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]

GO
</code>```

How can I output the results to JSON?

答:
To convert a simple resultset to Json, add for json auto to the end of the statement eg,

```<code>...GROUP BY
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]
FOR JSON AUTO
</code>```

See this example DB<>Fiddle

Body:
I would like to have a TSQL script to output all table counts from a SQL Server database to a JSON file. Getting the table counts is not the problem, but outputting this to JSON is the issue. I can't get it to work.

This is what I have to get the table counts:

USE databasename
GO

SELECT
      QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName]
      , SUM(sPTN.Rows) AS [RowCount]
FROM
      sys.objects AS sOBJ
      INNER JOIN sys.partitions AS sPTN
            ON sOBJ.object_id = sPTN.object_id
WHERE
      sOBJ.type = 'U'
      AND sOBJ.is_ms_shipped = 0x0
      AND index_id < 2 -- 0:Heap, 1:Clustered
GROUP BY
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]

GO

How can I output the results to JSON?

Body:
To convert a simple resultset to Json, add for json auto to the end of the statement eg,

...GROUP BY
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]
FOR JSON AUTO

See this example DB<>Fiddle


问:
Perl - Include YAML file in another YAML file
I am using YAML::XS LoadFile method to load a YAML file in a perl script. Does this module support some kind of construct for including another YAML file? If no, is there another CPAN module that has this feature?

Worst case, I will need to define my own construct for this. Any pointers or tips?

答:
A late answer, but yes, you can do that in perl with YAML::PP::Include (disclaimer: I'm the author)

```<code># /path/to/file.yaml
# ---
# included: !include include/file2.yaml

# /path/to/include/file2.yaml
# ---
# a: b
</code>```
```<code>use YAML::PP::Schema::Include;
my $include = YAML::PP::Schema::Include->new;

my $yp = YAML::PP->new( schema => ['Core', $include] );
$include->yp($yp);

my ($data) = $yp->load_file("/path/to/file.yaml");

# The result will be:
$data = {
    included => { a => 'b' }
};
</code>```

Also if you type in yaml include in metacpan you should get this module as a result: https://metacpan.org/search?size=20&q=yaml+include

Note that !include is not an official YAML tag, but any YAML library can choose to implement such a tag.

Body:
A late answer, but yes, you can do that in perl with YAML::PP::Include (disclaimer: I'm the author)

# /path/to/file.yaml
# ---
# included: !include include/file2.yaml

# /path/to/include/file2.yaml
# ---
# a: b

use YAML::PP::Schema::Include;
my $include = YAML::PP::Schema::Include->new;

my $yp = YAML::PP->new( schema => ['Core', $include] );
$include->yp($yp);

my ($data) = $yp->load_file("/path/to/file.yaml");

# The result will be:
$data = {
    included => { a => 'b' }
};

Also if you type in yaml include in metacpan you should get this module as a result: https://metacpan.org/search?size=20&q=yaml+include

Note that !include is not an official YAML tag, but any YAML library can choose to implement such a tag.


问:
Why script with Tensorflow.js src doesn't work?
If I remove src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" then it shows my alert. What's wrong?

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Brain Tumor </title>
<link rel="stylesheet" type="text/css" href="style.css">

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js">
alert("alert"); // doesn't work if there's src

/*async function LoadModels(){
           model = undefined;
           model = await tf.loadLayersModel("D:/user/diploma/models/models/model.json");
           const image = tf.fromPixels("D:/user/diploma/IM-0115-0001.jpeg");
           const prediction = model.predict(image);
           alert(prediction);
       }
       LoadModels();*/

</script>

</head>
...
</html>
</code>```

EDIT:

答:
You have to add alert in another script tag.

```<code>    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>
<script>
alert("alert");
</script>
</code>```

Body:
If I remove src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" then it shows my alert. What's wrong?

<!DOCTYPE html>

<meta charset="utf-8">
<title> Brain Tumor </title>
<link rel="stylesheet" type="text/css" href="style.css">

...

EDIT:

Body:
You have to add alert in another script tag.

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>
<script>
alert("alert");
</script>


问:
For an Azure Function HTTP Trigger how can I set a CORS policy "WithExposedHeaders("*")?
I am trying to get the Header values from a Azure Function HTTP Trigger.

I have a Blazor Wasm Client.

When I use the Client, the Headers collection is empty.

I have the same version of the code working with a my Blazor Wasm Client calling a REST API.  When I set up that version, I had to set up a CORS policy like the code below in my Startup.cs.

Once I added this code, my Blazor Wasm Client got the Header values from my API.

```<code>            services.AddCors(options =>
            {
                options.AddPolicy(StringConstant.AllowedSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins(origins)
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .WithExposedHeaders("*");
                    });
            });
</code>```

It looks like I have to do the same from my Azure Function since the Header collection is empty in my Response object.

Any idea on how to set this up?

My Blazor Wasm Client is using the httpClient.GetAsync method.

答:
Found the solution - https://stackoverflow.com/a/71080532/9276081, I've pasted my answer here as well -

The issue is not with Blazor WASM, rather if that header has been exposed on your API Side. In your azure function, add the following -

Note: Postman will still show the headers even if you don't expose the headers like below. That's because, Postman doesn't care about CORS headers. CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources and that's all.

First create a Startup File to inject the HttpContextAccessor

Package Required: Microsoft.Azure.Functions.Extensions

```<code>[assembly: FunctionsStartup(typeof(FuncAppName.Startup))]

namespace FuncAppName
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<HttpContextAccessor>();
        }
    }
}
</code>```

Next, inject it into your main Function -

```<code>using Microsoft.AspNetCore.Http;
namespace FuncAppName
{
    public class SomeFunction
    {
        private readonly HttpContext _httpContext;
        public SomeFunction(HttpContextAccessor contextAccessor)
        {
             _httpContext = contextAccessor.HttpContext;
        }

        [FunctionName("SomeFunc")]
        public override Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, new[] { "post" }, Route = "run")] HttpRequest req)
        {
            var response = "Some Response"
            _httpContext.Response.Headers.Add("my-custom-header", "some-custom-value");
            _httpContext.Response.Headers.Add("my-other-header", "some-other-value");
            _httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "my-custom-header, my-other-header");
            return new OkObjectResult(response)
        }
</code>```

If you want to allow all headers you can use wildcard (I think, not tested) -

```<code>_httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "*");
</code>```

You still need to add your web-app url to the azure platform CORS. You can add * wildcard, more info here - https://iotespresso.com/allowing-all-cross-origin-requests-azure-functions/

to enable CORS for Local Apps during development - https://stackoverflow.com/a/60109518/9276081

Now to access those headers in your Blazor WASM, as an e.g. you can -

```<code>protected override async Task OnInitializedAsync()
{
    var content = JsonContent.Create(new { query = "" });
    using (var client = new HttpClient())
    {
        var result = await client.PostAsync("https://func-app-name.azurewebsites.net/api/run", content);
        var headers = result.Headers.ToList();
    }
}
</code>```

Body:
I am trying to get the Header values from a Azure Function HTTP Trigger.

I have a Blazor Wasm Client.

When I use the Client, the Headers collection is empty.

I have the same version of the code working with a my Blazor Wasm Client calling a REST API.  When I set up that version, I had to set up a CORS policy like the code below in my Startup.cs.

Once I added this code, my Blazor Wasm Client got the Header values from my API.

            services.AddCors(options =>
            {
                options.AddPolicy(StringConstant.AllowedSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins(origins)
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .WithExposedHeaders("*");
                    });
            });

It looks like I have to do the same from my Azure Function since the Header collection is empty in my Response object.

Any idea on how to set this up?

My Blazor Wasm Client is using the httpClient.GetAsync method.

Body:
Found the solution - https://stackoverflow.com/a/71080532/9276081, I've pasted my answer here as well -

The issue is not with Blazor WASM, rather if that header has been exposed on your API Side. In your azure function, add the following -

Note: Postman will still show the headers even if you don't expose the headers like below. That's because, Postman doesn't care about CORS headers. CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources and that's all.

First create a Startup File to inject the HttpContextAccessor

Package Required: Microsoft.Azure.Functions.Extensions

[assembly: FunctionsStartup(typeof(FuncAppName.Startup))]

namespace FuncAppName
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<HttpContextAccessor>();
        }
    }
}

Next, inject it into your main Function -

using Microsoft.AspNetCore.Http;
namespace FuncAppName
{
    public class SomeFunction
    {
        private readonly HttpContext _httpContext;
        public SomeFunction(HttpContextAccessor contextAccessor)
        {
             _httpContext = contextAccessor.HttpContext;
        }

        [FunctionName("SomeFunc")]
        public override Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, new[] { "post" }, Route = "run")] HttpRequest req)
        {
            var response = "Some Response"
            _httpContext.Response.Headers.Add("my-custom-header", "some-custom-value");
            _httpContext.Response.Headers.Add("my-other-header", "some-other-value");
            _httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "my-custom-header, my-other-header");
            return new OkObjectResult(response)
        }

If you want to allow all headers you can use wildcard (I think, not tested) -

_httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "*");

You still need to add your web-app url to the azure platform CORS. You can add * wildcard, more info here - https://iotespresso.com/allowing-all-cross-origin-requests-azure-functions/

to enable CORS for Local Apps during development - https://stackoverflow.com/a/60109518/9276081

Now to access those headers in your Blazor WASM, as an e.g. you can -

protected override async Task OnInitializedAsync()
{
    var content = JsonContent.Create(new { query = "" });
    using (var client = new HttpClient())
    {
        var result = await client.PostAsync("https://func-app-name.azurewebsites.net/api/run", content);
        var headers = result.Headers.ToList();
    }
}


问:
Handling file transfers with scp
I'm trying to understand how scp works "under the hood".

The only reference I found that seem to explain how things work is a blog post on the Oracle website, through web archive.

Well, there, we can find a few examples, for instance:

{ echo D0755 0 testdir; echo C0644 6 test 123;
    printf "hello\\n"; echo E; } | scp -rqt /tmp
```
<p>While it does create <code>/tmp/testdir/test 123</code> with the right content, it actually <code>exit 1</code>. We can get more info by removing the <code>-q</code> flag:</p>
<pre class="lang-sh prettyprint-override"><code>$ { echo D0755 0 testdir; echo C0644 6 test 123;
     printf "hello\\n"; echo E; } | scp -tr /tmp
test 123         0%    0     0.0KB/s   --:-- ETA

$ echo $?
1
</code>```

So, we can see, it exits 0 and the progress is never updated.

My question is: why?

At first I thought it was because the terminal is not a SSH session, but then I actually tried to do it using golang.org/x/crypto/ssh, and I get the same results.

My guess is that both the terminal and my implementation are missing something, I don't know what it is, though.

Any pointers?

答:
OK, I figured it out!

Need to send a null byte after the file:

$ {
  echo D0755 0 testdir;
  echo C0644 6 test 123;
  printf "hello\\n";
  printf "\x00";
  echo E;
} | scp -tr /tmp
test 123         100%    6   102.4KB/s   00:00

$ echo $?
0
```

Title: Handling file transfers with scp

Body:
I'm trying to understand how scp works "under the hood".

The only reference I found that seem to explain how things work is a blog post on the Oracle website, through web archive.

Well, there, we can find a few examples, for instance:

{ echo D0755 0 testdir; echo C0644 6 test 123;
    printf "hello\\n"; echo E; } | scp -rqt /tmp

While it does create /tmp/testdir/test 123 with the right content, it actually exit 1. We can get more info by removing the -q flag:

$ { echo D0755 0 testdir; echo C0644 6 test 123;
     printf "hello\\n"; echo E; } | scp -tr /tmp
test 123         0%    0     0.0KB/s   --:-- ETA

$ echo $?
1

So, we can see, it exits 0 and the progress is never updated.

My question is: why?

At first I thought it was because the terminal is not a SSH session, but then I actually tried to do it using golang.org/x/crypto/ssh, and I get the same results.

My guess is that both the terminal and my implementation are missing something, I don't know what it is, though.

Any pointers?


问:
Visual Studio not installed; this is necessary for Windows development
My Flutter Doctor is saying:

Visual Studio - develop for Windows

X Visual Studio not installed; this is necessary for Windows development.
  Download at https://visualstudio.microsoft.com/downloads/.
  Please install the "Desktop development with C++" workload, including all
  of its default components.
```

How can I fix this problem?

答:
As it states, you need to download Visual Studio (which is different from Visual Studio Code).

When installing it, remember to select the required package Desktop development with C++:

This will not prevent you from developing Mobile apps, but it's a requirement only for Windows Development.

Body:
My Flutter Doctor is saying:

Visual Studio - develop for Windows

X Visual Studio not installed; this is necessary for Windows development.
  Download at https://visualstudio.microsoft.com/downloads/.
  Please install the "Desktop development with C++" workload, including all
  of its default components.

How can I fix this problem?


问:
How can i get value or check the role from Identity Server 4 to my MVC client?
I have an MVC Client (ASP.NET core) that interacts with Identity Server 4 (with Identity ASP.NET "installed") for all the functions of Login, Registration etc ..., without API.

In the Client I need to check the role of the logged in user and I don't know how to do it.
I tried the solution User.IsInRole("Administrator") but it doesn't read me the role, as well as [Authorize(Role="Administrator")].
When I log in with a user who has a role, this is actually displayed between the claims of the diagnostic page (in the image).

But the strange thing is that when I go to analyze, in the debug phase, the array of User.Claims Claims, "role" is not there or maybe I can't find it (being a beginner with Identity and Identity Server).

So how can I go about getting the role from the MVC Client?
I was thinking of creating Policy with the value of that "role", if User.IsInRole("Administrator") or [Authorize (Role = "Administrator")] cannot be used, but the problem is always that I can't get the role.

I leave you the Startup files of the client and Identity Server as well as the Config.cs of the latter so that you can analyze them better. There may be some unnecessary lines of code but it's all in development, so forgive me.

Startup.cs of Client

```<code>public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, true);
            Configuration = builder.Build();

        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "https://localhost:5001";

                    options.SignInScheme = "Cookies";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "mvc";
                    options.ClientSecret = "secret";
                    options.ResponseType = "code";

                    options.SaveTokens = true;

                });

            services.AddAuthorization(options => {

                options.AddPolicy("Admin", policy => policy.RequireRole("Administrator"));

            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(55);

            });

            string connString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext<SushiWebDbContext>(options => options.UseSqlServer(connString));
            services.AddMvc();
            services.AddRazorPages();
            services.AddControllersWithViews();
            services.AddDistributedMemoryCache();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }

            app.UseSession();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {

                endpoints.MapDefaultControllerRoute();

            });

        }
    }
</code>```

Startup.cs of Identity Server

```<code>public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddRoles<IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddTransient<IProfileService, UserProfile>();

            var builder = services.AddIdentityServer()
                .AddAspNetIdentity<ApplicationUser>()
                .AddConfigurationStore(options =>
                    {
                        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                    })
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                    })
                    .AddProfileService<UserProfile>();

            builder.AddDeveloperSigningCredential();

            services.AddAuthentication()
                .AddGoogle(options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                    options.ClientId = "copy client ID from Google here";
                    options.ClientSecret = "copy client secret from Google here";
                });
        }

        public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
        {

            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }

            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });

        }
}
</code>```

Config.cs of Identity Server

```<code> public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()

            };

        public static IEnumerable<ApiScope> ApiScopes =>
            new List<ApiScope>
            {

            };

        public static IEnumerable<Client> Clients =>
            new List<Client>
            {

                new Client
                {
                    ClientId = "mvc",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.Code,

                    // where to redirect to after login
                    RedirectUris = { "https://localhost:5002/signin-oidc" },

                    // where to redirect to after logout
                    PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    }
                }
            };
    }
</code>```

Perhaps the solution is easier than expected, forgive me for this. Thank you so much!

答:
To get roles from IdentityServer in MVC you need to change your Config.cs in IdentityServer project and also change Startup.cs in MVC project as follow:

Add in Startup.cs of MVC Client

```<code>.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    ...

    options.Scope.Add("roles");
    options.ClaimActions.MapJsonKey("role", "role");
    options.GetClaimsFromUserInfoEndpoint = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    };
}

</code>```

If we use MapUniqueJsonKey then all the roles will store like this:

```<code>...
[8] [Claim]:{role: ["Admin","User"]}
...
</code>```

In this case, User.IsInRole("Admin"); always return false so I prefer to get all roles like:

```<code>...
[8] [Claim]:{role: "Admin"}
[9] [Claim]:{role: "User"}
...
</code>```

Add in Config.cs in IdentityServer

```<code>public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
        };
    public static IEnumerable<Client> Clients =>
        new List<Client>
        {
            new Client
            {
                ...

                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "roles"
                }
            }
        };
</code>```

Change ConfigurationStore from SQL to Config.cs:
In IdentityServer Startup.cs

```<code>var builder = services.AddIdentityServer(options =>
{
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.Events.RaiseSuccessEvents = true;
    options.EmitStaticAudienceClaim = true;
    options.UserInteraction.LoginUrl = "/Account/Login";
    options.UserInteraction.LogoutUrl = "/Account/Logout";
    options.Authentication = new AuthenticationOptions()
    {
        CookieLifetime = TimeSpan.FromHours(10),
        CookieSlidingExpiration = true
    };
})
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients)
    .AddAspNetIdentity<ApplicationUser>();
</code>```

You can use the database instead of the Config.cs, but I do not prefer it because it adds a lot of tables to the database, and I prefer to use the configuration file for a small number of settings.

Body:
I have an MVC Client (ASP.NET core) that interacts with Identity Server 4 (with Identity ASP.NET "installed") for all the functions of Login, Registration etc ..., without API.

In the Client I need to check the role of the logged in user and I don't know how to do it.
I tried the solution User.IsInRole("Administrator") but it doesn't read me the role, as well as [Authorize(Role="Administrator")].
When I log in with a user who has a role, this is actually displayed between the claims of the diagnostic page (in the image).

But the strange thing is that when I go to analyze, in the debug phase, the array of User.Claims Claims, "role" is not there or maybe I can't find it (being a beginner with Identity and Identity Server).

So how can I go about getting the role from the MVC Client?
I was thinking of creating Policy with the value of that "role", if User.IsInRole("Administrator") or [Authorize (Role = "Administrator")] cannot be used, but the problem is always that I can't get the role.

I leave you the Startup files of the client and Identity Server as well as the Config.cs of the latter so that you can analyze them better. There may be some unnecessary lines of code but it's all in development, so forgive me.

Startup.cs of Client

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, true);
            Configuration = builder.Build();

        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "https://localhost:5001";

                    options.SignInScheme = "Cookies";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "mvc";
                    options.ClientSecret = "secret";
                    options.ResponseType = "code";

                    options.SaveTokens = true;

                });

            services.AddAuthorization(options => {

                options.AddPolicy("Admin", policy => policy.RequireRole("Administrator"));

            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(55);

            });

            string connString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext<SushiWebDbContext>(options => options.UseSqlServer(connString));
            services.AddMvc();
            services.AddRazorPages();
            services.AddControllersWithViews();
            services.AddDistributedMemoryCache();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }

            app.UseSession();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {

                endpoints.MapDefaultControllerRoute();

            });

        }
    }

Startup.cs of Identity Server

public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddRoles<IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddTransient<IProfileService, UserProfile>();

            var builder = services.AddIdentityServer()
                .AddAspNetIdentity<ApplicationUser>()
                .AddConfigurationStore(options =>
                    {
                        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                    })
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                    })
                    .AddProfileService<UserProfile>();

            builder.AddDeveloperSigningCredential();

            services.AddAuthentication()
                .AddGoogle(options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                    options.ClientId = "copy client ID from Google here";
                    options.ClientSecret = "copy client secret from Google here";
                });
        }

        public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
        {

            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }

            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });

        }
}

Config.cs of Identity Server

 public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()

            };

        public static IEnumerable<ApiScope> ApiScopes =>
            new List<ApiScope>
            {

            };

        public static IEnumerable<Client> Clients =>
            new List<Client>
            {

                new Client
                {
                    ClientId = "mvc",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.Code,

                    // where to redirect to after login
                    RedirectUris = { "https://localhost:5002/signin-oidc" },

                    // where to redirect to after logout
                    PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    }
                }
            };
    }

Perhaps the solution is easier than expected, forgive me for this. Thank you so much!

Body:
To get roles from IdentityServer in MVC you need to change your Config.cs in IdentityServer project and also change Startup.cs in MVC project as follow:

Add in Startup.cs of MVC Client

.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    ...

    options.Scope.Add("roles");
    options.ClaimActions.MapJsonKey("role", "role");
    options.GetClaimsFromUserInfoEndpoint = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    };
}

If we use MapUniqueJsonKey then all the roles will store like this:

...
[8] [Claim]:{role: ["Admin","User"]}
...

In this case, User.IsInRole("Admin"); always return false so I prefer to get all roles like:

...
[8] [Claim]:{role: "Admin"}
[9] [Claim]:{role: "User"}
...

Add in Config.cs in IdentityServer

public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
        };
    public static IEnumerable<Client> Clients =>
        new List<Client>
        {
            new Client
            {
                ...

                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "roles"
                }
            }
        };

Change ConfigurationStore from SQL to Config.cs:
In IdentityServer Startup.cs

var builder = services.AddIdentityServer(options =>
{
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.Events.RaiseSuccessEvents = true;
    options.EmitStaticAudienceClaim = true;
    options.UserInteraction.LoginUrl = "/Account/Login";
    options.UserInteraction.LogoutUrl = "/Account/Logout";
    options.Authentication = new AuthenticationOptions()
    {
        CookieLifetime = TimeSpan.FromHours(10),
        CookieSlidingExpiration = true
    };
})
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients)
    .AddAspNetIdentity<ApplicationUser>();

You can use the database instead of the Config.cs, but I do not prefer it because it adds a lot of tables to the database, and I prefer to use the configuration file for a small number of settings.


问:
CSS checking if input is checked and chaining elements
I cannot make this work, guys. The problem is I no longer have idea how to (try to) make it work.

#5starcheckbox:checked+label[for="5starcheckbox"]>.col-lg-10>.progress>.progress-bar {
  opacity: 1 !important;
}

input#5starcheckbox:checked+span#5starpercentage {
  color: #0060df !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="5starcheckbox" class="row filterlabel">
    <div class="col-lg-1 col-1">
        <div class="checkboxes text-end">

                <input type="checkbox" id="5starcheckbox" name="stars[]" value="5">
                <span class="checkmark"></span>

        </div>
    </div>
    <div class="col-lg-10 col-9 pt-1">
        <div class="progress">
            <div class="progress-bar progress5" role="progressbar" style="width: {{ $scoreInfo['percent_5_star'] }}%;opacity:0.6;" aria-valuenow="{{ $scoreInfo['percent_5_star'] }}" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
    </div>
    <div class="col-lg-1 col-2 text-end text-secondary" id="5starpercentage"><strong>{{ $scoreInfo['percent_5_star'] }}%</strong></div>
</label></code>```

Is there something wrong in my code? Why it isn't working?

答:
The problem is, that your label encloses your input. The CSS selector + (in your case #5starcheckbox:checked + label[for="5starcheckbox"]) matches the followin sibling, if the selector matches it. So, #5starcheckbox:checked + label[for="5starcheckbox"] only matches the label in the following code:

```<code><input type="checkbox" name="5starcheckbox" id="5starcheckbox">
<label for="5starcheckbox"></label>
</code>```

There isn't a parent selector in CSS.

Body:
I cannot make this work, guys. The problem is I no longer have idea how to (try to) make it work.

#5starcheckbox:checked+label[for="5starcheckbox"]>.col-lg-10>.progress>.progress-bar {
  opacity: 1 !important;
}

input#5starcheckbox:checked+span#5starpercentage {
  color: #0060df !important;
}

                <input type="checkbox" id="5starcheckbox" name="stars[]" value="5">

{{ $scoreInfo['percent_5_star'] }}%

Is there something wrong in my code? Why it isn't working?

Body:
The problem is, that your label encloses your input. The CSS selector + (in your case #5starcheckbox:checked + label[for="5starcheckbox"]) matches the followin sibling, if the selector matches it. So, #5starcheckbox:checked + label[for="5starcheckbox"] only matches the label in the following code:

<input type="checkbox" name="5starcheckbox" id="5starcheckbox">
<label for="5starcheckbox"></label>

There isn't a parent selector in CSS.


问:
Drop Database Error For Azure Synapse Database
When I try to drop a database in my builtin synapse pool, I'm getting the following error:

```<code>Cannot drop database "database name" because it is currently in use.
</code>```

I've tried in both SSMS and Studio Synapse Studio and both returned errors.

I made sure there's no external datasources and file formats in the database.

The SSMS command I used was:

```<code>DROP DATABASE [database name]
</code>```

Set Single_use mode doesn't work either. If you try this:

```<code>ALTER DATABASE [Database Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
</code>```

You'll get this:

```<code>SINGLE_USER is not supported for ALTER DATABASE.
</code>```

What blocks a database from being dropped in synapse?

Thanks.

答:
What worked for me is:

Run this in master

    select DB_NAME(database_id), 'kill '+cast(session_id as varchar(10)), *
    from sys.dm_exec_sessions
    where DB_NAME(database_id) NOT IN ('master')
    order by 1
```
<ol start="2">
<li>Kill all sessions (active as well as sleeping) for the database you want to delete using the kill command returned by the query above. Run it in master:</li>
</ol>
<pre class="lang-sql prettyprint-override"><code>    kill 82
</code>```

Drop the database from Synapse Studio, not from SSMS

Body:
When I try to drop a database in my builtin synapse pool, I'm getting the following error:

Cannot drop database "database name" because it is currently in use.

I've tried in both SSMS and Studio Synapse Studio and both returned errors.

I made sure there's no external datasources and file formats in the database.

The SSMS command I used was:

DROP DATABASE [database name]

Set Single_use mode doesn't work either. If you try this:

ALTER DATABASE [Database Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

You'll get this:

SINGLE_USER is not supported for ALTER DATABASE.

What blocks a database from being dropped in synapse?

Thanks.

Body:
What worked for me is:

Run this in master

    select DB_NAME(database_id), 'kill '+cast(session_id as varchar(10)), *
    from sys.dm_exec_sessions
    where DB_NAME(database_id) NOT IN ('master')
    order by 1

Kill all sessions (active as well as sleeping) for the database you want to delete using the kill command returned by the query above. Run it in master:

    kill 82

Drop the database from Synapse Studio, not from SSMS


问:
Is there a way to automatically fix `import type` errors on TypeScript when using "importsNotUsedAsValues": "error"?
I have a big TypeScript project that I started without using the "importsNotUsedAsValues": "error" compiler flag. As the project grew, I decided it is a good idea in terms of optimization to enforce import type when an import is not being used as a value.

Enabling this works fine and even makes my IDE auto import types using import types when possible, and it can also automatically fix open files that do not import types as types only, but not the entire project in one go, and I have so many of those cases in the project that fixing them manually is inconceivable.

I've been reading ESLint, TSC and similar tools documentations trying to find a way I could use them to automatically fix the imports, but with no success. Does anyone know a tool that could automatically fix those issues?

答:
After a little more searching, I found ESLint rule consistent-type-imports which basically ensure the same as "importsNotUsedAsValues": "error" TypeScript compiler flag but on ESLint level.

Enabling it was as simple as adding

```<code>'@typescript-eslint/consistent-type-imports': 'error',
</code>```

to rules section in my ESLint configuration file.

To autofix, now I then simply needed to run

```<code>eslint --fix .
</code>```

Body:
After a little more searching, I found ESLint rule consistent-type-imports which basically ensure the same as "importsNotUsedAsValues": "error" TypeScript compiler flag but on ESLint level.

Enabling it was as simple as adding

'@typescript-eslint/consistent-type-imports': 'error',

to rules section in my ESLint configuration file.

To autofix, now I then simply needed to run

eslint --fix .


问:
amazon alb and basic auth
I have a simple site in fargate and an alb.    I want to throw a simple basic auth on top of it - just a single hardwired username and password.  Is there an easy way to do this?

I tried going to cognito - creating a user pool, and attaching it to the site, but there were questions like "callback url" - which i just set to the same url and "signout url" that I wasn't sure about and when I managed to click a set of things that allowed me to add it, and add a listener to my https endpoint - it just gives a "redirect_mismatch" when I try to get in.

Is there any way to do what I want without editing the underlying system in any way?

答:
This is currently not possible. The supported methods are:

OIDC

Cognito: which supports common social IdPs and corporate identities like LDAP, SAML, etc.

Please refer to the ALB documentation for more information.

A common solution for this is to deploy an nginx server between the user and your service and configure it to provide the basic authentication layer you need.

Title: amazon alb and basic auth


问:
Angular DataTables: $(...).DataTable is not a function
Angular Version: 6.0.4 ~ Node Version: 10.4.1 ~ NPM Version: 6.1.0

I've seen this question asked many times, but not answered.

After following these instructions to install angular-datables, and trying to use the directive on a table, as in their Zero Configuration example, I keep getting this error:

TypeError: $(...).DataTable is not a function

at angular-datatables.directive.js:42

Included Styles and Scripts

"styles": [
   "node_modules/bootstrap/dist/css/bootstrap.min.css",
   "node_modules/datatables.net-dt/css/jquery.dataTables.css",
   "src/styles.css"
],
"scripts": [
   "node_modules/jquery/dist/jquery.min.js",
   "node_modules/bootstrap/dist/js/bootstrap.min.js",
   "node_modules/datatables.net/js/jquery.dataTables.js"
]
```
<p><strong>Import in app.module.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import { DataTablesModule } from 'angular-datatables';
</code>```

DataTablesModule is added to array of imports.

*.component.html

View Accounts

      #
      Account Name

      {{i+1}}
      {{account.accountHolder}}

```

答:
I was missing '        "node_modules/datatables.net/js/jquery.dataTables.js",
'
in angular.json
It should look like</p>
```<code>"scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/datatables.net/js/jquery.dataTables.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ]
</code>```

Body:
Angular Version: 6.0.4 ~ Node Version: 10.4.1 ~ NPM Version: 6.1.0

I've seen this question asked many times, but not answered.

After following these instructions to install angular-datables, and trying to use the directive on a table, as in their Zero Configuration example, I keep getting this error:

TypeError: $(...).DataTable is not a function

at angular-datatables.directive.js:42

Included Styles and Scripts

"styles": [
   "node_modules/bootstrap/dist/css/bootstrap.min.css",
   "node_modules/datatables.net-dt/css/jquery.dataTables.css",
   "src/styles.css"
],
"scripts": [
   "node_modules/jquery/dist/jquery.min.js",
   "node_modules/bootstrap/dist/js/bootstrap.min.js",
   "node_modules/datatables.net/js/jquery.dataTables.js"
]

Import in app.module.ts

import { DataTablesModule } from 'angular-datatables';

DataTablesModule is added to array of imports.

*.component.html

View Accounts

      #
      Account Name

      {{i+1}}
      {{account.accountHolder}}

Body:
I was missing '        "node_modules/datatables.net/js/jquery.dataTables.js",
'
in angular.json
It should look like

"scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/datatables.net/js/jquery.dataTables.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ]


问:
kubectl - determine local port used when port-forwarding on random local port?
kubectl lets one port forward to a remote service like so

```<code>$ kubectl port-forward service/my-service :12345
</code>```

How can I find out the local port that was chosen, and used by kubectl in this command?

Additional details: I'd like to be able to determine this from a script, that looks for an active port forward for a service. If a port forward isn't found, it creates a port forward on a free local port, and returns the port number (which is what the above does)

答:
I couldn't get any other approach to work, so I ended writing a script that dynamically finds a free port, and sets up a forward, then returns the port. If a matching port forward already exists, it can return that instead. Sample usage below. Note that currently I use another script to determine a free local port, and then use that port number to setup the port forward, and could've instead parsed the output from the generic port-forward command I mentioned in the question, but this approach is less fragile, and more re-usable, I believe.

```<code>$ kpf help

  kubernetes port forward helper
  * helps you transparently ensure a port forward is setup for a service.

  usage: kpf [require|get|create|remove|remove_all] {SERVICEI} {REMOTE_PORT} {EXTRA_ARGS}

  e.g.

  # get or create a port forward for your-service on remote port 8080
  # returns the port if successful, or fails and shows an error message
  kpf require service/your-service 8080

  # return any existing port forwards for your-service on remote port 8080, or nothing
  kpf get service/your-service 8080

  # create a new local port forward for your-service on remote port 8080, returning port used
  kpf create service/your-service 8080

  # remove any port forwards found to your-service on remote port 8080
  kpf remove service/your-service 8080

  # remove ALL port forwards to any kubernetes remote ports
  kpf remove_all
</code>```

kpf

```<code>#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; PATH="$DIR:$PATH"
ME=$(basename "$0")

function show_help()
{
  IT=$(cat <<EOF

  kubernetes port forward helper
  * helps you transparently ensure a port forward is setup for a service.

  usage: $ME [require|get|create|remove|remove_all] {SERVICE} {REMOTE_PORT} {EXTRA_ARGS}

  e.g.

  # get or create a port forward for your-service on remote port 8080
  # returns the port if successful, or fails and shows an error message
  $ME require service/your-service 8080

  # return any existing port forwards for your-service on remote port 8080, or nothing
  $ME get service/your-service 8080

  # create a new local port forward for your-service on remote port 8080, returning port used
  $ME create service/your-service 8080

  # remove any port forwards found to your-service on remote port 8080
  $ME remove service/your-service 8080

  # remove ALL port forwards to any kubernetes remote ports
  $ME remove_all

  # create a port forward on local port 4569, for localstack, in namespace localstack
  $ME create svc/localstack 4569:4569 --namespace localstack
EOF
)
  echo "$IT"
  echo
  exit
}

if [ -z "$1" ]
then
  show_help
fi
if [ "$1" = "help" ] || [ "$1" = '?' ] || [ "$1" = "--help" ] || [ "$1" = "h" ]; then
  show_help
fi

OP=$1
SERVICE=$2
REMOTE_PORT=$3
if [ -n "$4" ]
then
  shift;
  shift;
  shift;
  EXTRA_ARGS="$@"
fi

LOG_FILE_DIR="/tmp/__${ME}"

function getExistingPortForward(){
  listPortForwards | grep "$SERVICE" | grep -e ":$REMOTE_PORT" | head -n1
}

function coln(){
  COL=$1
  DELIM=${2:-' '}
  awk -F"$DELIM" -v col="$COL" '{print $col}' | sort | uniq
}

function err(){
  echo "$@" >&2;
}

function isNumeric(){
  INPUT=$*
  case ${INPUT#[-+]} in
    *[!0-9]* ) echo NO ;;
    * ) echo YES ;;
  esac
}

function getPid(){
  local INFO=$(getExistingPortForward | awk '{print $2}')

  if [ "$(isNumeric "$INFO")" == "YES" ]; then
    echo "$INFO"
  fi
}

function getLocalPort(){
  local INFO=$(getExistingPortForward)
  INFO=$(echo "$INFO" | awk -F ":$REMOTE_PORT" '{print $1}' | awk '{print $NF}')

  if [ "$(isNumeric "$INFO")" == "YES" ]; then
    echo "$INFO"
  fi
}

function removePortForward(){
  local PID=$(getPid)
  if [ -z "$PID" ]
  then
    return;
  fi

  set -x
  kill "$PID"
}

function portForward(){
  local LOCAL_PORT=$1
  local FILE=$2

  kubectl port-forward "$SERVICE" "$LOCAL_PORT":"$REMOTE_PORT" $EXTRA_ARGS > $FILE 2>&1 &
}

function failIfFileContains(){
  local FILE=$1
  local SUBSTR=$2
  local MSG=$3
  if grep -iq "$SUBSTR" "$FILE"; then
    cat "$FILE" >&2
    err "Failed: $MSG"
    err "Service:$SERVICE, $REMOTE_PORT $EXTRA_ARGS"
    err
    exit 1
  fi
}

function getTargetLocalPort(){
  local RESULT
  if [[ $REMOTE_PORT == *":"* ]]; then
    RESULT=$(echo $REMOTE_PORT | coln 1 ':')
    REMOTE_PORT=$(echo $REMOTE_PORT | coln 2 ':')
  else
    RESULT=$(port_find_free_local_port)
  fi
  echo "$RESULT"
}

function createPortForward(){
  local LOCAL_PORT=$(getTargetLocalPort)
  local LOG_FILE="${LOG_FILE_DIR}/${LOCAL_PORT}_log.txt"
  mkdir -p "$LOG_FILE_DIR"
  rm -f "$LOG_FILE"

  portForward "$LOCAL_PORT" "$LOG_FILE"

  # wait for the log file to indicate success or failure
  while true
  do
    sleep 0.5
    failIfFileContains "$LOG_FILE" "address already" "Port $LOCAL_PORT already in use"
    failIfFileContains "$LOG_FILE" "must be logged" "Please set some PCSK variables, and try again"
    failIfFileContains "$LOG_FILE" "Failed" "Please review the above log, and try again"
    failIfFileContains "$LOG_FILE" "Error" "Please review the above log, and try again"
    if grep -q Forwarding "$LOG_FILE"; then
      # port forward successful
      echo "$LOCAL_PORT"
      break
    fi
  done
}

function getOrCreatePortForward(){
  local PORT=$(getLocalPort)
  if [ -n "$PORT" ]
  then
    echo "$PORT"
    exit;
  fi

  createPortForward
}

function listPortForwards(){
  ps aux | grep kubectl | grep port-forward | sort
}

function removeAll(){
  listPortForwards | awk '{print $2}' | xargs kill -9
  rm -fr "$LOG_FILE_DIR"
}

function require3Args(){
  if [ -z "$REMOTE_PORT" ]
  then
    show_help
  fi
}

if [ "$OP" = "get" ]; then
  require3Args
  getLocalPort
elif [ "$OP" = "create" ]; then
  require3Args
  createPortForward
elif [ "$OP" = "require" ]; then
  require3Args
  getOrCreatePortForward
elif [ "$OP" = "remove" ]; then
  require3Args
  removePortForward
elif [ "$OP" = "list" ]; then
  listPortForwards
elif [ "$OP" = "remove_all" ]; then
  removeAll
else
  show_help
fi
</code>```

port_find_free_local_port

```<code>#!/usr/bin/env python
# https://stackoverflow.com/a/45690594/26510

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

print(find_free_port())
</code>```

Body:
kubectl lets one port forward to a remote service like so

$ kubectl port-forward service/my-service :12345

How can I find out the local port that was chosen, and used by kubectl in this command?

Additional details: I'd like to be able to determine this from a script, that looks for an active port forward for a service. If a port forward isn't found, it creates a port forward on a free local port, and returns the port number (which is what the above does)

Body:
I couldn't get any other approach to work, so I ended writing a script that dynamically finds a free port, and sets up a forward, then returns the port. If a matching port forward already exists, it can return that instead. Sample usage below. Note that currently I use another script to determine a free local port, and then use that port number to setup the port forward, and could've instead parsed the output from the generic port-forward command I mentioned in the question, but this approach is less fragile, and more re-usable, I believe.

$ kpf help

  kubernetes port forward helper
  * helps you transparently ensure a port forward is setup for a service.

  usage: kpf [require|get|create|remove|remove_all] {SERVICEI} {REMOTE_PORT} {EXTRA_ARGS}

  e.g.

  # get or create a port forward for your-service on remote port 8080
  # returns the port if successful, or fails and shows an error message
  kpf require service/your-service 8080

  # return any existing port forwards for your-service on remote port 8080, or nothing
  kpf get service/your-service 8080

  # create a new local port forward for your-service on remote port 8080, returning port used
  kpf create service/your-service 8080

  # remove any port forwards found to your-service on remote port 8080
  kpf remove service/your-service 8080

  # remove ALL port forwards to any kubernetes remote ports
  kpf remove_all

kpf

#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; PATH="$DIR:$PATH"
ME=$(basename "$0")

function show_help()
{
  IT=$(cat <<EOF

  kubernetes port forward helper
  * helps you transparently ensure a port forward is setup for a service.

  usage: $ME [require|get|create|remove|remove_all] {SERVICE} {REMOTE_PORT} {EXTRA_ARGS}

  e.g.

  # get or create a port forward for your-service on remote port 8080
  # returns the port if successful, or fails and shows an error message
  $ME require service/your-service 8080

  # return any existing port forwards for your-service on remote port 8080, or nothing
  $ME get service/your-service 8080

  # create a new local port forward for your-service on remote port 8080, returning port used
  $ME create service/your-service 8080

  # remove any port forwards found to your-service on remote port 8080
  $ME remove service/your-service 8080

  # remove ALL port forwards to any kubernetes remote ports
  $ME remove_all

  # create a port forward on local port 4569, for localstack, in namespace localstack
  $ME create svc/localstack 4569:4569 --namespace localstack
EOF
)
  echo "$IT"
  echo
  exit
}

if [ -z "$1" ]
then
  show_help
fi
if [ "$1" = "help" ] || [ "$1" = '?' ] || [ "$1" = "--help" ] || [ "$1" = "h" ]; then
  show_help
fi

OP=$1
SERVICE=$2
REMOTE_PORT=$3
if [ -n "$4" ]
then
  shift;
  shift;
  shift;
  EXTRA_ARGS="$@"
fi

LOG_FILE_DIR="/tmp/__${ME}"

function getExistingPortForward(){
  listPortForwards | grep "$SERVICE" | grep -e ":$REMOTE_PORT" | head -n1
}

function coln(){
  COL=$1
  DELIM=${2:-' '}
  awk -F"$DELIM" -v col="$COL" '{print $col}' | sort | uniq
}

function err(){
  echo "$@" >&2;
}

function isNumeric(){
  INPUT=$*
  case ${INPUT#[-+]} in
    *[!0-9]* ) echo NO ;;
    * ) echo YES ;;
  esac
}

function getPid(){
  local INFO=$(getExistingPortForward | awk '{print $2}')

  if [ "$(isNumeric "$INFO")" == "YES" ]; then
    echo "$INFO"
  fi
}

function getLocalPort(){
  local INFO=$(getExistingPortForward)
  INFO=$(echo "$INFO" | awk -F ":$REMOTE_PORT" '{print $1}' | awk '{print $NF}')

  if [ "$(isNumeric "$INFO")" == "YES" ]; then
    echo "$INFO"
  fi
}

function removePortForward(){
  local PID=$(getPid)
  if [ -z "$PID" ]
  then
    return;
  fi

  set -x
  kill "$PID"
}

function portForward(){
  local LOCAL_PORT=$1
  local FILE=$2

  kubectl port-forward "$SERVICE" "$LOCAL_PORT":"$REMOTE_PORT" $EXTRA_ARGS > $FILE 2>&1 &
}

function failIfFileContains(){
  local FILE=$1
  local SUBSTR=$2
  local MSG=$3
  if grep -iq "$SUBSTR" "$FILE"; then
    cat "$FILE" >&2
    err "Failed: $MSG"
    err "Service:$SERVICE, $REMOTE_PORT $EXTRA_ARGS"
    err
    exit 1
  fi
}

function getTargetLocalPort(){
  local RESULT
  if [[ $REMOTE_PORT == *":"* ]]; then
    RESULT=$(echo $REMOTE_PORT | coln 1 ':')
    REMOTE_PORT=$(echo $REMOTE_PORT | coln 2 ':')
  else
    RESULT=$(port_find_free_local_port)
  fi
  echo "$RESULT"
}

function createPortForward(){
  local LOCAL_PORT=$(getTargetLocalPort)
  local LOG_FILE="${LOG_FILE_DIR}/${LOCAL_PORT}_log.txt"
  mkdir -p "$LOG_FILE_DIR"
  rm -f "$LOG_FILE"

  portForward "$LOCAL_PORT" "$LOG_FILE"

  # wait for the log file to indicate success or failure
  while true
  do
    sleep 0.5
    failIfFileContains "$LOG_FILE" "address already" "Port $LOCAL_PORT already in use"
    failIfFileContains "$LOG_FILE" "must be logged" "Please set some PCSK variables, and try again"
    failIfFileContains "$LOG_FILE" "Failed" "Please review the above log, and try again"
    failIfFileContains "$LOG_FILE" "Error" "Please review the above log, and try again"
    if grep -q Forwarding "$LOG_FILE"; then
      # port forward successful
      echo "$LOCAL_PORT"
      break
    fi
  done
}

function getOrCreatePortForward(){
  local PORT=$(getLocalPort)
  if [ -n "$PORT" ]
  then
    echo "$PORT"
    exit;
  fi

  createPortForward
}

function listPortForwards(){
  ps aux | grep kubectl | grep port-forward | sort
}

function removeAll(){
  listPortForwards | awk '{print $2}' | xargs kill -9
  rm -fr "$LOG_FILE_DIR"
}

function require3Args(){
  if [ -z "$REMOTE_PORT" ]
  then
    show_help
  fi
}

if [ "$OP" = "get" ]; then
  require3Args
  getLocalPort
elif [ "$OP" = "create" ]; then
  require3Args
  createPortForward
elif [ "$OP" = "require" ]; then
  require3Args
  getOrCreatePortForward
elif [ "$OP" = "remove" ]; then
  require3Args
  removePortForward
elif [ "$OP" = "list" ]; then
  listPortForwards
elif [ "$OP" = "remove_all" ]; then
  removeAll
else
  show_help
fi

port_find_free_local_port

#!/usr/bin/env python
# https://stackoverflow.com/a/45690594/26510

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

print(find_free_port())


问:
Why can't I do any CABasicAnimation or Keyframe animation stuff?
For some reason Xcode tells me that it doesn't find symbols as soon as I use something like kCAFillModeForwards. There must be a library or class that I have to include...but which one? The normal Core Animation stuff works fine like [myView beginAnimations...]. What's the trick to get the more sophisticated animation stuff to work?

I've included in the .h file:

```<code>#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface TestClass : UIView {

}
// ...
</code>```

I run this code:

```<code>- (void)testAnimation {
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [fadeInAnimation setToValue:[NSNumber numberWithFloat:1.0]];
    fadeInAnimation.fillMode = kCAFillModeForwards;
    fadeInAnimation.removedOnCompletion = NO;
    // other stuff deleted to limit error possibilities...should at least compile
}
</code>```

This happens when I build (did clean up lots of times), 2 Errors:

```<code>    cd "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp"
    setenv MACOSX_DEPLOYMENT_TARGET 10.5
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.0 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator2.2.1.sdk "-L/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator" "-F/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator" -filelist "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/TestApp.build/Debug-iphonesimulator/TestApp.build/Objects-normal/i386/TestApp.LinkFileList" -mmacosx-version-min=10.5 -framework Foundation -framework UIKit -framework CoreGraphics -o "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator/TestApp.app/TestApp"
Undefined symbols:
  ".objc_class_name_CABasicAnimation", referenced from:
      literal-pointer@__OBJC@__cls_refs@CABasicAnimation in TestClassTestClass.o
  "_kCAFillModeForwards", referenced from:
      _kCAFillModeForwards$non_lazy_ptr in TestClass.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
      ".objc_class_name_CABasicAnimation", referenced from:
          literal-pointer@__OBJC@__cls_refs@CABasicAnimation in TestClass.o
      "_kCAFillModeForwards", referenced from:
          _kCAFillModeForwards$non_lazy_ptr in TestClass.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status
</code>```

It says Undefined symbols:

Must I include some framework?

I have already included:

CoreGraphics.framework
Foundation.framework
UIKit.framework

When I remove all the code, but import QuartzCore/QuartzCore.h, then I don't get any error. So I bet that import works, but not sure.

SOLVED

I missed to include the QuartzCore framework!!

答:
Probably you did not include the Quartz framework in your project.

To do so, choose your application target, go to the Build Phases tab and then under Link Binary With Libraries add the QuartzCore.framework.

ContentLicense: CC BY-SA 2.5

Body:
For some reason Xcode tells me that it doesn't find symbols as soon as I use something like kCAFillModeForwards. There must be a library or class that I have to include...but which one? The normal Core Animation stuff works fine like [myView beginAnimations...]. What's the trick to get the more sophisticated animation stuff to work?

I've included in the .h file:

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface TestClass : UIView {

}
// ...

I run this code:

- (void)testAnimation {
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [fadeInAnimation setToValue:[NSNumber numberWithFloat:1.0]];
    fadeInAnimation.fillMode = kCAFillModeForwards;
    fadeInAnimation.removedOnCompletion = NO;
    // other stuff deleted to limit error possibilities...should at least compile
}

This happens when I build (did clean up lots of times), 2 Errors:

    cd "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp"
    setenv MACOSX_DEPLOYMENT_TARGET 10.5
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.0 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator2.2.1.sdk "-L/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator" "-F/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator" -filelist "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/TestApp.build/Debug-iphonesimulator/TestApp.build/Objects-normal/i386/TestApp.LinkFileList" -mmacosx-version-min=10.5 -framework Foundation -framework UIKit -framework CoreGraphics -o "/Users/thanks/Desktop/Thanks/iPhone Development/TestApp/build/Debug-iphonesimulator/TestApp.app/TestApp"
Undefined symbols:
  ".objc_class_name_CABasicAnimation", referenced from:
      literal-pointer@__OBJC@__cls_refs@CABasicAnimation in TestClassTestClass.o
  "_kCAFillModeForwards", referenced from:
      _kCAFillModeForwards$non_lazy_ptr in TestClass.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
      ".objc_class_name_CABasicAnimation", referenced from:
          literal-pointer@__OBJC@__cls_refs@CABasicAnimation in TestClass.o
      "_kCAFillModeForwards", referenced from:
          _kCAFillModeForwards$non_lazy_ptr in TestClass.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

It says Undefined symbols:

Must I include some framework?

I have already included:

CoreGraphics.framework
Foundation.framework
UIKit.framework

When I remove all the code, but import QuartzCore/QuartzCore.h, then I don't get any error. So I bet that import works, but not sure.

SOLVED

I missed to include the QuartzCore framework!!


问:
Code to find cells that contain a constant preceded by = sign
Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.

I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:

```<code>Selection.SpecialCells(xlCellTypeConstants, 1).Select
</code>```

The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.

In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.

Any suggestions on how I can identify these cells?

答:
Assuming those inputs only contain number you could use a regex for that and ensure the value only contain "=" and numbers you'll have a code like this :

```<code>    Dim RegEx As Object, MyString As String
    Set RegEx = CreateObject("VBScript.RegExp")
    MyString = cell.formulas

    With RegEx
      .Pattern = "=*[0-9., ]+"
    End With

    RegEx.test(MyString) 'True if MyString is a number false if it's a function
</code>```

You'll need to activate "Microsoft VBScript Regular Expression" though.

Body:
Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.

I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:

Selection.SpecialCells(xlCellTypeConstants, 1).Select

The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.

In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.

Any suggestions on how I can identify these cells?

Body:
Assuming those inputs only contain number you could use a regex for that and ensure the value only contain "=" and numbers you'll have a code like this :

    Dim RegEx As Object, MyString As String
    Set RegEx = CreateObject("VBScript.RegExp")
    MyString = cell.formulas

    With RegEx
      .Pattern = "=*[0-9., ]+"
    End With

    RegEx.test(MyString) 'True if MyString is a number false if it's a function

You'll need to activate "Microsoft VBScript Regular Expression" though.


问:
Flutter/Dart how to check key in multidimensional json exists or not
I get response json like this from server :

```<code>{
  gender": {
    "label": "Wanita"
  }
}
</code>```

but sometime i get response like this :

```<code>{
  gender": []
}
</code>```

how to handle if key "label" in gender not exist?

答:
To check if a map contains a key you can use containsKey.
Small example:

```<code>final map = {
    'gender': {
      'label': 'Wanita',
    },
  };

print(map.containsKey('gender')); // true
print(map['gender']?.containsKey('label')); // true
print(map['gender']?.containsKey('age')); // false

</code>```

But somehow your server responses either a Map or a List. So for your case you have to check the type of the response with the is keyword.

```<code>final map = {
    'gender': {
      'label': 'Wanita',
    },
  };
print(map['gender'] is Map) // true
print(map['gender'] is List) // false

final map2 = {
    'gender': [],
  };
print(map2['gender'] is Map) // false
print(map2['gender'] is List) // true
</code>```

Body:
I get response json like this from server :

{
  gender": {
    "label": "Wanita"
  }
}

but sometime i get response like this :

{
  gender": []
}

how to handle if key "label" in gender not exist?

Body:
To check if a map contains a key you can use containsKey.
Small example:

final map = {
    'gender': {
      'label': 'Wanita',
    },
  };

print(map.containsKey('gender')); // true
print(map['gender']?.containsKey('label')); // true
print(map['gender']?.containsKey('age')); // false

But somehow your server responses either a Map or a List. So for your case you have to check the type of the response with the is keyword.

final map = {
    'gender': {
      'label': 'Wanita',
    },
  };
print(map['gender'] is Map) // true
print(map['gender'] is List) // false

final map2 = {
    'gender': [],
  };
print(map2['gender'] is Map) // false
print(map2['gender'] is List) // true