问:
karma doesn't see tests after ng test (Executed 0 of 0 SUCCESS)
I've got a problem with running tests. After running ng test command, the command line shows

```<code>Chrome 83.0.4103 (Windows 7.0.0): Executed 0 of 0 SUCCESS (0.007 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS
</code>```

In my browser I see the karma tab with information:
0 specs, 0 failures
and in the console I've got an error
Failed to load resource: the server responded with a status of 404 (Not Found)

Tests run on other laptop.

My karma.conf.js

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    files: [
      'src/app/**/*.js'
    ],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

Package.json

```<code>{
  "name": "angular-i-spy",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "api": "json-server server/db.json --watch"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^0.900.3",
    "@angular/animations": "^9.0.2",
    "@angular/common": "^9.0.2",
    "@angular/compiler": "^9.0.2",
    "@angular/core": "^9.0.2",
    "@angular/forms": "^9.0.2",
    "@angular/http": "^7.2.16",
    "@angular/localize": "^9.1.9",
    "@angular/platform-browser": "^9.0.2",
    "@angular/platform-browser-dynamic": "^9.0.2",
    "@angular/router": "^9.0.2",
    "@ng-bootstrap/ng-bootstrap": "^5.3.0",
    "bootstrap": "^4.4.1",
    "core-js": "^2.6.11",
    "json-server": "^0.16.1",
    "rxjs": "~6.5.4",
    "ts-md5": "^1.2.7",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular/cli": "^9.0.3",
    "@angular/compiler-cli": "^9.0.2",
    "@angular/language-service": "^9.0.2",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.6",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.3",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "^3.7.5"
  }
}
</code>```

Test example:

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InitialPageComponent } from './initial-page.component';

describe('InitialPageComponent', () => {
  let component: InitialPageComponent;
  let fixture: ComponentFixture<InitialPageComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ InitialPageComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(InitialPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

Test.ts

```<code>import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
</code>```

tsconfig.spec.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}
</code>```

angular.json

```{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-iSpy": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-iSpy",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-iSpy:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular-iSpy:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-iSpy:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "angular-iSpy-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "angular-iSpy:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "angular-iSpy:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyBeaconManagement": {
      "root": "projects/ISpyBeaconManagement/",
      "sourceRoot": "projects/ISpyBeaconManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyBeaconManagement",
            "index": "projects/ISpyBeaconManagement/src/index.html",
            "main": "projects/ISpyBeaconManagement/src/main.ts",
            "polyfills": "projects/ISpyBeaconManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyBeaconManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyBeaconManagement/src/favicon.ico",
              "projects/ISpyBeaconManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyBeaconManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyBeaconManagement/src/environments/environment.ts",
                  "with": "projects/ISpyBeaconManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyBeaconManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyBeaconManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyBeaconManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyBeaconManagement/src/test.ts",
            "polyfills": "projects/ISpyBeaconManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyBeaconManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyBeaconManagement/karma.conf.js",
            "styles": [
              "projects/ISpyBeaconManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyBeaconManagement/src/favicon.ico",
              "projects/ISpyBeaconManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyBeaconManagement/tsconfig.app.json",
              "projects/ISpyBeaconManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyBeaconManagement-e2e": {
      "root": "projects/ISpyBeaconManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyBeaconManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyBeaconManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyBeaconManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyBeaconManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyRoomManagement": {
      "root": "projects/ISpyRoomManagement/",
      "sourceRoot": "projects/ISpyRoomManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyRoomManagement",
            "index": "projects/ISpyRoomManagement/src/index.html",
            "main": "projects/ISpyRoomManagement/src/main.ts",
            "polyfills": "projects/ISpyRoomManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyRoomManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyRoomManagement/src/favicon.ico",
              "projects/ISpyRoomManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyRoomManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyRoomManagement/src/environments/environment.ts",
                  "with": "projects/ISpyRoomManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyRoomManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyRoomManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyRoomManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyRoomManagement/src/test.ts",
            "polyfills": "projects/ISpyRoomManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyRoomManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyRoomManagement/karma.conf.js",
            "styles": [
              "projects/ISpyRoomManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyRoomManagement/src/favicon.ico",
              "projects/ISpyRoomManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyRoomManagement/tsconfig.app.json",
              "projects/ISpyRoomManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyRoomManagement-e2e": {
      "root": "projects/ISpyRoomManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyRoomManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyRoomManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyRoomManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyRoomManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyLocationManagement": {
      "root": "projects/ISpyLocationManagement/",
      "sourceRoot": "projects/ISpyLocationManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyLocationManagement",
            "index": "projects/ISpyLocationManagement/src/index.html",
            "main": "projects/ISpyLocationManagement/src/main.ts",
            "polyfills": "projects/ISpyLocationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyLocationManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyLocationManagement/src/favicon.ico",
              "projects/ISpyLocationManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyLocationManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyLocationManagement/src/environments/environment.ts",
                  "with": "projects/ISpyLocationManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyLocationManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyLocationManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyLocationManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyLocationManagement/src/test.ts",
            "polyfills": "projects/ISpyLocationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyLocationManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyLocationManagement/karma.conf.js",
            "styles": [
              "projects/ISpyLocationManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyLocationManagement/src/favicon.ico",
              "projects/ISpyLocationManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyLocationManagement/tsconfig.app.json",
              "projects/ISpyLocationManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyLocationManagement-e2e": {
      "root": "projects/ISpyLocationManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyLocationManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyLocationManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyLocationManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyLocationManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyPresentationManagement": {
      "root": "projects/ISpyPresentationManagement/",
      "sourceRoot": "projects/ISpyPresentationManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyPresentationManagement",
            "index": "projects/ISpyPresentationManagement/src/index.html",
            "main": "projects/ISpyPresentationManagement/src/main.ts",
            "polyfills": "projects/ISpyPresentationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyPresentationManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyPresentationManagement/src/favicon.ico",
              "projects/ISpyPresentationManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyPresentationManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyPresentationManagement/src/environments/environment.ts",
                  "with": "projects/ISpyPresentationManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyPresentationManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyPresentationManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyPresentationManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyPresentationManagement/src/test.ts",
            "polyfills": "projects/ISpyPresentationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyPresentationManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyPresentationManagement/karma.conf.js",
            "styles": [
              "projects/ISpyPresentationManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyPresentationManagement/src/favicon.ico",
              "projects/ISpyPresentationManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyPresentationManagement/tsconfig.app.json",
              "projects/ISpyPresentationManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyPresentationManagement-e2e": {
      "root": "projects/ISpyPresentationManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyPresentationManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyPresentationManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyPresentationManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyPresentationManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "angular-iSpy"
}
```

<p>I also get an error in command line</p>

```ERROR in node_modules/@types/node/index.d.ts:73:11 - error TS2300: Duplicate identifier 'IteratorResult'.

73 interface IteratorResult<T> { }
             ~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6
    41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
            ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.
node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'.

41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
        ~~~~~~~~~~~~~~

  node_modules/@types/node/index.d.ts:73:11
    73 interface IteratorResult<T> { }
                 ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.
```

Thank you very much for any help.

答:
```<code>Run npm i @types/node@latest --save-dev
</code>```

This command will resolve the error you are having.

For solving 0 specs issue do this :-
Remove files array from your karma.conf.js, and it should be fine.test.ts will take care of executing all test cases.

If it still doesn't work, change your tsconfig.spec.json to :-

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}
</code>```

and in angular.json, you should have something like:-

```<code>"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    "main": "src/test.ts",
    "polyfills": "src/polyfills.ts",
    "tsConfig": "tsconfig.spec.json",
    "karmaConfig": "karma.conf.js",
    "assets": [
      "src/favicon.ico",
      "src/assets"
    ],
    "styles": [
      "src/styles.css"
    ],
    "scripts": []
  }
}
</code>```

Body:
I've got a problem with running tests. After running ng test command, the command line shows

Chrome 83.0.4103 (Windows 7.0.0): Executed 0 of 0 SUCCESS (0.007 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS

In my browser I see the karma tab with information:
0 specs, 0 failures
and in the console I've got an error
Failed to load resource: the server responded with a status of 404 (Not Found)

Tests run on other laptop.

My karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    files: [
      'src/app/**/*.js'
    ],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Package.json

{
  "name": "angular-i-spy",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "api": "json-server server/db.json --watch"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^0.900.3",
    "@angular/animations": "^9.0.2",
    "@angular/common": "^9.0.2",
    "@angular/compiler": "^9.0.2",
    "@angular/core": "^9.0.2",
    "@angular/forms": "^9.0.2",
    "@angular/http": "^7.2.16",
    "@angular/localize": "^9.1.9",
    "@angular/platform-browser": "^9.0.2",
    "@angular/platform-browser-dynamic": "^9.0.2",
    "@angular/router": "^9.0.2",
    "@ng-bootstrap/ng-bootstrap": "^5.3.0",
    "bootstrap": "^4.4.1",
    "core-js": "^2.6.11",
    "json-server": "^0.16.1",
    "rxjs": "~6.5.4",
    "ts-md5": "^1.2.7",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular/cli": "^9.0.3",
    "@angular/compiler-cli": "^9.0.2",
    "@angular/language-service": "^9.0.2",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.6",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.3",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "^3.7.5"
  }
}

Test example:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InitialPageComponent } from './initial-page.component';

describe('InitialPageComponent', () => {
  let component: InitialPageComponent;
  let fixture: ComponentFixture<InitialPageComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ InitialPageComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(InitialPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Test.ts

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

tsconfig.spec.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-iSpy": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-iSpy",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-iSpy:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular-iSpy:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-iSpy:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "angular-iSpy-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "angular-iSpy:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "angular-iSpy:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyBeaconManagement": {
      "root": "projects/ISpyBeaconManagement/",
      "sourceRoot": "projects/ISpyBeaconManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyBeaconManagement",
            "index": "projects/ISpyBeaconManagement/src/index.html",
            "main": "projects/ISpyBeaconManagement/src/main.ts",
            "polyfills": "projects/ISpyBeaconManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyBeaconManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyBeaconManagement/src/favicon.ico",
              "projects/ISpyBeaconManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyBeaconManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyBeaconManagement/src/environments/environment.ts",
                  "with": "projects/ISpyBeaconManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyBeaconManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyBeaconManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyBeaconManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyBeaconManagement/src/test.ts",
            "polyfills": "projects/ISpyBeaconManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyBeaconManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyBeaconManagement/karma.conf.js",
            "styles": [
              "projects/ISpyBeaconManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyBeaconManagement/src/favicon.ico",
              "projects/ISpyBeaconManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyBeaconManagement/tsconfig.app.json",
              "projects/ISpyBeaconManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyBeaconManagement-e2e": {
      "root": "projects/ISpyBeaconManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyBeaconManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyBeaconManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyBeaconManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyBeaconManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyRoomManagement": {
      "root": "projects/ISpyRoomManagement/",
      "sourceRoot": "projects/ISpyRoomManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyRoomManagement",
            "index": "projects/ISpyRoomManagement/src/index.html",
            "main": "projects/ISpyRoomManagement/src/main.ts",
            "polyfills": "projects/ISpyRoomManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyRoomManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyRoomManagement/src/favicon.ico",
              "projects/ISpyRoomManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyRoomManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyRoomManagement/src/environments/environment.ts",
                  "with": "projects/ISpyRoomManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyRoomManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyRoomManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyRoomManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyRoomManagement/src/test.ts",
            "polyfills": "projects/ISpyRoomManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyRoomManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyRoomManagement/karma.conf.js",
            "styles": [
              "projects/ISpyRoomManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyRoomManagement/src/favicon.ico",
              "projects/ISpyRoomManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyRoomManagement/tsconfig.app.json",
              "projects/ISpyRoomManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyRoomManagement-e2e": {
      "root": "projects/ISpyRoomManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyRoomManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyRoomManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyRoomManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyRoomManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyLocationManagement": {
      "root": "projects/ISpyLocationManagement/",
      "sourceRoot": "projects/ISpyLocationManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyLocationManagement",
            "index": "projects/ISpyLocationManagement/src/index.html",
            "main": "projects/ISpyLocationManagement/src/main.ts",
            "polyfills": "projects/ISpyLocationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyLocationManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyLocationManagement/src/favicon.ico",
              "projects/ISpyLocationManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyLocationManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyLocationManagement/src/environments/environment.ts",
                  "with": "projects/ISpyLocationManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyLocationManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyLocationManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyLocationManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyLocationManagement/src/test.ts",
            "polyfills": "projects/ISpyLocationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyLocationManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyLocationManagement/karma.conf.js",
            "styles": [
              "projects/ISpyLocationManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyLocationManagement/src/favicon.ico",
              "projects/ISpyLocationManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyLocationManagement/tsconfig.app.json",
              "projects/ISpyLocationManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyLocationManagement-e2e": {
      "root": "projects/ISpyLocationManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyLocationManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyLocationManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyLocationManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyLocationManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyPresentationManagement": {
      "root": "projects/ISpyPresentationManagement/",
      "sourceRoot": "projects/ISpyPresentationManagement/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ISpyPresentationManagement",
            "index": "projects/ISpyPresentationManagement/src/index.html",
            "main": "projects/ISpyPresentationManagement/src/main.ts",
            "polyfills": "projects/ISpyPresentationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyPresentationManagement/tsconfig.app.json",
            "assets": [
              "projects/ISpyPresentationManagement/src/favicon.ico",
              "projects/ISpyPresentationManagement/src/assets"
            ],
            "styles": [
              "projects/ISpyPresentationManagement/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/ISpyPresentationManagement/src/environments/environment.ts",
                  "with": "projects/ISpyPresentationManagement/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ISpyPresentationManagement:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ISpyPresentationManagement:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ISpyPresentationManagement:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ISpyPresentationManagement/src/test.ts",
            "polyfills": "projects/ISpyPresentationManagement/src/polyfills.ts",
            "tsConfig": "projects/ISpyPresentationManagement/tsconfig.spec.json",
            "karmaConfig": "projects/ISpyPresentationManagement/karma.conf.js",
            "styles": [
              "projects/ISpyPresentationManagement/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/ISpyPresentationManagement/src/favicon.ico",
              "projects/ISpyPresentationManagement/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ISpyPresentationManagement/tsconfig.app.json",
              "projects/ISpyPresentationManagement/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ISpyPresentationManagement-e2e": {
      "root": "projects/ISpyPresentationManagement-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/ISpyPresentationManagement-e2e/protractor.conf.js",
            "devServerTarget": "ISpyPresentationManagement:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ISpyPresentationManagement:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/ISpyPresentationManagement-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "angular-iSpy"
}

I also get an error in command line

ERROR in node_modules/@types/node/index.d.ts:73:11 - error TS2300: Duplicate identifier 'IteratorResult'.

73 interface IteratorResult<T> { }
             ~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6
    41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
            ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.
node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'.

41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
        ~~~~~~~~~~~~~~

  node_modules/@types/node/index.d.ts:73:11
    73 interface IteratorResult<T> { }
                 ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.

Thank you very much for any help.

Body:
Run npm i @types/node@latest --save-dev

This command will resolve the error you are having.

For solving 0 specs issue do this :-
Remove files array from your karma.conf.js, and it should be fine.test.ts will take care of executing all test cases.

If it still doesn't work, change your tsconfig.spec.json to :-

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

and in angular.json, you should have something like:-

"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    "main": "src/test.ts",
    "polyfills": "src/polyfills.ts",
    "tsConfig": "tsconfig.spec.json",
    "karmaConfig": "karma.conf.js",
    "assets": [
      "src/favicon.ico",
      "src/assets"
    ],
    "styles": [
      "src/styles.css"
    ],
    "scripts": []
  }
}


来源: stackexchange

问:
Mongodb Aggregation get count of search results
I set index for data field below, then trying to get the count of particular text search content and over all text content

My input is like this below:

```<code>{
_id: 14572
data: "selling bike in india"
}
{
_id: 14673
data: "sale bike in india"
}
{
_id: 14673
data: "buying cars in india"
}
</code>```

I tired to get the count of cars, bike and total documents from collection, unfortunately not getting it,

```<code>db.collection.aggregate([
  {
    "Total": [
      {$match:{"$text":{$search:"india"}}},
      { "$count": "Total" },
    ],
    "bike": [
      {$match:{"$text":{$search:"bike"}}},
      { "$count": "bike" }
      ]

  { "$project": {
    "Total": { "$arrayElemAt": ["$Total.Total", 0] },
    "bike": { "$arrayElemAt": ["$bikebike.Birds", 0] }
  }}
])
</code>```

expected output like below

```<code>Total:3
bike:2
car:1
</code>```

答:
The $text operator has some restrictions described at https://docs.mongodb.com/manual/reference/operator/query/text/index.html

A couple relevant to this query:

A query can specify, at most, one $text expression.

If using the $text operator in aggregation, the following restrictions also apply.

The $match stage that includes a $text must be the first stage in the pipeline.

Since you are trying to do separate text searches for different strings, you'll need to do each one separately, like

```<code>db.collection.count({$text:{$search:"india"}})
db.collection.count({$text:{$search:"bike"}})
db.collection.count({$text:{$search:"car"}})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I set index for data field below, then trying to get the count of particular text search content and over all text content

My input is like this below:

{
_id: 14572
data: "selling bike in india"
}
{
_id: 14673
data: "sale bike in india"
}
{
_id: 14673
data: "buying cars in india"
}

I tired to get the count of cars, bike and total documents from collection, unfortunately not getting it,

db.collection.aggregate([
  {
    "Total": [
      {$match:{"$text":{$search:"india"}}},
      { "$count": "Total" },
    ],
    "bike": [
      {$match:{"$text":{$search:"bike"}}},
      { "$count": "bike" }
      ]

  { "$project": {
    "Total": { "$arrayElemAt": ["$Total.Total", 0] },
    "bike": { "$arrayElemAt": ["$bikebike.Birds", 0] }
  }}
])

expected output like below

Total:3
bike:2
car:1

Body:
The $text operator has some restrictions described at https://docs.mongodb.com/manual/reference/operator/query/text/index.html

A couple relevant to this query:

A query can specify, at most, one $text expression.

If using the $text operator in aggregation, the following restrictions also apply.

The $match stage that includes a $text must be the first stage in the pipeline.

Since you are trying to do separate text searches for different strings, you'll need to do each one separately, like

db.collection.count({$text:{$search:"india"}})
db.collection.count({$text:{$search:"bike"}})
db.collection.count({$text:{$search:"car"}})


问:
How to execute activate and deactivate methods of OSGI bundle in a single thread
I have an OSGI bundle of a following structure:

```<code>//...

public ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

//...

@Activate
public void activate() {
   executor.submit(new Runnable() {
     @Override
     public void run() {
      //call 3 functions and log the data
     }
   }
}

@Deactivate
public void deactivate(){
  //call 2 other functions
}
</code>```

The executor in the activate method makes sure that 3 functions are called in a separate from all other bundles thread, because those functions actually implement some sophisticated Windows-message-loop, i.e. a while true loop, that's why, in order not to block other bundles, it is activated in a separate thread. Now what I've sadly noticed, that in order to run 2 functions in deactivate method I need to run them in the same thread, in which 3 functions in activate method were run. Simply speaking, I need to be sure, that activate and deactivate methods of my bundle run in the one same thread, but still to keep this bundle activation separated (in an own thread) from the other bundles.

My question is: how to implement this?

I am not a guru in concurrency in Java, I've tried simply to call this executor in the deactivate method too but I don't know how to do it with one Runnable task, since in deactivate I have only to call 2 functions and in activate only 3 functions and no other calls should be made.

UPD: sorry, I forgot to mention, that there is a routine in another bundle, which calls in certain situations context.getBundle(0).stop() in order to call a deactivation for all bundles. If I want just to add the same submit routine in the deactivate method as is in activate, then in such situation I could clearly see, that those 2 functions from deactivate method of my bundle in the submit's body were not called.

答:
This sounds like a very common problem. I would just make it explicit you're using a thread and use the methods in Thread that were designed for this. At activate you start the thread, at deactivate you interrupt it. Your main loop watches the interrupt status and executes your deactivate functions after it is interrupted. After interrupt, it is best to join the thread to ensure your activate() method does not return before the background thread has finished running your deactivate functions.

Since exiting the framework (stopping bundle 0) must stop all bundles, and a stopped bundle will deactivate its components, this should all work.

```<code> public class Foo extends Thread {

      @Activate   void activate()   { start(); }
      @Deactivate void deactivate() throws Exception { interrupt(); join(); }

      public void run() {

            while(!isInterrupted()) try {
              ... your 3 function loop
            } catch( InterruptedException e) {
              break;
            }
            ... 2 deactivate functions
      }
  }
</code>```

Body:
I have an OSGI bundle of a following structure:

//...

public ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

//...

@Activate
public void activate() {
   executor.submit(new Runnable() {
     @Override
     public void run() {
      //call 3 functions and log the data
     }
   }
}

@Deactivate
public void deactivate(){
  //call 2 other functions
}

The executor in the activate method makes sure that 3 functions are called in a separate from all other bundles thread, because those functions actually implement some sophisticated Windows-message-loop, i.e. a while true loop, that's why, in order not to block other bundles, it is activated in a separate thread. Now what I've sadly noticed, that in order to run 2 functions in deactivate method I need to run them in the same thread, in which 3 functions in activate method were run. Simply speaking, I need to be sure, that activate and deactivate methods of my bundle run in the one same thread, but still to keep this bundle activation separated (in an own thread) from the other bundles.

My question is: how to implement this?

I am not a guru in concurrency in Java, I've tried simply to call this executor in the deactivate method too but I don't know how to do it with one Runnable task, since in deactivate I have only to call 2 functions and in activate only 3 functions and no other calls should be made.

UPD: sorry, I forgot to mention, that there is a routine in another bundle, which calls in certain situations context.getBundle(0).stop() in order to call a deactivation for all bundles. If I want just to add the same submit routine in the deactivate method as is in activate, then in such situation I could clearly see, that those 2 functions from deactivate method of my bundle in the submit's body were not called.

Body:
This sounds like a very common problem. I would just make it explicit you're using a thread and use the methods in Thread that were designed for this. At activate you start the thread, at deactivate you interrupt it. Your main loop watches the interrupt status and executes your deactivate functions after it is interrupted. After interrupt, it is best to join the thread to ensure your activate() method does not return before the background thread has finished running your deactivate functions.

Since exiting the framework (stopping bundle 0) must stop all bundles, and a stopped bundle will deactivate its components, this should all work.

 public class Foo extends Thread {

      @Activate   void activate()   { start(); }
      @Deactivate void deactivate() throws Exception { interrupt(); join(); }

      public void run() {

            while(!isInterrupted()) try {
              ... your 3 function loop
            } catch( InterruptedException e) {
              break;
            }
            ... 2 deactivate functions
      }
  }


问:
Lotusscript MIME Email
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

```<code>    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream
</code>```

Set body = mailDoc.CreateMIMEEntity

```<code>    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True
</code>```

Any idea what could I miss?
Thanks

答: IMHO far better code you can find at: http://www.codestore.net/store.nsf/unid/BLOG-20091022-0419</p>

Title: Lotusscript MIME Email

Body:
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream

Set body = mailDoc.CreateMIMEEntity

    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True

Any idea what could I miss?
Thanks


问:
Unification in pattern matching case
I was trying to write a function whose type is forall n, option (n = 1).

I choose option as an altertnative to reflect avoiding giving the proof of the negative case. So Some plays the role ReflectT and holds the proof, while None doesn't hold the negative proof.

```<code>Definition is_1 n: bool:=
  match n with
    1 => true |
    _ => false
  end.

Lemma is_1_complete : forall n, is_1 n = true -> n = 1.
intros.
destruct n. simpl in H. discriminate.
destruct n. reflexivity.
simpl in H. discriminate.
Qed.

Lemma a_nat_is_1_or_not: forall n, option (n = 1).
intros.
cut (is_1 n = true -> n = 1).
-
intros.
destruct n. exact None.
destruct n. simpl in H. exact (Some (H (eq_refl))).
exact None.
-
exact (is_1_complete n).
Qed.
</code>```

I've done with tactics. a_nat_is_1_or_not is the proof. And I thought I can do this writing the definition directly, so I tried.

```<code>Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n with
     true => Some (is_1_complete n eq_refl)
     | false => None
  end.
</code>```

But Coq saids

```<code>Error:
In environment
n : nat
The term "eq_refl" has type "is_1 n = is_1 n"
while it is expected to have type "is_1 n = true" (cannot unify "is_1 n" and
"true").
</code>```

It seems is_1 n cannot be unified to true in true case of the pattern matching of itself.

So I tried a more trivial example.

```<code>Definition every_true_is_I x: x = I :=
  match x with
     I => eq_refl
  end.
</code>```

It works.

What is the difference between a_nat_is_1_or_not' and every_truer_is_I?
Am I missing something? What can I do for writing a valid definition of forall n, is_1 n = true -> n = 1.?

答:
The difference is that, in a_nat_is_1_or_not', you are depending on an external term whose type is is_1 n = true -> _. If you want a_nat_is_1_or_not' to look like every_true_is_I, you have to make sure that all the occurrences of is_1 n are covered by the pattern matching:

```<code>Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n as b return ((b = true -> _) -> _) with
  | true => fun H => Some (H eq_refl)
  | false => fun _ => None
  end (is_1_complete n).
</code>```

Notice how is_1_complete has been instantiated outside the pattern matching, so that its occurrence of is_1 n (renamed b) is handled.

There is another way to do it, perhaps a bit more idiomatic. Instead of generalizing the whole context, you just keep enough information to fill all the holes:

```<code>Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n as b return (is_1 n = b -> _) with
  | true => fun H => Some (is_1_complete n H)
  | false => fun _ => None
  end eq_refl.
</code>```

But the idea is the same. By instantiating eq_refl outside the pattern matching, you do not lose any information when matching on is_1 n.

Title: Unification in pattern matching case

Body:
I was trying to write a function whose type is forall n, option (n = 1).

I choose option as an altertnative to reflect avoiding giving the proof of the negative case. So Some plays the role ReflectT and holds the proof, while None doesn't hold the negative proof.

Definition is_1 n: bool:=
  match n with
    1 => true |
    _ => false
  end.

Lemma is_1_complete : forall n, is_1 n = true -> n = 1.
intros.
destruct n. simpl in H. discriminate.
destruct n. reflexivity.
simpl in H. discriminate.
Qed.

Lemma a_nat_is_1_or_not: forall n, option (n = 1).
intros.
cut (is_1 n = true -> n = 1).
-
intros.
destruct n. exact None.
destruct n. simpl in H. exact (Some (H (eq_refl))).
exact None.
-
exact (is_1_complete n).
Qed.

I've done with tactics. a_nat_is_1_or_not is the proof. And I thought I can do this writing the definition directly, so I tried.

Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n with
     true => Some (is_1_complete n eq_refl)
     | false => None
  end.

But Coq saids

Error:
In environment
n : nat
The term "eq_refl" has type "is_1 n = is_1 n"
while it is expected to have type "is_1 n = true" (cannot unify "is_1 n" and
"true").

It seems is_1 n cannot be unified to true in true case of the pattern matching of itself.

So I tried a more trivial example.

Definition every_true_is_I x: x = I :=
  match x with
     I => eq_refl
  end.

It works.

What is the difference between a_nat_is_1_or_not' and every_truer_is_I?
Am I missing something? What can I do for writing a valid definition of forall n, is_1 n = true -> n = 1.?

Body:
The difference is that, in a_nat_is_1_or_not', you are depending on an external term whose type is is_1 n = true -> _. If you want a_nat_is_1_or_not' to look like every_true_is_I, you have to make sure that all the occurrences of is_1 n are covered by the pattern matching:

Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n as b return ((b = true -> _) -> _) with
  | true => fun H => Some (H eq_refl)
  | false => fun _ => None
  end (is_1_complete n).

Notice how is_1_complete has been instantiated outside the pattern matching, so that its occurrence of is_1 n (renamed b) is handled.

There is another way to do it, perhaps a bit more idiomatic. Instead of generalizing the whole context, you just keep enough information to fill all the holes:

Definition a_nat_is_1_or_not' n: option (n = 1) :=
  match is_1 n as b return (is_1 n = b -> _) with
  | true => fun H => Some (is_1_complete n H)
  | false => fun _ => None
  end eq_refl.

But the idea is the same. By instantiating eq_refl outside the pattern matching, you do not lose any information when matching on is_1 n.


问:
Detect click outside react parent component
How to know that user has clicked outside our react app which is pointed to

(I'm having extra space to click outside root div)

I've tried the below code

```<code>import ReactDOM from 'react-dom';
// ... ✂

componentDidMount() {
    document.addEventListener('click', this.handleClickOutside, true);
}

componentWillUnmount() {
    document.removeEventListener('click', this.handleClickOutside, true);
}

handleClickOutside = event => {
    const domNode = ReactDOM.findDOMNode(this);

    if (!domNode || !domNode.contains(event.target)) {
        this.setState({
            visible: false
        });
    console.log("clicked outside")
    }
}
</code>```

But then, even if I clicked inside some child popup component under parent, it is showing as "clicked outside"

If I click anywhere inside the app (including children component), it should not say, "clicked outside"

So is there any way to know that the user clicked outside the complete app itself?

答:
There is a special component, just wrap your component in it and that's it...very convinient

```<code>import onClickOutside from "react-onclickoutside";

class MyComponent extends Component {
  handleClickOutside = evt => {
    // ..handling code goes here...
  };
}

export default onClickOutside(MyComponent);
</code>```

https://github.com/Pomax/react-onclickoutside

Body:
How to know that user has clicked outside our react app which is pointed to

(I'm having extra space to click outside root div)

I've tried the below code

import ReactDOM from 'react-dom';
// ... ✂

componentDidMount() {
    document.addEventListener('click', this.handleClickOutside, true);
}

componentWillUnmount() {
    document.removeEventListener('click', this.handleClickOutside, true);
}

handleClickOutside = event => {
    const domNode = ReactDOM.findDOMNode(this);

    if (!domNode || !domNode.contains(event.target)) {
        this.setState({
            visible: false
        });
    console.log("clicked outside")
    }
}

But then, even if I clicked inside some child popup component under parent, it is showing as "clicked outside"

If I click anywhere inside the app (including children component), it should not say, "clicked outside"

So is there any way to know that the user clicked outside the complete app itself?

Body:
There is a special component, just wrap your component in it and that's it...very convinient

import onClickOutside from "react-onclickoutside";

class MyComponent extends Component {
  handleClickOutside = evt => {
    // ..handling code goes here...
  };
}

export default onClickOutside(MyComponent);

https://github.com/Pomax/react-onclickoutside


问:
Accuracy is not increasing, though loss is decreasing
I am feeding cnn features into gpflow model. I am writing the chunks of code from my program here. I am using tape.gradient with Adam optimizer (scheduled lr). My accuracy gets stuck on 47% and surprisingly , my loss still gets reducing. Its very weird. I have debugged the program. CNN features are ok but gp model is not learning .Please can you check the training loop and let me know where am I wrong.

```<code>def optimization_step(gp_model: gpflow.models.SVGP, image_data,labels):

 with tf.GradientTape(watch_accessed_variables=False)as tape:
    tape.watch(gp_model.trainable_variables)

    cnn_feat = cnn_model(image_data,training=False)

    cnn_feat=tf.cast(cnn_feat,dtype=default_float())
    labels=tf.cast(labels,dtype=np.int64)

    data=(cnn_feat, labels)

    loss = gp_model.training_loss(data)

    gp_grads=tape.gradient(loss, gp_model.trainable_variables)

 gp_optimizer.apply_gradients(zip(gp_grads, gp_model.trainable_variables))

 return loss, cnn_feat
</code>```

the loop for training is

```<code> def simple_training_loop(gp_model: gpflow.models.SVGP, epochs: int = 3, logging_epoch_freq: int = 10):

    total_loss = []
    features=[]

    tf_optimization_step = tf.function(optimization_step, autograph=False)

    for epoch in range(epochs):

       lr.assign(max(args.learning_rate_clip, args.learning_rate * (args.decay_rate ** epoch)))

       data_loader.shuffle_data(args.is_training)

       for b in range(data_loader.n_batches):

            batch_x, batch_y= data_loader.next_batch(b)

            batch_x=tf.convert_to_tensor(batch_x)
            batch_y=tf.convert_to_tensor(batch_y)

            loss,features_CNN=tf_optimization_step(gp_model, batch_x,batch_y)
</code>```

I am restoring weights for CNN from checkpoints saved during transfer learning.

With more epochs , loss continue to decrease but accuracy starts decreasing as well.

The gp model declaration is as follows

```<code>     kernel = gpflow.kernels.Matern32() +  gpflow.kernels.White(variance=0.01)

     invlink = gpflow.likelihoods.RobustMax(C)
     likelihood = gpflow.likelihoods.MultiClass(C, invlink=invlink)
</code>```

the test Function

```<code>       cnn_feat=cnn_model(test_x,training=False)

       cnn_feat = tf.cast(cnn_feat, dtype=default_float())

       mean, var = gp_model.predict_f(cnn_feat)

       preds = np.argmax(mean, 1).reshape(test_labels.shape)
       correct = (preds == test_labels.numpy().astype(int))
       acc = np.average(correct.astype(float)) * 100
</code>```

答:
Can you please just check that whether the training loop is correctly written

The training loop looks fine. However, there are bits that should be modified for clarity and for optimisation sake.

```<code>def simple_training_loop(gp_model: gpflow.models.SVGP, epochs: int = 3, logging_epoch_freq: int = 10):
    total_loss = []
    features=[]

    @tf.function
    def compute_cnn_feat(x: tf.Tensor) -> tf.Tensor:
        return tf.cast(cnn_model(x, training=False), dtype=default_float())

    @tf.function
    def optimization_step(cnn_feat: tf.Tensor, labels: tf.Tensor):  # **Change 1.**
        with tf.GradientTape(watch_accessed_variables=False) as tape:
            tape.watch(gp_model.trainable_variables)
            data = (cnn_feat, labels)
            loss = gp_model.training_loss(data)
        gp_grads = tape.gradient(loss, gp_model.trainable_variables)  # **Change 2.**
        gp_optimizer.apply_gradients(zip(gp_grads, gp_model.trainable_variables))
        return loss

    for epoch in range(epochs):
       lr.assign(max(args.learning_rate_clip, args.learning_rate * (args.decay_rate ** epoch)))
       data_loader.shuffle_data(args.is_training)
       for b in range(data_loader.n_batches):
            batch_x, batch_y= data_loader.next_batch(b)
            batch_x = tf.convert_to_tensor(batch_x)
            batch_y = tf.convert_to_tensor(batch_y, dtype=default_float())
            cnn_feat = compute_cnn_feat(batch_x)  # **Change 3.**
            loss = optimization_step(cnn_feat, batch_y)
</code>```

Change 1. Signature of a function that you wrap with tf.function should not have mutable objects.

Change 2. The gradient tape will track all computations inside the context manager, including the computation of the gradients i.e. tape.gradient(...). In turn, that means your code performs an unnecessary calculation.

Change 3.  For the same reason as in "Change 2." I moved the CNN feature extraction outside of the gradient tape.

Body:
I am feeding cnn features into gpflow model. I am writing the chunks of code from my program here. I am using tape.gradient with Adam optimizer (scheduled lr). My accuracy gets stuck on 47% and surprisingly , my loss still gets reducing. Its very weird. I have debugged the program. CNN features are ok but gp model is not learning .Please can you check the training loop and let me know where am I wrong.

def optimization_step(gp_model: gpflow.models.SVGP, image_data,labels):

 with tf.GradientTape(watch_accessed_variables=False)as tape:
    tape.watch(gp_model.trainable_variables)

    cnn_feat = cnn_model(image_data,training=False)

    cnn_feat=tf.cast(cnn_feat,dtype=default_float())
    labels=tf.cast(labels,dtype=np.int64)

    data=(cnn_feat, labels)

    loss = gp_model.training_loss(data)

    gp_grads=tape.gradient(loss, gp_model.trainable_variables)

 gp_optimizer.apply_gradients(zip(gp_grads, gp_model.trainable_variables))

 return loss, cnn_feat

the loop for training is

 def simple_training_loop(gp_model: gpflow.models.SVGP, epochs: int = 3, logging_epoch_freq: int = 10):

    total_loss = []
    features=[]

    tf_optimization_step = tf.function(optimization_step, autograph=False)

    for epoch in range(epochs):

       lr.assign(max(args.learning_rate_clip, args.learning_rate * (args.decay_rate ** epoch)))

       data_loader.shuffle_data(args.is_training)

       for b in range(data_loader.n_batches):

            batch_x, batch_y= data_loader.next_batch(b)

            batch_x=tf.convert_to_tensor(batch_x)
            batch_y=tf.convert_to_tensor(batch_y)

            loss,features_CNN=tf_optimization_step(gp_model, batch_x,batch_y)

I am restoring weights for CNN from checkpoints saved during transfer learning.

With more epochs , loss continue to decrease but accuracy starts decreasing as well.

The gp model declaration is as follows

     kernel = gpflow.kernels.Matern32() +  gpflow.kernels.White(variance=0.01)

     invlink = gpflow.likelihoods.RobustMax(C)
     likelihood = gpflow.likelihoods.MultiClass(C, invlink=invlink)

the test Function

       cnn_feat=cnn_model(test_x,training=False)

       cnn_feat = tf.cast(cnn_feat, dtype=default_float())

       mean, var = gp_model.predict_f(cnn_feat)

       preds = np.argmax(mean, 1).reshape(test_labels.shape)
       correct = (preds == test_labels.numpy().astype(int))
       acc = np.average(correct.astype(float)) * 100

Body:
Can you please just check that whether the training loop is correctly written

The training loop looks fine. However, there are bits that should be modified for clarity and for optimisation sake.

def simple_training_loop(gp_model: gpflow.models.SVGP, epochs: int = 3, logging_epoch_freq: int = 10):
    total_loss = []
    features=[]

    @tf.function
    def compute_cnn_feat(x: tf.Tensor) -> tf.Tensor:
        return tf.cast(cnn_model(x, training=False), dtype=default_float())

    @tf.function
    def optimization_step(cnn_feat: tf.Tensor, labels: tf.Tensor):  # **Change 1.**
        with tf.GradientTape(watch_accessed_variables=False) as tape:
            tape.watch(gp_model.trainable_variables)
            data = (cnn_feat, labels)
            loss = gp_model.training_loss(data)
        gp_grads = tape.gradient(loss, gp_model.trainable_variables)  # **Change 2.**
        gp_optimizer.apply_gradients(zip(gp_grads, gp_model.trainable_variables))
        return loss

    for epoch in range(epochs):
       lr.assign(max(args.learning_rate_clip, args.learning_rate * (args.decay_rate ** epoch)))
       data_loader.shuffle_data(args.is_training)
       for b in range(data_loader.n_batches):
            batch_x, batch_y= data_loader.next_batch(b)
            batch_x = tf.convert_to_tensor(batch_x)
            batch_y = tf.convert_to_tensor(batch_y, dtype=default_float())
            cnn_feat = compute_cnn_feat(batch_x)  # **Change 3.**
            loss = optimization_step(cnn_feat, batch_y)

Change 1. Signature of a function that you wrap with tf.function should not have mutable objects.

Change 2. The gradient tape will track all computations inside the context manager, including the computation of the gradients i.e. tape.gradient(...). In turn, that means your code performs an unnecessary calculation.

Change 3.  For the same reason as in "Change 2." I moved the CNN feature extraction outside of the gradient tape.


问:
Infinispan equivalent to ehcache's copyOnRead and copyOnWrite
I am planning to implement a cache solution into an existing web app. Nothing complicated: basically a concurrent map that supports overflowing to disk and automatic eviction. Clustering the cache could be requirement in the future, but not now.

I like ehcache's copyOnRead and copyOnWrite features, because it means that I don't have to manually clone things before modifying something I take out of the cache. Now I have started to look at Infinispan, but I have not found anything equivalent there. Does it exist?

I.e., the following unit tests should pass:

```<code>@Test
public void testCopyOnWrite() {
    Date date = new Date(0);
    cache.put(0, date);
    date.setTime(1000);
    date = cache.get(0);
    assertEquals(0, date.getTime());
}

@Test
public void testCopyOnRead() {
    Date date = new Date(0);
    cache.put(0, date);
    assertNotSame(cache.get(0), cache.get(0));
}
</code>```

答: Infinispan does support copyOnRead/copyOnWrite, albeit the actual format isn't pluggable.  The configuration element is lazyDeserialization in Infinispan 4.x and storeAsBinary in Infinispan 5.x.  Objects are serialized using the pluggable Marshaller framework, which is used for all forms of marshalling including for RPC calls over a network and storage to disk.

ContentLicense: CC BY-SA 2.5

Body:
I am planning to implement a cache solution into an existing web app. Nothing complicated: basically a concurrent map that supports overflowing to disk and automatic eviction. Clustering the cache could be requirement in the future, but not now.

I like ehcache's copyOnRead and copyOnWrite features, because it means that I don't have to manually clone things before modifying something I take out of the cache. Now I have started to look at Infinispan, but I have not found anything equivalent there. Does it exist?

I.e., the following unit tests should pass:

@Test
public void testCopyOnWrite() {
    Date date = new Date(0);
    cache.put(0, date);
    date.setTime(1000);
    date = cache.get(0);
    assertEquals(0, date.getTime());
}

@Test
public void testCopyOnRead() {
    Date date = new Date(0);
    cache.put(0, date);
    assertNotSame(cache.get(0), cache.get(0));
}

ContentLicense: CC BY-SA 3.0


问:
Add a column to spark dataframe which contains list of all column names of the current row whose value is not null
Hi I want to add a new column to a dafaframe which contains the list of all column names(for that row) which are not null. How do I achieve this in Scala. Please help.

```<code>val baseDF = Seq(
(3, "California", "name1", 9846, null, "SFO"),
(1, "Oregon", "name2", 9847, null, null),
(2, null, null, null, null, null)
).toDF("emp_id", "emp_city", "emp_name", "emp_phone", "emp_sal", "emp_site")
</code>```

Expected output is new column named "NonNullColumns" with expected non null column names for each row:

```<code>NonNullColumns
==============
["emp_id", "emp_city", "emp_name", "emp_phone", "emp_site"]
["emp_id", "emp_city", "emp_name", "emp_phone"]
["emp_id"]
</code>```

Body:
Hi I want to add a new column to a dafaframe which contains the list of all column names(for that row) which are not null. How do I achieve this in Scala. Please help.

val baseDF = Seq(
(3, "California", "name1", 9846, null, "SFO"),
(1, "Oregon", "name2", 9847, null, null),
(2, null, null, null, null, null)
).toDF("emp_id", "emp_city", "emp_name", "emp_phone", "emp_sal", "emp_site")

Expected output is new column named "NonNullColumns" with expected non null column names for each row:

NonNullColumns
==============
["emp_id", "emp_city", "emp_name", "emp_phone", "emp_site"]
["emp_id", "emp_city", "emp_name", "emp_phone"]
["emp_id"]

Body:
I've loaded data from csv, all fields as strings.

val cols = baseDF.schema.fieldNames.map(s=>when(col(s).isNotNull, s).otherwise(""))
df.select(cols:_*).select(array_remove(array('*),"").as("NonNullColumns")).show(false)

output:

+------+----------+--------+---------+-------+--------+
|emp_id|  emp_city|emp_name|emp_phone|emp_sal|emp_site|
+------+----------+--------+---------+-------+--------+
|     3|California|   name1|     9846|   null|     SFO|
|     1|    Oregon|   name2|     9847|   null|    null|
|     2|      null|    null|     null|   null|    null|
+------+----------+--------+---------+-------+--------+

+-------------------------------------------------+
|NonNullColumns                                   |
+-------------------------------------------------+
|[emp_id, emp_city, emp_name, emp_phone, emp_site]|
|[emp_id, emp_city, emp_name, emp_phone]          |
|[emp_id]                                         |
+-------------------------------------------------+


问:
Use python date function inside SQLAlchemy column property
I have these models in SQLAlchemy. it is defining a simple action of my system which is liking a post by an account, so each account can like several posts and also a post can be liked by many accounts(Many-to-Many), Every looks fine execpt likes_per_day column property that I want it to show number of likes each day of an account. when I run this code and keep this running, it looks like date.today() will execute at run time and always shows me the number of likes of rundate, not today.

So I'm planning to get number of likes for each day using column property. what is the correct way to do this?

```<code>class Account(Base):
    __tablename__ = 'account'

    id = Column(
        Integer,
        primary_key=True
    )

    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == date.today()) # Problem is here
        .correlate_except(Like)
    )

class Like(Base):
    __tablename__ = 'like'

    id = Column(
        Integer,
        primary_key=True
    )

    post_id = Column(
        Integer,
        ForeignKey('post.id')
    )
    account_id = Column(
        Integer,
        ForeignKey('account.id')
    )
    created_at = Column(
        DateTime,
        nullable=False,
        default=datetime.utcnow,
    )
</code>```

答:
How about to use:

    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == bindparam(
            'today',
            callable_=lambda:date.today().isoformat()
            )
        )
        .correlate_except(Like),
        deferred=True
    )
```

the date function returns the iso format of a DateTime, on the other hand the date.today() is an object of date that sqlalchemy doesn't know how should parse because of various date formats.
So by declaring the date format explicitly you should get the result you want.

Body:
I have these models in SQLAlchemy. it is defining a simple action of my system which is liking a post by an account, so each account can like several posts and also a post can be liked by many accounts(Many-to-Many), Every looks fine execpt likes_per_day column property that I want it to show number of likes each day of an account. when I run this code and keep this running, it looks like date.today() will execute at run time and always shows me the number of likes of rundate, not today.

So I'm planning to get number of likes for each day using column property. what is the correct way to do this?

class Account(Base):
    __tablename__ = 'account'

    id = Column(
        Integer,
        primary_key=True
    )

    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == date.today()) # Problem is here
        .correlate_except(Like)
    )

class Like(Base):
    __tablename__ = 'like'

    id = Column(
        Integer,
        primary_key=True
    )

    post_id = Column(
        Integer,
        ForeignKey('post.id')
    )
    account_id = Column(
        Integer,
        ForeignKey('account.id')
    )
    created_at = Column(
        DateTime,
        nullable=False,
        default=datetime.utcnow,
    )

Body:
How about to use:

    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == bindparam(
            'today',
            callable_=lambda:date.today().isoformat()
            )
        )
        .correlate_except(Like),
        deferred=True
    )

the date function returns the iso format of a DateTime, on the other hand the date.today() is an object of date that sqlalchemy doesn't know how should parse because of various date formats.
So by declaring the date format explicitly you should get the result you want.


问:
Search box with various filters
I have a table name voice with tele_no, date_time and appointment as records. I am trying filter with various combination. If i use OR then it include all fields, If i use AND then all fields must be entered. How to use combination, mean if i type single field or combination of multiple fields. It should return query

```<code>$result =mysqli_query($hello,"
SELECT voice.*
     , record.*
  FROM voice (voice.tele_no = '$tele' AND voice.tele_no<>'')
    OR (voice.date_time between '$date_fm' and '$date_to' AND voice.date_time<>'')
    OR (voice.appointment= '$tele' AND voice.appointment<>'')
</code>```

答:
I would use a flexible prepared statement here, something like:

```<code>SELECT *
FROM voice
WHERE
    (tele_no = ? OR tele_no IS NULL) AND
    (date_time BETWEEN ? AND ? OR date_time IS NULL) AND
    (appointment = ? OR appointment IS NULL);
</code>```

Should any of the three columns appearing in the WHERE clause be NULL, then that particular condition would effectively no-op and logically drop out of the query.  Note that to implement this from PHP, you would need to use one of several PHP's prepared statement libraries.

Title: Search box with various filters

Body:
I have a table name voice with tele_no, date_time and appointment as records. I am trying filter with various combination. If i use OR then it include all fields, If i use AND then all fields must be entered. How to use combination, mean if i type single field or combination of multiple fields. It should return query

$result =mysqli_query($hello,"
SELECT voice.*
     , record.*
  FROM voice (voice.tele_no = '$tele' AND voice.tele_no<>'')
    OR (voice.date_time between '$date_fm' and '$date_to' AND voice.date_time<>'')
    OR (voice.appointment= '$tele' AND voice.appointment<>'')

Body:
I would use a flexible prepared statement here, something like:

SELECT *
FROM voice
WHERE
    (tele_no = ? OR tele_no IS NULL) AND
    (date_time BETWEEN ? AND ? OR date_time IS NULL) AND
    (appointment = ? OR appointment IS NULL);

Should any of the three columns appearing in the WHERE clause be NULL, then that particular condition would effectively no-op and logically drop out of the query.  Note that to implement this from PHP, you would need to use one of several PHP's prepared statement libraries.


问:
Select the value of a TD on click to ease copy
I want to select onclick the innerHTML of a td so the user can just do ctrl+C to copy the content.

I tried many combination and I can't find a way. However it seams to work on inputs with a simple document.getElementById(id).select();

Adding a focus don't effect anything, and the .select() send and error:

document.getElementById(...).select is not a function

So how can I do with a td element?
I don't mind if it's not working on IE.

Or if possible, directly copying the text.

答:
try this:

```<code>$("td").click(function (e) {
    var clickedCell = $(e.target).closest("td");
    navigator.clipboard.writeText(clickedCell.text());
});
</code>```

It will write the clicked cell text to the browser clipboard, works for me!

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText

Body:
try this:

$("td").click(function (e) {
    var clickedCell = $(e.target).closest("td");
    navigator.clipboard.writeText(clickedCell.text());
});

It will write the clicked cell text to the browser clipboard, works for me!

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText