问:
Using Dot Leaders for a food menu with flex *follow-up
This is a follow-up from: Using dot leaders for a food menu with bootstrap grids

I'm creating a food menu using the grid column system with bootstrap 3, and I've created dot leaders between the menu item and the price. Thanks to user LGSon I'm using

```<code>display:flex;
</code>```

Which is doing the trick, however now the word margin seems to be cutting off the dot leaders differently depending on how many words there are. One word there is no cut off, after that there seems to be around 10px (These are approximated, and not exact). My goal is to make the dot leaders completely uniform and even. Here's what the image:

Here's my code. My apologies if it's too long, I tried to keep it brief. If anyone could help I would appreciate it.

```<code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class=" col-xs-6 ">
       <p class="item dots">Cheese</p>
       <p class="item dots">White</p>
       <p class="item dots">Special</p>
       <p class="item dots">Whole Wheat</p>
       <p class="item dots">Silician</p>
       <p class="item dots">Silician Special</p>
       <p class="item dots">Chicago Style</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$8.99</p>
       <p class="item">$9.99</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$11.99</p>
       <p class="item">$12.99</p>
       <p class="item">$15.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$12.99</p>
       <p class="item">$13.99</p>
       <p class="item">$17.99</p>
       <p class="item">$13.99</p>
       <p class="item">$15.99</p>
       <p class="item">$20.00</p>
       <p class="item">$14.99</p>
     </div>
  </div>
</div>

<style>
.dots {
  display: flex;
}

.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}
</style>

<!-- Matches Height in between divs--><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.0/jquery.matchHeight-min.js">

$(function() {
   $('.item').matchHeight(false);

   //Make links '.active' in Handlebars
   var url = window.location.href;
      $('nav li').find('.active').removeClass('active');
      $('nav li a').filter(function(){
         return this.href == url;
    }).parent().addClass('active');
});
</script>
</code>```

答:
Simply add white-space: nowrap to the dots rule

$(function() {
   $('.item').matchHeight(false);

   //Make links '.active' in Handlebars
   var url = window.location.href;
      $('nav li').find('.active').removeClass('active');
      $('nav li a').filter(function(){
         return this.href == url;
    }).parent().addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dots {
  display: flex;
  white-space: nowrap;
}

.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Cheese

White

Special

Whole Wheat

Silician

Silician Special

Chicago Style

$8.99

$9.99

$13.50

$13.50

$13.50

$13.50

$13.50

$11.99

$12.99

$15.99

$12.99

$12.99

$12.99

$12.99

$12.99

$13.99

$17.99

$13.99

$15.99

$20.00

$14.99

```

Body:
This is a follow-up from: Using dot leaders for a food menu with bootstrap grids

I'm creating a food menu using the grid column system with bootstrap 3, and I've created dot leaders between the menu item and the price. Thanks to user LGSon I'm using

display:flex;

Which is doing the trick, however now the word margin seems to be cutting off the dot leaders differently depending on how many words there are. One word there is no cut off, after that there seems to be around 10px (These are approximated, and not exact). My goal is to make the dot leaders completely uniform and even. Here's what the image:

Here's my code. My apologies if it's too long, I tried to keep it brief. If anyone could help I would appreciate it.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Cheese

White

Special

Whole Wheat

Silician

Silician Special

Chicago Style

$8.99

$9.99

$13.50

$13.50

$13.50

$13.50

$13.50

$11.99

$12.99

$15.99

$12.99

$12.99

$12.99

$12.99

$12.99

$13.99

$17.99

$13.99

$15.99

$20.00

$14.99

Body:
Simply add white-space: nowrap to the dots rule

$(function() {
   $('.item').matchHeight(false);

   //Make links '.active' in Handlebars
   var url = window.location.href;
      $('nav li').find('.active').removeClass('active');
      $('nav li a').filter(function(){
         return this.href == url;
    }).parent().addClass('active');
});

.dots {
  display: flex;
  white-space: nowrap;
}

.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class=" col-xs-6 ">
       <p class="item dots">Cheese</p>
       <p class="item dots">White</p>
       <p class="item dots">Special</p>
       <p class="item dots">Whole Wheat</p>
       <p class="item dots">Silician</p>
       <p class="item dots">Silician Special</p>
       <p class="item dots">Chicago Style</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$8.99</p>
       <p class="item">$9.99</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
       <p class="item">$13.50</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$11.99</p>
       <p class="item">$12.99</p>
       <p class="item">$15.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
       <p class="item">$12.99</p>
     </div>
     <div class="col-xs-2">
       <p class="item">$12.99</p>
       <p class="item">$13.99</p>
       <p class="item">$17.99</p>
       <p class="item">$13.99</p>
       <p class="item">$15.99</p>
       <p class="item">$20.00</p>
       <p class="item">$14.99</p>
     </div>
  </div>
</div>

<!-- Matches Height in between divs--><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.0/jquery.matchHeight-min.js"></script>


来源: stackexchange

问:
.Net Core + Angular 2 : can't load module
I am trying to implement Angular 2 with help of gulp in .Net Core using visual Studio update 3
with npm version 4.4.4 and node version v6.10.0 and already installed Typescript tool. All are

here is my Github link

And quick description of code

1.gulpfile.js

```<code>    /// <binding BeforeBuild='libs' Clean='clean' />

    var gulp = require('gulp');
    var rimraf = require('rimraf')
    var paths = {
        npm: './node_modules/',
        lib: './wwwroot/lib/'
    };
    var libs = [
       paths.npm + 'core-js/client/shim.min.js',
       paths.npm + 'zone.js/dist/zone.js',
       paths.npm + 'reflect-metadata/Reflect.js',
       paths.npm + 'systemjs/dist/system.src.js'
    ];
    gulp.task('libs', function () {
        return gulp.src(libs).pipe(gulp.dest(paths.lib));
    });
    gulp.task('clean', function (callback) {
        rimraf(paths.lib, callback);
    });
</code>```

2. package.json

```<code>{
    "version": "1.0.0",
    "name": "asp.net",
  "private": true,
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",

    "angular-in-memory-web-api": "~0.2.1",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "rimraf": "^2.6.1"
  }
}
</code>```

3. tsconfig.json

```<code>{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "outDir": "wwwroot/app/",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib",
    "wwwroot/app"
  ]
}
</code>```

4. typings.json

```<code>{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}
</code>```

And all other files from my last question

project build successfully but got error while executing like below

Please help me, What exactly I am missing?

答:
first thing use of systemjs.config,js file is missing so add it and as per    systemjs.config.js file change in gulpfile for required angular dependent files so here is a change

gulpfile.js
    /////

```<code>//var gulp = require('gulp');
//var rimraf = require('rimraf')
//var paths = {
//    npm: './node_modules/',
//    lib: './wwwroot/lib/'
//};
//var libs = [
//   paths.npm + 'core-js/client/shim.min.js',
//   paths.npm + 'zone.js/dist/zone.js',
//   paths.npm + 'reflect-metadata/Reflect.js',
//   paths.npm + 'systemjs/dist/system.src.js'
//];
//gulp.task('libs', function () {
//    return gulp.src(libs).pipe(gulp.dest(paths.lib));
//});
//gulp.task('clean', function (callback) {
//    rimraf(paths.lib, callback);
//});

var gulp = require('gulp');

var libs = './wwwroot/libs/';

gulp.task('default', function () {
    // place code for your default task here
});

gulp.task('restore:core-js', function () {
    gulp.src([
        'node_modules/core-js/client/*.js'
    ]).pipe(gulp.dest(libs + 'core-js'));
});
gulp.task('restore:zone.js', function () {
    gulp.src([
        'node_modules/zone.js/dist/*.js'
    ]).pipe(gulp.dest(libs + 'zone.js'));
});
gulp.task('restore:reflect-metadata', function () {
    gulp.src([
        'node_modules/reflect-metadata/reflect.js'
    ]).pipe(gulp.dest(libs + 'reflect-metadata'));
});
gulp.task('restore:systemjs', function () {
    gulp.src([
        'node_modules/systemjs/dist/*.js'
    ]).pipe(gulp.dest(libs + 'systemjs'));
});
gulp.task('restore:rxjs', function () {
    gulp.src([
        'node_modules/rxjs/**/*.js'
    ]).pipe(gulp.dest(libs + 'rxjs'));
});
gulp.task('restore:angular-in-memory-web-api', function () {
    gulp.src([
        'node_modules/angular-in-memory-web-api/**/*.js'
    ]).pipe(gulp.dest(libs + 'angular-in-memory-web-api'));
});

gulp.task('restore:angular', function () {
    gulp.src([
        'node_modules/@angular/**/*.js'
    ]).pipe(gulp.dest(libs + '@angular'));
});

gulp.task('restore:bootstrap', function () {
    gulp.src([
        'node_modules/bootstrap/dist/**/*.*'
    ]).pipe(gulp.dest(libs + 'bootstrap'));
});

gulp.task('restore', [
    'restore:core-js',
    'restore:zone.js',
    'restore:reflect-metadata',
    'restore:systemjs',
    'restore:rxjs',
    'restore:angular-in-memory-web-api',
    'restore:angular',
    'restore:bootstrap'
]);
</code>```

index.html file under wwwroot folder

```<code><html>
<head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="libs/core-js/shim.min.js"></script>
    <script src="libs/zone.js/zone.js"></script>
    <script src="libs/reflect-metadata/Reflect.js"></script>
    <script src="libs/systemjs/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function (err) { console.error(err); });
    </script>
</head>
<!-- 3. Display the application -->
<body>
    <my-app>Loading...</my-app>
</body>
</html>
</code>```

and most important 3.systemjs.config.js file

```<code>    /**
     * System configuration for Angular samples
     * Adjust as necessary for your application needs.
     */
    (function (global) {
        System.config({
            paths: {
                // paths serve as alias
                'npm:': 'libs/'
            },
            // map tells the System loader where to look for things
            map: {
                // our app is within the app folder
                app: 'app',
                // angular bundles
                '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
                '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
                '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
                '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
                '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
                '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
                '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
                '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
                // other libraries
                'rxjs': 'npm:rxjs',
                'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            },
            // packages tells the System loader how to load when no filename and/or no extension
            packages: {
                app: {
                    main: './main.js',
                    defaultExtension: 'js'
                },
                rxjs: {
                    defaultExtension: 'js'
                },
                'angular-in-memory-web-api': {
                    main: './index.js',
                    defaultExtension: 'js'
                }
            }
        });
    })(this);
</code>```

updated code at Github

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement Angular 2 with help of gulp in .Net Core using visual Studio update 3
with npm version 4.4.4 and node version v6.10.0 and already installed Typescript tool. All are

here is my Github link

And quick description of code

1.gulpfile.js

    /// <binding BeforeBuild='libs' Clean='clean' />

    var gulp = require('gulp');
    var rimraf = require('rimraf')
    var paths = {
        npm: './node_modules/',
        lib: './wwwroot/lib/'
    };
    var libs = [
       paths.npm + 'core-js/client/shim.min.js',
       paths.npm + 'zone.js/dist/zone.js',
       paths.npm + 'reflect-metadata/Reflect.js',
       paths.npm + 'systemjs/dist/system.src.js'
    ];
    gulp.task('libs', function () {
        return gulp.src(libs).pipe(gulp.dest(paths.lib));
    });
    gulp.task('clean', function (callback) {
        rimraf(paths.lib, callback);
    });

2. package.json

{
    "version": "1.0.0",
    "name": "asp.net",
  "private": true,
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",

    "angular-in-memory-web-api": "~0.2.1",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "rimraf": "^2.6.1"
  }
}

3. tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "outDir": "wwwroot/app/",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib",
    "wwwroot/app"
  ]
}

4. typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

And all other files from my last question

project build successfully but got error while executing like below

Please help me, What exactly I am missing?

Body:
first thing use of systemjs.config,js file is missing so add it and as per    systemjs.config.js file change in gulpfile for required angular dependent files so here is a change

gulpfile.js
    /////

//var gulp = require('gulp');
//var rimraf = require('rimraf')
//var paths = {
//    npm: './node_modules/',
//    lib: './wwwroot/lib/'
//};
//var libs = [
//   paths.npm + 'core-js/client/shim.min.js',
//   paths.npm + 'zone.js/dist/zone.js',
//   paths.npm + 'reflect-metadata/Reflect.js',
//   paths.npm + 'systemjs/dist/system.src.js'
//];
//gulp.task('libs', function () {
//    return gulp.src(libs).pipe(gulp.dest(paths.lib));
//});
//gulp.task('clean', function (callback) {
//    rimraf(paths.lib, callback);
//});

var gulp = require('gulp');

var libs = './wwwroot/libs/';

gulp.task('default', function () {
    // place code for your default task here
});

gulp.task('restore:core-js', function () {
    gulp.src([
        'node_modules/core-js/client/*.js'
    ]).pipe(gulp.dest(libs + 'core-js'));
});
gulp.task('restore:zone.js', function () {
    gulp.src([
        'node_modules/zone.js/dist/*.js'
    ]).pipe(gulp.dest(libs + 'zone.js'));
});
gulp.task('restore:reflect-metadata', function () {
    gulp.src([
        'node_modules/reflect-metadata/reflect.js'
    ]).pipe(gulp.dest(libs + 'reflect-metadata'));
});
gulp.task('restore:systemjs', function () {
    gulp.src([
        'node_modules/systemjs/dist/*.js'
    ]).pipe(gulp.dest(libs + 'systemjs'));
});
gulp.task('restore:rxjs', function () {
    gulp.src([
        'node_modules/rxjs/**/*.js'
    ]).pipe(gulp.dest(libs + 'rxjs'));
});
gulp.task('restore:angular-in-memory-web-api', function () {
    gulp.src([
        'node_modules/angular-in-memory-web-api/**/*.js'
    ]).pipe(gulp.dest(libs + 'angular-in-memory-web-api'));
});

gulp.task('restore:angular', function () {
    gulp.src([
        'node_modules/@angular/**/*.js'
    ]).pipe(gulp.dest(libs + '@angular'));
});

gulp.task('restore:bootstrap', function () {
    gulp.src([
        'node_modules/bootstrap/dist/**/*.*'
    ]).pipe(gulp.dest(libs + 'bootstrap'));
});

gulp.task('restore', [
    'restore:core-js',
    'restore:zone.js',
    'restore:reflect-metadata',
    'restore:systemjs',
    'restore:rxjs',
    'restore:angular-in-memory-web-api',
    'restore:angular',
    'restore:bootstrap'
]);

index.html file under wwwroot folder

<html>
<head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="libs/core-js/shim.min.js"></script>
    <script src="libs/zone.js/zone.js"></script>
    <script src="libs/reflect-metadata/Reflect.js"></script>
    <script src="libs/systemjs/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function (err) { console.error(err); });
    </script>
</head>
<!-- 3. Display the application -->
<body>
    <my-app>Loading...</my-app>
</body>
</html>

and most important 3.systemjs.config.js file

    /**
     * System configuration for Angular samples
     * Adjust as necessary for your application needs.
     */
    (function (global) {
        System.config({
            paths: {
                // paths serve as alias
                'npm:': 'libs/'
            },
            // map tells the System loader where to look for things
            map: {
                // our app is within the app folder
                app: 'app',
                // angular bundles
                '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
                '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
                '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
                '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
                '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
                '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
                '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
                '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
                // other libraries
                'rxjs': 'npm:rxjs',
                'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            },
            // packages tells the System loader how to load when no filename and/or no extension
            packages: {
                app: {
                    main: './main.js',
                    defaultExtension: 'js'
                },
                rxjs: {
                    defaultExtension: 'js'
                },
                'angular-in-memory-web-api': {
                    main: './index.js',
                    defaultExtension: 'js'
                }
            }
        });
    })(this);

updated code at Github


问:
Why is my page not being cached?
This is just making me angry. I can't figure out why all the resources in my page are being requested EVERY single time.

E.g. my site.css returns the following headers (using fiddler):

```<code>HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Mon, 29 Nov 2010 17:36:21 GMT
X-AspNet-Version: 2.0.50727
Content-Length: 9093
Cache-Control: public, max-age=2592000
Expires: Wed, 29 Dec 2010 17:36:21 GMT
Last-Modified: Mon, 08 Nov 2010 17:20:16 GMT
Content-Type: text/css
Connection: Close
</code>```

But every time I hit refresh I see all the resources (css,js,images) getting re-requested. I have control over the headers returned for any and all of these resources, but I haven't figured it out yet.

I have even debugged my ASP.NET app and the HttpModule is definitely being asked for the resources again.

Can someone give me an idea of what to do?

EDIT:
Ok, I removed must-revalidate, proxy-revalidate from the headers and that is getting me closer to where I want to be, now when I press back it still requests my css/js files when I press back.

Is there anything more I can do to avoid this?

答:
If you are handling the requests in your own module - which seems to be the case - and the request contains an If-Modified-Since header, you can use that to determine whether to respond with a 200 and sending the whole resource again, or just send a 304 and skip sending the js/css/etc contents.

Other than that, expect browsers to re-query resources on hitting F5 / Refresh. It is just that you may skip sending the whole js/css/etc and return a 304 if everything is OK.
Other than that,  @Chris's answer covers pretty much everything else.

What are the request headers you see when you hit back?

ContentLicense: CC BY-SA 2.5

Title: Why is my page not being cached?

Body:
This is just making me angry. I can't figure out why all the resources in my page are being requested EVERY single time.

E.g. my site.css returns the following headers (using fiddler):

HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Mon, 29 Nov 2010 17:36:21 GMT
X-AspNet-Version: 2.0.50727
Content-Length: 9093
Cache-Control: public, max-age=2592000
Expires: Wed, 29 Dec 2010 17:36:21 GMT
Last-Modified: Mon, 08 Nov 2010 17:20:16 GMT
Content-Type: text/css
Connection: Close

But every time I hit refresh I see all the resources (css,js,images) getting re-requested. I have control over the headers returned for any and all of these resources, but I haven't figured it out yet.

I have even debugged my ASP.NET app and the HttpModule is definitely being asked for the resources again.

Can someone give me an idea of what to do?

EDIT:
Ok, I removed must-revalidate, proxy-revalidate from the headers and that is getting me closer to where I want to be, now when I press back it still requests my css/js files when I press back.

Is there anything more I can do to avoid this?


问:
Local Notification is not displayed in iOS 10
i have tried this Code in Appdelegates.

```<code>@import UserNotifications;

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
            NSLog(@"request authorization succeeded!");

                center.delegate = self;
            }
    }];
</code>```

And the local notification is fired by this code

```<code>-(void)localNotification{

NSLog(@"local notification fired");

UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];

objNotificationContent.title = @"local notificatin";

objNotificationContent.body = @"message";

objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                              triggerWithTimeInterval:0.3 repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"three"
                                                                      content:objNotificationContent trigger:trigger];

/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];
</code>```

}

But Local notification is not displayed. As  i have used two Delegates method one is for present notification in foreground and one method that Must be called when local notification received.

that Delegates methods does not called at any Scenario.

please find Silly Mistake where i m wrong

答:
You are unable to see the local notification because your application might be in foreground. Local Notification doesn't show up if you are in foreground.

Your code is okay, but I would suggest to make some changes & test your app again.

Increase trigger time to 10 seconds.  UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

Added following in applicationDidEnterBackground

[self localNotification];

Make the application to go background.

Wait for 10 seconds, your will get local notification.

Show Notification on Foreground

If you want to show notification when your application is in foreground then, implement

Conform UNUserNotificationCenterDelegate in AppDelegate.h

Add following code in AppDelegate.m

```<code>-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}```

Body:
i have tried this Code in Appdelegates.

@import UserNotifications;

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
            NSLog(@"request authorization succeeded!");

                center.delegate = self;
            }
    }];

And the local notification is fired by this code

-(void)localNotification{

NSLog(@"local notification fired");

UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];

objNotificationContent.title = @"local notificatin";

objNotificationContent.body = @"message";

objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                              triggerWithTimeInterval:0.3 repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"three"
                                                                      content:objNotificationContent trigger:trigger];

/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];

}

But Local notification is not displayed. As  i have used two Delegates method one is for present notification in foreground and one method that Must be called when local notification received.

that Delegates methods does not called at any Scenario.

please find Silly Mistake where i m wrong

Body:
You are unable to see the local notification because your application might be in foreground. Local Notification doesn't show up if you are in foreground.

Your code is okay, but I would suggest to make some changes & test your app again.

Increase trigger time to 10 seconds.  UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

Added following in applicationDidEnterBackground

[self localNotification];

Make the application to go background.

Wait for 10 seconds, your will get local notification.

Show Notification on Foreground

If you want to show notification when your application is in foreground then, implement

Conform UNUserNotificationCenterDelegate in AppDelegate.h

Add following code in AppDelegate.m

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}


问:
How to access route after certain controller call
I have two routes

```<code>Route::post('checkout','CartController@billingSave');
Route::get('success','CartController@billingSave');
</code>```

So after completing the billingSave method it will redirect to success page..
But if put /success also in url it shows the success page also..though he didn't complete the payment..is there anyway i could let access only the success url after completing the billingSave functionality?

means he can't access success url instead of completing the billingSave method ..or like don't give him access the success url?

答:
Change the following route:

```<code>Route::get('success','CartController@billingSave');
</code>```

to

```<code>Route::post('success','CartController@billingSave');
</code>```

so that user cannot access it directly by using the success route in browser, don't forget to show error page here. It can only be accessed by form post method. After data saved successfully submit the form to success route.

Body:
I have two routes

Route::post('checkout','CartController@billingSave');
Route::get('success','CartController@billingSave');

So after completing the billingSave method it will redirect to success page..
But if put /success also in url it shows the success page also..though he didn't complete the payment..is there anyway i could let access only the success url after completing the billingSave functionality?

means he can't access success url instead of completing the billingSave method ..or like don't give him access the success url?

Body:
Change the following route:

Route::get('success','CartController@billingSave');

to

Route::post('success','CartController@billingSave');

so that user cannot access it directly by using the success route in browser, don't forget to show error page here. It can only be accessed by form post method. After data saved successfully submit the form to success route.


问:
Undefined variable (Codeigniter)
I have this error in my view and cannot find out where is the problem:

MY Controller name 'Question':

```<code>public function show_all_question_set() {
$data = array();
$data['question_set'] = $this->Question_Model->select_all_question_set();
$this->load->view('question/make_set', $data);
}
</code>```

My Model name 'Question_Model':

```<code>public function select_all_question_set() {
$this->db->select('*');
$this->db->from('tbl_question_set');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
</code>```

My view name 'make_set':

```<code><?php
foreach ($question_set as $all_set) {
?>
<tr>
<td align="center">
<a href="#" class="btn btn-default"><em class="fa fa-pencil"></em></a>
<a href="#" class="btn btn-danger"><em class="fa fa-trash"></em></a>
</td>
<td> <?php echo $all_set->exam_name; ?>  </td>
<td> <?php echo $all_set->subject_name; ?> </td>
<td> <?php echo $all_set->set_name; ?> </td>
<td align="center">
<a href="#"class="btn btn-default"><em class="fa fa-book"> দেখুন </em></a>
</td>
</tr>
<?php } ?>
</code>```

Table : tbl_question_set(set_id, exam_name, subject_name, set_name)

答:
```<code>i think you are getting error because you write model name in capital letter.. please try this. paste this code in your model hopefully it will work..

public function show_all_question_set() {
$data = array();
$data['question_set'] = $this->question_model->select_all_question_set();
$this->load->view('question/make_set', $data);
}
</code>```

Title: Undefined variable (Codeigniter)

Body:
I have this error in my view and cannot find out where is the problem:

MY Controller name 'Question':

public function show_all_question_set() {
$data = array();
$data['question_set'] = $this->Question_Model->select_all_question_set();
$this->load->view('question/make_set', $data);
}

My Model name 'Question_Model':

public function select_all_question_set() {
$this->db->select('*');
$this->db->from('tbl_question_set');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}

My view name 'make_set':

<?php
foreach ($question_set as $all_set) {
?>

 <?php echo $all_set->exam_name; ?>
 <?php echo $all_set->subject_name; ?>
 <?php echo $all_set->set_name; ?>

 দেখুন

<?php } ?>

Table : tbl_question_set(set_id, exam_name, subject_name, set_name)


问:
Property 'X' is private and only accessible within class 'xyzComponent'
I'm trying to build angular2 application for production for that I'm following this blog. After my ngc successful compilation when the tsc compilation takes place it generates below error shown in the image:

After searching for a while I found this blog which explains the problem in "The context property" section which I'm not able to understood properly may be it give some good idea to you that what's happening wrong.
basically when we're making a variable private we're getting "ERROR: Property is private and only accessible within class".

答:
For a given component all its members (methods, properties) accessed by its template must be public in the AOT compilation scenario. This is due to the fact that a template is turned into a TS class. A generated class and a component are 2 separate classes now and you can't access private members cross-class.

In short: you can't access private members in your templates if you want to use ahead-of-time compilation.

For better explaination https://github.com/angular/angular/issues/11422

ContentLicense: CC BY-SA 4.0


问:
Missing Payment Plugin Extension In Opencart
I currently finished writing a payment plugin for opencart. I uploaded it using filezilla to an online opencart site, tested it and it worked perfectly.
After which i tried installing the same plugin using the extensions installer from admin, setup my ftp and i got a "installed successfully" message.

The problem is i can't find the extension under payment extensions in the opencart site. As in, it is completely missing but it definitely has to be somewhere since it installed successfully

NOTE

The previously installed plugin through filezilla cannot be possibly crashing with the new one because i removed that one completely.

I setup my FTP perfectly.

I zipped the upload folder, saved it with upload.ocmod.zip before uploading it.

How do i find the missing extension and if i'm installing it the wrong way, what is right way to go about the it.

答:
In OpenCart 2.3, all extensions are listed in the Extensions > Extensions area. You then have to choose which extensions you want to filter on (e.g. Shipping extensions).

Which Opencart version you are using?


问:
python to C# data table via xml
Is there a way to write an xml file from python that can be read by the C# DataTable.ReadXml method?

I have written some python code that gathers information, compiles, sorts, analyzes, etc. I have another program that I'm trying to get to read in the final output of my python code. The other program uses xml files to read in the data that I am creating using the DataTable.ReadXml method. I have tried writing an xml file from python but the formatting seems to be wrong. Anyone have any tips to get the xml format to comply with this C# method?

答:
try using etree and encode the xml string to UTF8, then write it to file, and use it in C#.
Something like this :

```<code>from lxml import etree
page = etree.Element('root')
doc = etree.ElementTree(page)
child1 = etree.SubElement(page, 'child1')
child2 = etree.SubElement(page, 'child2')
child1.text = 'I am child 1'
child2.text = 'I am child 1'
utf8String = etree.tostring(doc, encoding='utf8', method='xml')
print (utf8String ) #just for display
outFile = open('test.xml', 'wb')
outFile.write(utf8String)
</code>```

Hope this was useful

Title: python to C# data table via xml

Body:
try using etree and encode the xml string to UTF8, then write it to file, and use it in C#.
Something like this :

from lxml import etree
page = etree.Element('root')
doc = etree.ElementTree(page)
child1 = etree.SubElement(page, 'child1')
child2 = etree.SubElement(page, 'child2')
child1.text = 'I am child 1'
child2.text = 'I am child 1'
utf8String = etree.tostring(doc, encoding='utf8', method='xml')
print (utf8String ) #just for display
outFile = open('test.xml', 'wb')
outFile.write(utf8String)

Hope this was useful


问:
Change Class to Hover Class
I have a couple of nested divs and have set a CSS class for one of the interior divs. How would I go about setting off the hover version of the class (class.hover) when the user hovers of the outer div, but not necessarily over the interior div's area.

I'm assuming this has to be done via JavaScript. I need some inputs with this.

Thanks

答:
If I have understood your question correctly, you can do it with pure CSS:

CSS:

```
.outer:hover .inner
{
   // Your hover style here
}
```

HTML:

```
<div class="outer">
   <div class="inner">Button text</div>
</div>
```

Title: Change Class to Hover Class

Body:
If I have understood your question correctly, you can do it with pure CSS:

CSS:

.outer:hover .inner
{
   // Your hover style here
}

HTML:

<div class="outer">
   <div class="inner">Button text</div>
</div>


问:
How to display default parameters in the page URL in php?
I have created the php page named sample.php.I have used get method to get parameter values.

If no parameters passed from any pages get method uses default values.

```<code>if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
}
</code>```

Other pages in my project has the hyperlink to link to this page

.

I would like to display those default parameters in the URL even if no parameters passed from other pages.

```<code>http:\\localhost\myproj\sample.php?name="nithya"&id=1
</code>```

答:
```<code>if(!isset($_GET['name'])&&!isset($_GET['id'])){
    header('Location:http:\\localhost\myproj\sample.php?name="nithya"&id=1');
}
</code>```

Something like this,
and inside your if condition check you parameter like

```<code>if(!isset($_GET['name'].........&&....){

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

In your case:

```<code>if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
   header('Location:http:\\localhost\myproj\sample.php?name="'.$name.'"&id='.$id);
}
</code>```

You can not show these parameter directly on your URL, easiest way is to redirect the page having parameter. Another good way might be using htaccess

Body:
I have created the php page named sample.php.I have used get method to get parameter values.

If no parameters passed from any pages get method uses default values.

if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
}

Other pages in my project has the hyperlink to link to this page

.

I would like to display those default parameters in the URL even if no parameters passed from other pages.

http:\\localhost\myproj\sample.php?name="nithya"&id=1

Body:
if(!isset($_GET['name'])&&!isset($_GET['id'])){
    header('Location:http:\\localhost\myproj\sample.php?name="nithya"&id=1');
}

Something like this,
and inside your if condition check you parameter like

if(!isset($_GET['name'].........&&....){

header....
}

In your case:

if($_SERVER['REQUEST_METHOD'] == 'GET'){
   $name = isset($_GET("name"))?$_GET("name"):"nithya";
   $id = isset($_GET("id"))?$_GET("id"):1;
   header('Location:http:\\localhost\myproj\sample.php?name="'.$name.'"&id='.$id);
}

You can not show these parameter directly on your URL, easiest way is to redirect the page having parameter. Another good way might be using htaccess


问:
How can I optimize this jquery script? Different classes and same function
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

```<code> $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });
</code>```

答:
You can select several elements at once by separating their class selections with a comma.

```<code>$('.sub-cat, .prod-type, .prod-finnish, .prod-color, .prod-included, .prod-series').change(function() {
     var $this = $(this); // cache this so we don't have to wrap it twice
     $this.toggle($this.find('option:selected').text() == "Other"));
});
</code>```

It's then just a matter of using .toggle() and passing in a boolean; In our case whether the selected option has "Other" as its text.

This has a really good performance advantage since you only need one event delegate to handle the change event for all the elements in the selector.

Body:
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

 $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });

Body:
You can select several elements at once by separating their class selections with a comma.

$('.sub-cat, .prod-type, .prod-finnish, .prod-color, .prod-included, .prod-series').change(function() {
     var $this = $(this); // cache this so we don't have to wrap it twice
     $this.toggle($this.find('option:selected').text() == "Other"));
});

It's then just a matter of using .toggle() and passing in a boolean; In our case whether the selected option has "Other" as its text.

This has a really good performance advantage since you only need one event delegate to handle the change event for all the elements in the selector.


问:
Multi module Maven project with Spring - Do I include Spring in the Web layer or Service layer?
So I have a multi-module Maven project that simply has two child modules: Web, and Service. The Web layer has only one controller and one method in that controller that simply displays the age of a dog on the screen.

Where does the dog come from? Well I have another module that is a 'service' layer that basically contains a Dog store/service, and this dog store actually only contains one Dog object at any given time (this is all for learning purposes).

I need to use Spring's Dependency Injection functionality in my Service module in order to autowire a Dog object into my Dog store, and I obviously need Spring's D.I. functionality in my Web module, in order to autowire a Dog store/service into my Dog controller, but I don't know WHICH POM.xml should contain a Spring dependency.

My question is this: Do I need to put a Spring dependency in both the service module AND the web module? The end project is going to be built from the web module, in fact. The web module will have a dependency for the service module (because I need that Dog Service and Dog object classes).

If I don't include spring as a dependency in my Service-module, then the compiler will freak out when I use an annotation like @Autowire. So this leaves my a bit confused. Which module do I put the spring dependency in?

Perhaps just put the entire Spring Web MVC dependency in the Service module, and let the Web module 'inherit' all the custom service classes, PLUS the downloaded Spring jars? (Since, again, the web-module will have a dependency on the service module). This just seems a little counter-intuitive to me because it's not really the service-module that is dependent on Spring Web MVC. Really, the service module only needs Spring Context. But the confusion here is that the "FINAL" spring context (Dispatcher Servlet, etc) will only be used once, from the Web-module build.

I'm ONLY creating the service-module so that my web-module can inherit those classes I've built, but should the web-module inherit the spring classes from the service-module, or should the web-module actually declare the spring classes in it's own POM.xml? If it is the latter option, then won't the service-module freak out when it sees that I'm using annotations and other things from Spring framework, without having a dependency to it?

I realize that was a lot, but I was trying to be as clear as possible in my situation, and I hope that my question makes sense. Thanks for your answers!

答:
I would recommend adding a parent POM to your application and keep all dependencies defined there and make your web and service modules are child modules. See this for more details

In your parent POM, dependencies are defined something like this,

```<code><dependencyManagement>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.5.RELEASE</version>
  </dependency>
</dependencyManagement>
</code>```

Use above defined dependency in your web and service modules,

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
</code>```

Also, add service module as a dependency to your web module.

Body:
I would recommend adding a parent POM to your application and keep all dependencies defined there and make your web and service modules are child modules. See this for more details

In your parent POM, dependencies are defined something like this,

<dependencyManagement>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.5.RELEASE</version>
  </dependency>
</dependencyManagement>

Use above defined dependency in your web and service modules,

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

Also, add service module as a dependency to your web module.


问:
Cannot start rails server
I tried to rails server

= Could not find rake-12.0.0 in any of the sources
    Run bundle install to install missing gems.

I tried to bundle update/ install
It goes to the error msg below .

答:
Try following commands:</p>

```<code>gem update --system

bundle install
</code>```

Title: Cannot start rails server

Body:
Try following commands:

gem update --system

bundle install


问:
Vaadin GridLayout not updating correctly
I have a problem where Vaadin does not update the display of a GridLayout in time. The GridLayout is a component in a VerticalLayout, that I use to list all uploaded files. When I upload a file everything works fine on the server-side but the client does not see the change until he creates a new request to the server (by uploading another file or triggering some other event / rarely the update works fine though).

Here is the component that contains the problematic GridLayout:

```<code>public class ListedMultiFileUpload extends VerticalLayout {
    private MultiFileUpload multiFileUpload;
    private GridLayout fileList;

    public ListedMultiFileUpload(UploadFinishedHandler uploadFinishedHandler, UploadStateWindow uploadStateWindow) {
        multiFileUpload = new MultiFileUpload(uploadFinishedHandler, uploadStateWindow);
        fileList = new GridLayout(2, 5);
        fileList.setImmediate(true);

        addComponents(multiFileUpload, fileList);
    }

    public SmartMultiUpload getSmartUpload() {
        return multiFileUpload.getSmartUpload();
    }

    public void addFile(String fileName, final Runnable fileRemover) {
        final Label label = new Label(fileName);
        final Button button = new Button("X");
        button.addClickListener(new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                fileList.removeComponent(label);
                fileList.removeComponent(button);
                fileRemover.run();
            }
        });
        fileList.addComponent(label);
        fileList.addComponent(button);
        markAsDirtyRecursive();
    }
}
</code>```

I already tried setting the GridLayout to immediate as well as marking the whole component as dirty but nothing seems to make a difference.

So basically am I doing something wrong here? Or if not, is there a "nice" way I could force the client to update its components?

答: As proposed by @Morfic I enabled the Server-Push addon in automatic mode and now the required updates to the client are made by that addon. Not sure how much I like that solution but it works.</p>

Body:
I have a problem where Vaadin does not update the display of a GridLayout in time. The GridLayout is a component in a VerticalLayout, that I use to list all uploaded files. When I upload a file everything works fine on the server-side but the client does not see the change until he creates a new request to the server (by uploading another file or triggering some other event / rarely the update works fine though).

Here is the component that contains the problematic GridLayout:

public class ListedMultiFileUpload extends VerticalLayout {
    private MultiFileUpload multiFileUpload;
    private GridLayout fileList;

    public ListedMultiFileUpload(UploadFinishedHandler uploadFinishedHandler, UploadStateWindow uploadStateWindow) {
        multiFileUpload = new MultiFileUpload(uploadFinishedHandler, uploadStateWindow);
        fileList = new GridLayout(2, 5);
        fileList.setImmediate(true);

        addComponents(multiFileUpload, fileList);
    }

    public SmartMultiUpload getSmartUpload() {
        return multiFileUpload.getSmartUpload();
    }

    public void addFile(String fileName, final Runnable fileRemover) {
        final Label label = new Label(fileName);
        final Button button = new Button("X");
        button.addClickListener(new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                fileList.removeComponent(label);
                fileList.removeComponent(button);
                fileRemover.run();
            }
        });
        fileList.addComponent(label);
        fileList.addComponent(button);
        markAsDirtyRecursive();
    }
}

I already tried setting the GridLayout to immediate as well as marking the whole component as dirty but nothing seems to make a difference.

So basically am I doing something wrong here? Or if not, is there a "nice" way I could force the client to update its components?


问:
Read or open a file using "fuzzy match" filename - Python
Given a list of files in a directory:

```<code>import os
os.listdir('system-outputs/newstest2016/ru-en')
</code>```

[out]:

```<code>['newstest2016.AFRL-MITLL-contrast.4524.ru-en',
 'newstest2016.AFRL-MITLL-Phrase.4383.ru-en',
 'newstest2016.AMU-UEDIN.4458.ru-en',
 'newstest2016.NRC.4456.ru-en',
 'newstest2016.online-A.0.ru-en',
 'newstest2016.online-B.0.ru-en',
 'newstest2016.online-F.0.ru-en',
 'newstest2016.online-G.0.ru-en',
 'newstest2016.PROMT-Rule-based.4277.ru-en',
 'newstest2016.uedin-nmt.4309.ru-en']
</code>```

And then I have the input:

```<code>filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'
</code>```

Using the filename, if I want to do a regex match such that I can read the file newstest2016.AFRL-MITLL-contrast.4524.ru-en, I could do:

```<code>import re
fin = open(next(_fn for _fn in os.list('system-outputs/newstest2016/ru-en') if re.match(filename + '.*.' + suffix, _fn) for _fn in))
</code>```

But is there a way to read/open a "fuzzy match" filename? There must be a better way than the crude re.match way above.

It's okay to assume that there should always be one clear match from the os.listdir.

答: I believe glob might be a better way.</p>

Body:
Given a list of files in a directory:

import os
os.listdir('system-outputs/newstest2016/ru-en')

[out]:

['newstest2016.AFRL-MITLL-contrast.4524.ru-en',
 'newstest2016.AFRL-MITLL-Phrase.4383.ru-en',
 'newstest2016.AMU-UEDIN.4458.ru-en',
 'newstest2016.NRC.4456.ru-en',
 'newstest2016.online-A.0.ru-en',
 'newstest2016.online-B.0.ru-en',
 'newstest2016.online-F.0.ru-en',
 'newstest2016.online-G.0.ru-en',
 'newstest2016.PROMT-Rule-based.4277.ru-en',
 'newstest2016.uedin-nmt.4309.ru-en']

And then I have the input:

filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'

Using the filename, if I want to do a regex match such that I can read the file newstest2016.AFRL-MITLL-contrast.4524.ru-en, I could do:

import re
fin = open(next(_fn for _fn in os.list('system-outputs/newstest2016/ru-en') if re.match(filename + '.*.' + suffix, _fn) for _fn in))

But is there a way to read/open a "fuzzy match" filename? There must be a better way than the crude re.match way above.

It's okay to assume that there should always be one clear match from the os.listdir.

Body: I believe glob might be a better way.


问:
Windows Home Server backup solution
I admit this is not strictly a programming question, although I do use my WHS as a source repository server for home projects, and I'm guessing many other coders here do as well.

Does anyone have a recommendation for a good backup solution for the non-fileshare portion of Windows Home Server?  All the WHS backups I've seen handle the fileshares, but none of the system files or other administrative stuff on the box.

Thanks,
  Andy

答: Windows Home Server is designed to not need a backup of the OS. If your system drive fails, install a new drive, and then boot the WHS OS setup disc and install the OS. It will find the data on the other drives and recreate all the shared folders. You do need to do some configuring once it is back up but that is pretty small compared to not having to back it up. </p>

OwnerDisplayName: AndrewCr

Title: Windows Home Server backup solution

OwnerDisplayName: stevex


问:
In functional testing, should I compare all tabular data rendered in the browser with the one coming from the DB?
I'm working on a test plan for a website where some tests are taking the following path:

Hit the requested URI and get the data rendered inside some table(20 rows per page).

Make a database query to get the data that is supposed to be rendered in that table.

Compare the 2 data row by row, they should match.

Is that a correct way of doing functional testing? If that request was an Ajax request, what will be the answer also? Would the answer differ for integration testing?

I have some reason that makes me believe that this is wrong somehow.... still need your opinions guys!

答:
This kind of test could be good for testing a large set of data with relatively little tester effort if there is not much developer logic between the database and the display to the end user.  Our team has done this on a number of occasions, and it is especially useful for running large quantities of real production data through our tests to be sure that actual scenarios are handled as expected.  Do make sure you do at least a little fixed input testing for rare scenarios that might be especially likely to be handled differently in the DB and on the web page - null values, special characters, and other oddities.

Personally, I would call this "integration testing", since you are testing the integration of the DB and the web site, and not "functional testing". For "functional testing", I'd probably want to make a mock of the datasource (e.g., the database) that will provide pre-written sets of data in the format you expect.

Having said that, if I had high confidence in the validity of the DB data and if the logic between the DB query and the web page display was very small and low-risk, I would probably not bother with the mock and would let the integration test cover the functionality as well.  I don't know that testing the functionality and integration separately would be a big quality win in this case, and there are likely better things you could do with the available testing time.  If there is a lot of logic around this data, you should probably test the integration separately from the functionality.  Additional integration testing would probably include things like, "What if the database can't be reached?" and "What if the database is slow?".

While this technique will work with Ajax, make sure your testing tools will work with Ajax.  Specifically, think about how you will capture the database query results and how you will gather the results displayed on the web page.

I'm assuming that the validity of the data in the query is being tested elsewhere, since you mentioned that this was just one type of test in the test plan.  I'm also just discussing integration with the database and this report and not other features or components, and not other aspects of testing (performance, security. etc.), since that was the scope of your question.


答:
You can utilize data-attributes to help you out. I didnt test out this code, but I think something like this could possibly work. Update your HTML to be something like this

```<code><select data-target="sub-cat"></select>
<div class="other-category" data-target="sub-cat"></div>
</code>```

Followed by this abbreviated jquery code...

```<code>$(document).ready(function () {
    $('select').change(function() {
        var target = $(this).data('target'),
            isSelected = $(that).find('option:selected').text() == "Other";
        $(this).find('.other-category[data-target="'+target+'"]').toggleClass(isSelected);
    })
});
</code>```

By storing the attributes in a data-attribute, you can easily access that in your javascript code, targeting specific elements much more easily.

Title: How can I optimize this jquery script? Different classes and same function

Body:
You can utilize data-attributes to help you out. I didnt test out this code, but I think something like this could possibly work. Update your HTML to be something like this

<select data-target="sub-cat"></select>
<div class="other-category" data-target="sub-cat"></div>

Followed by this abbreviated jquery code...

$(document).ready(function () {
    $('select').change(function() {
        var target = $(this).data('target'),
            isSelected = $(that).find('option:selected').text() == "Other";
        $(this).find('.other-category[data-target="'+target+'"]').toggleClass(isSelected);
    })
});

By storing the attributes in a data-attribute, you can easily access that in your javascript code, targeting specific elements much more easily.


问:
Gmail Add-ons Developer Preview Invitation
We develop Gmail Extensions and recently saw and applied to be included in the proposed Gmail Add-ons Developer Preview...

We have not had a Response from Google.

Has anybody been accepted into the Preview?

All I can find on the web is the following

https://gsuite-developers.googleblog.com/2017/03/bring-power-of-your-apps-into-gmail_9.html

Thanks for your feedback
Paul C

答:
There is still no definite date as to when the Invitations will be sent out. If you have filled out the form, next thing to do is to simply wait for the announcement/email.

As also stated in the form:

Please be advised that space in this program is limited. Applications will be reviewed on a one-on-one basis.

It's either still being reviewed or is already processed and just waiting for the invites. I suggest following G Suite Developers Twitter account (seen in the page) to be aware of any updates. I think if they would announce something like that if it comes live. Cheers!


问:
Type mismatch of same type
I'm currently trying to start on a project for one of my CS courses, and I didn't even get five minutes in before I was hit with a rather perplexing error. My code is as follows:

```<code>import java.util.Comparator;
import java.util.List;

public class MergeSorter<T extends Comparable<T>> implements IMergeSorter
{
    private List<T> arrayStore;
    private List<T> temp;
    private int arrSize;

    @Override
    public <T extends Comparable<T>> int sort(List<T> list)
    {
        arrayStore = list;
        return 0;
    }
</code>```

The issue i'm having is with the first line in the sort method,

```<code>arrayStore = list;
</code>```

with Eclipse giving me the following error:

```<code>Type mismatch: cannot convert from List<T extends Comparable<T>> to List<T extends Comparable<T>>
</code>```

Notes:
The method itself was provided to me by my professor, and the only things I have done with this class are add the three variables at the top, change the class' generic type (it was originally (T), which I changed to (T extends Comparable(T)), and add the one line in the "sort" method. Any help is greatly appreciated!

答:
From your code I think simply remove <T extends Comparable<T>> from your method is not enough because it is a override method but there's no type declaration in your interface IMergeSorter.

I don't know your IMergeSorter declaration but it could be:

```<code>public interface IMergeSorter<T extends Comparable<T>> {
 int sort(List<T> list);
}
</code>```

And then your MergeSorter should be:

```<code>import java.util.Comparator;
import java.util.List;

public class MergeSorter<T extends Comparable<T>> implements IMergeSorter<T> {
    private List<T> arrayStore;
    private List<T> temp;
    private int arrSize;

    @Override
    public int sort(List<T> list) {
        this.arrayStore = list;
        return 0;
    }
}
</code>```

Title: Type mismatch of same type

Body:
I'm currently trying to start on a project for one of my CS courses, and I didn't even get five minutes in before I was hit with a rather perplexing error. My code is as follows:

import java.util.Comparator;
import java.util.List;

public class MergeSorter<T extends Comparable<T>> implements IMergeSorter
{
    private List<T> arrayStore;
    private List<T> temp;
    private int arrSize;

    @Override
    public <T extends Comparable<T>> int sort(List<T> list)
    {
        arrayStore = list;
        return 0;
    }

The issue i'm having is with the first line in the sort method,

arrayStore = list;

with Eclipse giving me the following error:

Type mismatch: cannot convert from List<T extends Comparable<T>> to List<T extends Comparable<T>>

Notes:
The method itself was provided to me by my professor, and the only things I have done with this class are add the three variables at the top, change the class' generic type (it was originally (T), which I changed to (T extends Comparable(T)), and add the one line in the "sort" method. Any help is greatly appreciated!

Body:
From your code I think simply remove <T extends Comparable<T>> from your method is not enough because it is a override method but there's no type declaration in your interface IMergeSorter.

I don't know your IMergeSorter declaration but it could be:

public interface IMergeSorter<T extends Comparable<T>> {
 int sort(List<T> list);
}

And then your MergeSorter should be:

import java.util.Comparator;
import java.util.List;

public class MergeSorter<T extends Comparable<T>> implements IMergeSorter<T> {
    private List<T> arrayStore;
    private List<T> temp;
    private int arrSize;

    @Override
    public int sort(List<T> list) {
        this.arrayStore = list;
        return 0;
    }
}


问:
How to retrieve ClaimsPrincipal from JWT in asp.net core
In my solution, I have two projects. 1) Web API and 2) MVC. I am using ASP.NET Core. API issues JWT token and MVC consumes it to get protected resources. I am using openiddict library to issue JWT. In MVC project, in AccountController Login method, I want to retrieve ClaimsPrincipal (using JwtSecurityTokenHandler ValidateToken method) and assign to HttpContext.User.Claims and HttpContext.User.Identity. I want to store the token in session and for each request after successful login, pass it in header to Web API. I can successfully, issue JWT and consume it in MVC project, but when I try to retrieve ClaimsPrincipal it throws me an error. First of all, I am not even sure whether this retrieving of ClaimsPrinciapal from JWT is a right approach or not. And if it is, what is the way forward.

WebAPI.Startup.CS

```<code>public class Startup
{
    public static string SecretKey => "MySecretKey";
    public static SymmetricSecurityKey SigningKey => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IContainer ApplicationContainer { get; private set; }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddCors();
        services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); });
        services.AddAutoMapper();

        services.AddDbContext<MyDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("MyDbContext"));
            options.UseOpenIddict();
        });

        services.AddOpenIddict(options =>
        {
            options.AddEntityFrameworkCoreStores<TelescopeContext>();
            options.AddMvcBinders();
            options.EnableTokenEndpoint("/Authorization/Token");
            options.AllowPasswordFlow();
            options.AllowRefreshTokenFlow();
            options.DisableHttpsRequirement();
            options.UseJsonWebTokens();
            options.AddEphemeralSigningKey();
            options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30));
        });

        var config = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); });
        services.AddSingleton(sp => config.CreateMapper());

        // Create the Autofac container builder.
        var builder = new ContainerBuilder();

        // Add any Autofac modules or registrations.
        builder.RegisterModule(new AutofacModule());

        // Populate the services.
        builder.Populate(services);

        // Build the container.
        var container = builder.Build();

        // Create and return the service provider.
        return container.Resolve<IServiceProvider>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseCors(builder => builder.WithOrigins("http://localhost:9001/")
                                      .AllowAnyOrigin());

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            Authority = "http://localhost:9001/",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            Audience = "http://localhost:9000/",
            RequireHttpsMetadata = false,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidIssuer = "http://localhost:9001/",

                ValidateAudience = true,
                ValidAudience = "http://localhost:9000",

                ValidateLifetime = true,
                IssuerSigningKey = SigningKey
            }
        });

        app.UseOpenIddict();
        app.UseMvcWithDefaultRoute();
        applicationLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
    }
}
</code>```

WebAPI.AuthorizationController.cs which issues JWT.

```<code>[Route("[controller]")]
public class AuthorizationController : Controller
{
    private IUsersService UserService { get; set; }

    public AuthorizationController(IUsersService userService)
    {
        UserService = userService;
    }

    [HttpPost("Token"), Produces("application/json")]
    public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
    {
        if (request.IsPasswordGrantType())
        {
            if (await UserService.AuthenticateUserAsync(new ViewModels.AuthenticateUserVm() { UserName = request.Username, Password = request.Password }) == false)
                return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme);

            var user = await UserService.FindByNameAsync(request.Username);

            var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme, OpenIdConnectConstants.Claims.Name, null);
            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.UserId.ToString(), OpenIdConnectConstants.Destinations.AccessToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Username, user.UserName, OpenIdConnectConstants.Destinations.AccessToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Email, user.EmailAddress, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.GivenName, user.FirstName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.MiddleName, user.MiddleName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.FamilyName, user.LastName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.EmailVerified, user.IsEmailConfirmed.ToString(), OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Audience, "http://localhost:9000", OpenIdConnectConstants.Destinations.AccessToken);

            var principal = new ClaimsPrincipal(identity);

            return SignIn(principal, OpenIdConnectServerDefaults.AuthenticationScheme);
        }

        throw new InvalidOperationException("The specified grant type is not supported.");
    }
}
</code>```

MVC.AccountController.cs contains Login, GetTokenAsync method.

```<code>public class AccountController : Controller
    {
        public static string SecretKey => "MySecretKey";
        public static SymmetricSecurityKey SigningKey => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginVm vm, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var token = await GetTokenAsync(vm);

                SecurityToken validatedToken = null;

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = "http://localhost:9001/",

                    ValidateAudience = true,
                    ValidAudience = "http://localhost:9000",

                    ValidateLifetime = true,
                    IssuerSigningKey = SigningKey
                };

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

                try
                {
                    ClaimsPrincipal principal = handler.ValidateToken(token.AccessToken, validationParameters, out validatedToken);
                }
                catch (Exception e)
                {
                    throw;
                }
            }

            return View(vm);
        }

        private async Task<TokenVm> GetTokenAsync(LoginVm vm)
        {
            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:9001/Authorization/Token");
                request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["grant_type"] = "password",
                    ["username"] = vm.EmailAddress,
                    ["password"] = vm.Password
                });

                var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
                response.EnsureSuccessStatusCode();

                var payload = await response.Content.ReadAsStringAsync();
                //if (payload["error"] != null)
                //    throw new Exception("An error occurred while retriving an access tocken.");

                return JsonConvert.DeserializeObject<TokenVm>(payload);
            }
        }
}
</code>```

Error I am getting: "IDX10501: Signature validation failed. Unable to match 'kid': '0-AY7TPAUE2-ZVLUVQMMUJFJ54IMIB70E-XUSYIB', \ntoken: '{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"0-AY7TPAUE2-ZVLUVQMMUJFJ54IMIB70E-XUSYIB\"}.{\"sub\":\"10\",\"username\":\"...

答:
First of all, I am not even sure whether this retrieving of ClaimsPrinciapal from JWT is a right approach or not.

It's likely not the approach I'd personally use. Instead, I'd simply rely on the JWT middleware to extract the ClaimsPrincipal from the access token for me (no need to manually use JwtSecurityTokenHandler for that).

The exception thrown by IdentityModel is actually caused by a very simple root cause: you've configured OpenIddict to use an ephemeral RSA asymmetric signing key (via AddEphemeralSigningKey()) and registered a symmetric signing key in the JWT bearer options, a scenario that can't obviously work.

You have two options to fix that:

Register your symmetric signing key in the OpenIddict options using AddSigningKey(SigningKey) so OpenIddict can use it.

Use an asymmetric signing key (by calling AddEphemeralSigningKey(), or AddSigningCertificate()/AddSigningKey() on production) and let the JWT bearer middleware use it instead of your symmetric signing key. For that, remove the entire TokenValidationParameters configuration to allow IdentityModel to download the public signing key from OpenIddict's discovery endpoint.

Body:
In my solution, I have two projects. 1) Web API and 2) MVC. I am using ASP.NET Core. API issues JWT token and MVC consumes it to get protected resources. I am using openiddict library to issue JWT. In MVC project, in AccountController Login method, I want to retrieve ClaimsPrincipal (using JwtSecurityTokenHandler ValidateToken method) and assign to HttpContext.User.Claims and HttpContext.User.Identity. I want to store the token in session and for each request after successful login, pass it in header to Web API. I can successfully, issue JWT and consume it in MVC project, but when I try to retrieve ClaimsPrincipal it throws me an error. First of all, I am not even sure whether this retrieving of ClaimsPrinciapal from JWT is a right approach or not. And if it is, what is the way forward.

WebAPI.Startup.CS

public class Startup
{
    public static string SecretKey => "MySecretKey";
    public static SymmetricSecurityKey SigningKey => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IContainer ApplicationContainer { get; private set; }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddCors();
        services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); });
        services.AddAutoMapper();

        services.AddDbContext<MyDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("MyDbContext"));
            options.UseOpenIddict();
        });

        services.AddOpenIddict(options =>
        {
            options.AddEntityFrameworkCoreStores<TelescopeContext>();
            options.AddMvcBinders();
            options.EnableTokenEndpoint("/Authorization/Token");
            options.AllowPasswordFlow();
            options.AllowRefreshTokenFlow();
            options.DisableHttpsRequirement();
            options.UseJsonWebTokens();
            options.AddEphemeralSigningKey();
            options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30));
        });

        var config = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); });
        services.AddSingleton(sp => config.CreateMapper());

        // Create the Autofac container builder.
        var builder = new ContainerBuilder();

        // Add any Autofac modules or registrations.
        builder.RegisterModule(new AutofacModule());

        // Populate the services.
        builder.Populate(services);

        // Build the container.
        var container = builder.Build();

        // Create and return the service provider.
        return container.Resolve<IServiceProvider>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseCors(builder => builder.WithOrigins("http://localhost:9001/")
                                      .AllowAnyOrigin());

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            Authority = "http://localhost:9001/",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            Audience = "http://localhost:9000/",
            RequireHttpsMetadata = false,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidIssuer = "http://localhost:9001/",

                ValidateAudience = true,
                ValidAudience = "http://localhost:9000",

                ValidateLifetime = true,
                IssuerSigningKey = SigningKey
            }
        });

        app.UseOpenIddict();
        app.UseMvcWithDefaultRoute();
        applicationLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
    }
}

WebAPI.AuthorizationController.cs which issues JWT.

[Route("[controller]")]
public class AuthorizationController : Controller
{
    private IUsersService UserService { get; set; }

    public AuthorizationController(IUsersService userService)
    {
        UserService = userService;
    }

    [HttpPost("Token"), Produces("application/json")]
    public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
    {
        if (request.IsPasswordGrantType())
        {
            if (await UserService.AuthenticateUserAsync(new ViewModels.AuthenticateUserVm() { UserName = request.Username, Password = request.Password }) == false)
                return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme);

            var user = await UserService.FindByNameAsync(request.Username);

            var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme, OpenIdConnectConstants.Claims.Name, null);
            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.UserId.ToString(), OpenIdConnectConstants.Destinations.AccessToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Username, user.UserName, OpenIdConnectConstants.Destinations.AccessToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Email, user.EmailAddress, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.GivenName, user.FirstName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.MiddleName, user.MiddleName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.FamilyName, user.LastName, OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.EmailVerified, user.IsEmailConfirmed.ToString(), OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Audience, "http://localhost:9000", OpenIdConnectConstants.Destinations.AccessToken);

            var principal = new ClaimsPrincipal(identity);

            return SignIn(principal, OpenIdConnectServerDefaults.AuthenticationScheme);
        }

        throw new InvalidOperationException("The specified grant type is not supported.");
    }
}

MVC.AccountController.cs contains Login, GetTokenAsync method.

public class AccountController : Controller
    {
        public static string SecretKey => "MySecretKey";
        public static SymmetricSecurityKey SigningKey => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginVm vm, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var token = await GetTokenAsync(vm);

                SecurityToken validatedToken = null;

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = "http://localhost:9001/",

                    ValidateAudience = true,
                    ValidAudience = "http://localhost:9000",

                    ValidateLifetime = true,
                    IssuerSigningKey = SigningKey
                };

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

                try
                {
                    ClaimsPrincipal principal = handler.ValidateToken(token.AccessToken, validationParameters, out validatedToken);
                }
                catch (Exception e)
                {
                    throw;
                }
            }

            return View(vm);
        }

        private async Task<TokenVm> GetTokenAsync(LoginVm vm)
        {
            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:9001/Authorization/Token");
                request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["grant_type"] = "password",
                    ["username"] = vm.EmailAddress,
                    ["password"] = vm.Password
                });

                var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
                response.EnsureSuccessStatusCode();

                var payload = await response.Content.ReadAsStringAsync();
                //if (payload["error"] != null)
                //    throw new Exception("An error occurred while retriving an access tocken.");

                return JsonConvert.DeserializeObject<TokenVm>(payload);
            }
        }
}

Error I am getting: "IDX10501: Signature validation failed. Unable to match 'kid': '0-AY7TPAUE2-ZVLUVQMMUJFJ54IMIB70E-XUSYIB', \ntoken: '{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"0-AY7TPAUE2-ZVLUVQMMUJFJ54IMIB70E-XUSYIB\"}.{\"sub\":\"10\",\"username\":\"...


问:
I have two buttons, when I select one and then want to select the other, I want the first one to get unselected
I have done two buttons in Swift by code.
Now I want them to become selectable and then when I select the first one, it gets selected but when I select the second one, the first one gets unselected and the second one gets select normally. Then when I select the first one again, the second one gets unselected.</p>

答:
In the IBAction of first button:

```<code>buttonOne.isSelected = true
buttonTwo.isSelected = false
</code>```

In the IBAction of the second button:

```<code>buttonOne.isSelected = false
buttonTwo.isSelected = true
</code>```

Body:
In the IBAction of first button:

buttonOne.isSelected = true
buttonTwo.isSelected = false

In the IBAction of the second button:

buttonOne.isSelected = false
buttonTwo.isSelected = true


问:
Are there any negative consequences if a python script moves/renames its parent directory?
I have a github project available to others. One of the scripts, update.py, checks github everyday (via cron) to see if there is a newer version available.

Locally, the script is located at directory /home/user/.Project/update.py

If the version on github is newer, then update.py moves /home/user/.Project/ to /home/user/.OldProject/, clones the github repo and moves/renames the downloaded repo to /home/user/.Project/

It has worked perfectly for me about five times, but I just realized that the script is moving itself while it is still running. Are there any unforeseen consequences to this approach, and it there a better way?

答: As long as all of the code used by the script has been compiled and loaded into the Python VM there will be no issue with the source moving since it will remain resident in memory until the process ends or is replaced (or swapped out, but since it is considered dirty data it will be swapped in exactly the same). The operating system, though, may attempt to block the move operation if any files remain open during the process.</p>


问:
Cannot resolve symbol 'Theme.AppCompat.Light.DarkActionBar' in styles.xml
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

```<code>build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }
</code>```

答:
```<code>compile 'com.android.support:appcompat-v7:23.4.0'
</code>```

try this

Body:
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }

Body:
compile 'com.android.support:appcompat-v7:23.4.0'

try this