问:
Angular route guard always redirects to app component only
I have a guard which should run on every route. If user is logged in, they should be redirected to dashboard else to login. Login works fine but auth guard never redirects to dashboard. it always stays in base route. If i manually redirect to dashboard from guard it causes an infinite loop.

app-routes.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'home',
        component: AppComponent
      }
    ]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];
```

<p><strong>AuthGuard.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private _router: Router, private _loaderService: LoaderService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this._loaderService.show();
    this.authService.isLoggedIn().subscribe( (_allowed: boolean) => {
      if (_allowed) {
        this._loaderService.hide();
        console.info('authenticated', next, _state);
        // this._router.navigate(['/dashboard']); // this cause infinite loop if uncommented
        return true;
      } else {
        console.info('not authenticated');
        this._loaderService.hide();
        this._router.navigate(['/login'], {
          queryParams: {
            return: _state.url
          }
        });
      }
    });
    return false;
  }
}
</code>```

AuthService.ts

isLoggedIn(): Observable<boolean> {
    if (this.token) {
      return this._httpClient.get(environment.api_url + `/api/auth/` + this.token)
        .pipe(map((_response: any) => {
          this._user.updateUser(_response.data);
          this.updateToken(_response.token);
          return _response.status;
        }));
    } else {
      return of(false);
    }
  }
```

答:
try implementing CanActivateChild also -</p>

```<code>canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(route, state);
}
</code>```

Body:
I have a guard which should run on every route. If user is logged in, they should be redirected to dashboard else to login. Login works fine but auth guard never redirects to dashboard. it always stays in base route. If i manually redirect to dashboard from guard it causes an infinite loop.

app-routes.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'home',
        component: AppComponent
      }
    ]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

AuthGuard.ts

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private _router: Router, private _loaderService: LoaderService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this._loaderService.show();
    this.authService.isLoggedIn().subscribe( (_allowed: boolean) => {
      if (_allowed) {
        this._loaderService.hide();
        console.info('authenticated', next, _state);
        // this._router.navigate(['/dashboard']); // this cause infinite loop if uncommented
        return true;
      } else {
        console.info('not authenticated');
        this._loaderService.hide();
        this._router.navigate(['/login'], {
          queryParams: {
            return: _state.url
          }
        });
      }
    });
    return false;
  }
}

AuthService.ts

isLoggedIn(): Observable<boolean> {
    if (this.token) {
      return this._httpClient.get(environment.api_url + `/api/auth/` + this.token)
        .pipe(map((_response: any) => {
          this._user.updateUser(_response.data);
          this.updateToken(_response.token);
          return _response.status;
        }));
    } else {
      return of(false);
    }
  }

Body:
try implementing CanActivateChild also -

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(route, state);
}


来源: stackexchange

问:
Webdriver.io session not created: Unable to create new service: GeckoDriverService
I am running my initial project setup for Webdriver.io, I was able to run tests earlier but now getting errors which are related to geckodrivers or capabilities I am not understanding.

I have tried finding an issue with geckodriver and finding geckodriver version in that I am getting some errors as below:

geckodriver -v
1559030261896   geckodriver ERROR   Address in use (os error 98)

wdio.conf.js:

```<code>exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/test-specs/**/*.specs.js'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    maxInstancesPerCapability: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{
        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        //maxInstances: 5,
        //
        browserName: 'firefox',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'error',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
        // webdriver: 'info',
        // '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: '<my base url>',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if Selenium Grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 3,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['selenium-standalone'],
    //
    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'mocha',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec'],

    //
    // Options to be passed to Mocha.
    // See the full list at http://mochajs.org/
    mochaOpts: {
        ui: 'bdd',
        timeout: 100000
    },
    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // before: function (capabilities, specs) {
    // },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },

    /**
     * Hook that gets executed before the suite starts
     * @param {Object} suite suite details
     */
    // beforeSuite: function (suite) {
    // },
    /**
     * Function to be executed before a test (in Mocha/Jasmine) or a step (in Cucumber) starts.
     * @param {Object} test test details
     */
    // beforeTest: function (test) {
    // },
    /**
     * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
     * beforeEach in Mocha)
     */
    // beforeHook: function () {
    // },
    /**
     * Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
     * afterEach in Mocha)
     */
    // afterHook: function () {
    // },
    /**
     * Function to be executed after a test (in Mocha/Jasmine) or a step (in Cucumber) starts.
     * @param {Object} test test details
     */
    // afterTest: function (test) {
    // },
    /**
     * Hook that gets executed after the suite has ended
     * @param {Object} suite suite details
     */
    // afterSuite: function (suite) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}

</code>```

Tests should be running with specs file provided. but getting error as below:

```<code>> webdriverio-test@1.0.0 test /home/apaliwal/Solution-Engine-new/new-solution-engine-test
> wdio wdio.conf.js

Execution of 1 spec files started at 2019-05-28T08:04:11.842Z

[0-0] RUNNING in firefox - /test/test-specs/login.specs.js
[0-0] 2019-05-28T08:04:16.698Z ERROR webdriver: Request failed due to session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)
    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)
    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:277:13)
[0-0] 2019-05-28T08:04:16.701Z ERROR @wdio/runner: session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)
    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)
    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:277:13)
0-0 worker error { name: 'session not created',
  message:
   'Unable to create new service: GeckoDriverService\nBuild info: version: \'3.141.59\', revision: \'e82be7d358\', time: \'2018-11-14T08:25:53\'\nSystem info: host: \'localhost.localdomain\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'5.0.16-200.fc29.x86_64\', java.version: \'1.8.0_212\'\nDriver info: driver.version: unknown',
  stack:
   'session not created: Unable to create new service: GeckoDriverService\nBuild info: version: \'3.141.59\', revision: \'e82be7d358\', time: \'2018-11-14T08:25:53\'\nSystem info: host: \'localhost.localdomain\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'5.0.16-200.fc29.x86_64\', java.version: \'1.8.0_212\'\nDriver info: driver.version: unknown\n    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)\n    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)\n    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)\n    at Request.emit (events.js:189:13)\n    at Request.EventEmitter.emit (domain.js:441:20)\n    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)\n    at Request.emit (events.js:189:13)\n    at Request.EventEmitter.emit (domain.js:441:20)\n    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)\n    at Object.onceWrapper (events.js:277:13)' }
[0-0] 2019-05-28T08:04:16.702Z ERROR @wdio/local-runner: Failed launching test session: TypeError: Cannot read property 'capabilities' of null
    at Runner.run (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/@wdio/runner/build/index.js:91:74)
    at process._tickCallback (internal/process/next_tick.js:68:7)
[0-0] FAILED in firefox - /test/test-specs/login.specs.js

Spec Files:  0 passed, 1 failed, 1 total (100% completed) in 00:00:04

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webdriverio-test@1.0.0 test: `wdio wdio.conf.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the webdriverio-test@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/apaliwal/.npm/_logs/2019-05-28T08_04_16_722Z-debug.log
</code>```

答:
The error you are seeing does gives us some hint about whats going wrong as follows :

```<code>ERROR @wdio/runner: session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
</code>```

It is clear from the error message that a new GeckoDriverService is not getting initiated as you see the log message as Driver info: driver.version: unknown. The main reason of this error can be the incompatibility between the binaries you are using.

Your Selenium Client version is 3.141.59.

Your GeckoDriver version  is unknown to us.

Your Firefox browser version  is unknown to us.

Solution

A quick solution would be to :

Update GeckoDriver version to recent levels i.e. GeckoDriver v0.24.0

Update Firefox version to recent levels i.e. Firefox v67.0

Follow the GeckoDriver, Selenium and Firefox Browser compatibility chart as depicted below.

If your base version of Firefox is older uninstall Firefox and install a recent GA released version of Firefox

Execute your Test.

GeckoDriver, Selenium and Firefox Browser compatibility chart

ContentLicense: CC BY-SA 4.0

Body:
I am running my initial project setup for Webdriver.io, I was able to run tests earlier but now getting errors which are related to geckodrivers or capabilities I am not understanding.

I have tried finding an issue with geckodriver and finding geckodriver version in that I am getting some errors as below:

geckodriver -v
1559030261896   geckodriver ERROR   Address in use (os error 98)

wdio.conf.js:

exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/test-specs/**/*.specs.js'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    maxInstancesPerCapability: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{
        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        //maxInstances: 5,
        //
        browserName: 'firefox',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'error',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
        // webdriver: 'info',
        // '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: '<my base url>',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if Selenium Grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 3,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['selenium-standalone'],
    //
    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'mocha',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec'],

    //
    // Options to be passed to Mocha.
    // See the full list at http://mochajs.org/
    mochaOpts: {
        ui: 'bdd',
        timeout: 100000
    },
    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // before: function (capabilities, specs) {
    // },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },

    /**
     * Hook that gets executed before the suite starts
     * @param {Object} suite suite details
     */
    // beforeSuite: function (suite) {
    // },
    /**
     * Function to be executed before a test (in Mocha/Jasmine) or a step (in Cucumber) starts.
     * @param {Object} test test details
     */
    // beforeTest: function (test) {
    // },
    /**
     * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
     * beforeEach in Mocha)
     */
    // beforeHook: function () {
    // },
    /**
     * Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
     * afterEach in Mocha)
     */
    // afterHook: function () {
    // },
    /**
     * Function to be executed after a test (in Mocha/Jasmine) or a step (in Cucumber) starts.
     * @param {Object} test test details
     */
    // afterTest: function (test) {
    // },
    /**
     * Hook that gets executed after the suite has ended
     * @param {Object} suite suite details
     */
    // afterSuite: function (suite) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}

Tests should be running with specs file provided. but getting error as below:

> webdriverio-test@1.0.0 test /home/apaliwal/Solution-Engine-new/new-solution-engine-test
> wdio wdio.conf.js

Execution of 1 spec files started at 2019-05-28T08:04:11.842Z

[0-0] RUNNING in firefox - /test/test-specs/login.specs.js
[0-0] 2019-05-28T08:04:16.698Z ERROR webdriver: Request failed due to session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)
    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)
    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:277:13)
[0-0] 2019-05-28T08:04:16.701Z ERROR @wdio/runner: session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)
    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)
    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:189:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:277:13)
0-0 worker error { name: 'session not created',
  message:
   'Unable to create new service: GeckoDriverService\nBuild info: version: \'3.141.59\', revision: \'e82be7d358\', time: \'2018-11-14T08:25:53\'\nSystem info: host: \'localhost.localdomain\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'5.0.16-200.fc29.x86_64\', java.version: \'1.8.0_212\'\nDriver info: driver.version: unknown',
  stack:
   'session not created: Unable to create new service: GeckoDriverService\nBuild info: version: \'3.141.59\', revision: \'e82be7d358\', time: \'2018-11-14T08:25:53\'\nSystem info: host: \'localhost.localdomain\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'5.0.16-200.fc29.x86_64\', java.version: \'1.8.0_212\'\nDriver info: driver.version: unknown\n    at getErrorFromResponseBody (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/utils.js:349:10)\n    at Request._callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/webdriver/build/request.js:121:64)\n    at Request.self.callback (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:185:22)\n    at Request.emit (events.js:189:13)\n    at Request.EventEmitter.emit (domain.js:441:20)\n    at Request.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1161:10)\n    at Request.emit (events.js:189:13)\n    at Request.EventEmitter.emit (domain.js:441:20)\n    at IncomingMessage.<anonymous> (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/request/request.js:1083:12)\n    at Object.onceWrapper (events.js:277:13)' }
[0-0] 2019-05-28T08:04:16.702Z ERROR @wdio/local-runner: Failed launching test session: TypeError: Cannot read property 'capabilities' of null
    at Runner.run (/home/apaliwal/Solution-Engine-new/new-solution-engine-test/node_modules/@wdio/runner/build/index.js:91:74)
    at process._tickCallback (internal/process/next_tick.js:68:7)
[0-0] FAILED in firefox - /test/test-specs/login.specs.js

Spec Files:  0 passed, 1 failed, 1 total (100% completed) in 00:00:04

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webdriverio-test@1.0.0 test: `wdio wdio.conf.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the webdriverio-test@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/apaliwal/.npm/_logs/2019-05-28T08_04_16_722Z-debug.log

Body:
The error you are seeing does gives us some hint about whats going wrong as follows :

ERROR @wdio/runner: session not created: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'localhost.localdomain', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.0.16-200.fc29.x86_64', java.version: '1.8.0_212'
Driver info: driver.version: unknown

It is clear from the error message that a new GeckoDriverService is not getting initiated as you see the log message as Driver info: driver.version: unknown. The main reason of this error can be the incompatibility between the binaries you are using.

Your Selenium Client version is 3.141.59.

Your GeckoDriver version  is unknown to us.

Your Firefox browser version  is unknown to us.

Solution

A quick solution would be to :

Update GeckoDriver version to recent levels i.e. GeckoDriver v0.24.0

Update Firefox version to recent levels i.e. Firefox v67.0

Follow the GeckoDriver, Selenium and Firefox Browser compatibility chart as depicted below.

If your base version of Firefox is older uninstall Firefox and install a recent GA released version of Firefox

Execute your Test.

GeckoDriver, Selenium and Firefox Browser compatibility chart


问:
Issue "Could not fetch/save url https://download.docker.com/linux/centos/docker-ce.repo"
I am trying to set up the Docker repository on CentOS, after I run the command

```<code>$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
</code>```

I am getting error message:

Could not fetch/save url
  https://download.docker.com/linux/centos/docker-ce.repo to file
  /etc/yum.repos.d/docker-ce.repo: [Errno 12] Timeout on
  https://download.docker.com/linux/centos/docker-ce.repo: (28,
  'Operation timed out after 30005 milliseconds with 0 out of 0 bytes
  received')

I am following the docker documentation to set up the repository.

Step 1: Install required packages. yum-utils provides the yum-config-manager utility, and device-mapper-persistent-data and lvm2 are required by the devicemapper storage driver.

```<code>$ sudo yum install -y yum-utils device-mapper-persistent-data lvm2
</code>```

Step 2: Use the following command to set up the stable repository.

```<code>$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
</code>```

Expected result: System should download the files.

Actual result: Not able to download the files.

答:
I have the same problem but I solved it by updating the yum config file, just add timeout=120 to /etc/yum.conf:

```<code>cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_report_page.php?category=yum
distroverpkg=centos-release

#add timeout here
timeout=120

</code>```

Set timeout to 2 min (or 3 min = 180), restart the server then re-run your command.

NOTE: you need to edit the yum.conf file as a super user in order to be able to save your changes.

To switch to super user run next:

```<code>sudo -i
</code>```

To edit your file and save the changes use the nano editor (or Vi).

I think that it is not necessarily a good solution but it worked well for me.

Should help!

Body:
I am trying to set up the Docker repository on CentOS, after I run the command

$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

I am getting error message:

Could not fetch/save url
  https://download.docker.com/linux/centos/docker-ce.repo to file
  /etc/yum.repos.d/docker-ce.repo: [Errno 12] Timeout on
  https://download.docker.com/linux/centos/docker-ce.repo: (28,
  'Operation timed out after 30005 milliseconds with 0 out of 0 bytes
  received')

I am following the docker documentation to set up the repository.

Step 1: Install required packages. yum-utils provides the yum-config-manager utility, and device-mapper-persistent-data and lvm2 are required by the devicemapper storage driver.

$ sudo yum install -y yum-utils device-mapper-persistent-data lvm2

Step 2: Use the following command to set up the stable repository.

$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

Expected result: System should download the files.

Actual result: Not able to download the files.

Body:
I have the same problem but I solved it by updating the yum config file, just add timeout=120 to /etc/yum.conf:

cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_report_page.php?category=yum
distroverpkg=centos-release

#add timeout here
timeout=120

Set timeout to 2 min (or 3 min = 180), restart the server then re-run your command.

NOTE: you need to edit the yum.conf file as a super user in order to be able to save your changes.

To switch to super user run next:

sudo -i

To edit your file and save the changes use the nano editor (or Vi).

I think that it is not necessarily a good solution but it worked well for me.

Should help!


问:
Using Threejs + OrbitContols in TypeScript
I'm not able to get this example of using the aforementioned combo going in TypeScript.

I have  and  in my html  and the typescript file in :

```<code>/// <reference path="lib\three.d.ts" />
...
this.controls = new THREE.OrbitControls(this.camera); //there's the error
this.controls.addEventListener('change', this.render);
...
</code>```

and

```<code>this.controls.update();
</code>```

in periodically called render() function. For all I know, the setup is identical to the expample, but gives me a huge error (abbreviated) on compilation of the OrbitControls constructor line:

```<code>The property 'OrbitControls' does not exist on value of type '{REVISION:string;
CullFace: {[x: number ...
</code>```

I guess there's whole Threejs in that error, since Visual Studio crashes the moment I click on it :). Thanks for your help.

答:
As described in the docs do the following:

```<code>import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
</code>```

Important is that you use the folder jsm instead of js. And keep in mind that not all modules are available in the jsm folder yet

ContentLicense: CC BY-SA 3.0

Body:
I'm not able to get this example of using the aforementioned combo going in TypeScript.

I have  and  in my html  and the typescript file in :

/// <reference path="lib\three.d.ts" />
...
this.controls = new THREE.OrbitControls(this.camera); //there's the error
this.controls.addEventListener('change', this.render);
...

and

this.controls.update();

in periodically called render() function. For all I know, the setup is identical to the expample, but gives me a huge error (abbreviated) on compilation of the OrbitControls constructor line:

The property 'OrbitControls' does not exist on value of type '{REVISION:string;
CullFace: {[x: number ...

I guess there's whole Threejs in that error, since Visual Studio crashes the moment I click on it :). Thanks for your help.

Body:
As described in the docs do the following:

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

Important is that you use the folder jsm instead of js. And keep in mind that not all modules are available in the jsm folder yet


问:
How to hold collection of files throughout application?
In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the collection:

view all/individual files

upload subsets of the collection to a server

share individual files

...

The collection is initialized only once.

I was wondering if it is a good idea to use a singleton pattern as an object that holds the collection so I do not have to initialize the collection every time user opens a particular screen?

答: If collection is initialized only once then use singleton. No doubt. </p>


问:
Should I dispose of X509Certificate2?
I'm using IdentityServer4 and I want to load signing certificate from file. For example,

```<code>var certificate = new X509Certificate2(
        path,
        password,
        X509KeyStorageFlags.EphemeralKeySet);

services.AddIdentityServer()
        .AddSigningCredential(certificate)
...
certificate.Dispose();
</code>```

The code above won't work when I request the token from IdentityServer. But it will work in case I remove certificate.Dispose();.

I also tried another option. I created RsaSecurityKey from certificate's private key and used it for adding signing credential. And in this case disposing will not break anything.

```<code>var rsk = new RsaSecurityKey(certificate.GetRSAPrivateKey()))

services.AddIdentityServer()
        .AddSigningCredential(rsk)
...
certificate.Dispose()
</code>```

So my question is more general. Should I dispose X509Certificate2 object created from the existing certificate?

From Microsoft Docs:

Starting with the .NET Framework 4.6, this type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly.

答: No, you should not dispose certificate object while the application runs, because when requested, IdentityServer will attempt to use disposed certificate object and will fail.</p>

Title: Should I dispose of X509Certificate2?

Body:
I'm using IdentityServer4 and I want to load signing certificate from file. For example,

var certificate = new X509Certificate2(
        path,
        password,
        X509KeyStorageFlags.EphemeralKeySet);

services.AddIdentityServer()
        .AddSigningCredential(certificate)
...
certificate.Dispose();

The code above won't work when I request the token from IdentityServer. But it will work in case I remove certificate.Dispose();.

I also tried another option. I created RsaSecurityKey from certificate's private key and used it for adding signing credential. And in this case disposing will not break anything.

var rsk = new RsaSecurityKey(certificate.GetRSAPrivateKey()))

services.AddIdentityServer()
        .AddSigningCredential(rsk)
...
certificate.Dispose()

So my question is more general. Should I dispose X509Certificate2 object created from the existing certificate?

From Microsoft Docs:

Starting with the .NET Framework 4.6, this type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly.


问:
Draw rhombus inscribed in a group with circle SVG
I have multiple <g> elements and all of them have a circle:

```<code><g class="my-group">
    <circle r="40" cx="10" cy="10"></circle>
</g>
</code>```

In some cases I need to draw a rectange with rounded corners instead of circle, it should be presented as rhombus. I'm trying to draw it like this:

```<code><g class="my-group">
    <rect x="-16" y="-30" width="60" height="60" fill="red" transform="rotate(45)" rx="4"></rect>
</g>
</code>```

But this is a wrong way to hardcode coordinates and width/height of rect.

How I can calculate width and height of rotated rect to inscribe it in circle, so group will have the same width and height 80px.

答:
Simple pythagorean theorem. Rectangle width  (or hypotenuse) equals the square root of two lots of the radius squared.

const radius = document.querySelector('#circle').getAttribute('r')
const rectWidth = Math.sqrt(radius * radius * 2)
const square = document.querySelector('#square')

square.setAttribute('x', -rectWidth/2 + 'px')
square.setAttribute('y', -rectWidth/2 + 'px')
square.setAttribute('width', rectWidth + 'px')
square.setAttribute('height', rectWidth + 'px')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  width: 100vmin;
  height: 100vmin;
}</code>```

<svg viewbox="0 0 100 100">
    <circle id="circle" fill="green" r="40" cx="50" cy="50"></circle>
    <rect id="square" fill="red" transform="translate(50, 50) rotate(45)"></rect></svg>```

Body:
I have multiple <g> elements and all of them have a circle:

<g class="my-group">
    <circle r="40" cx="10" cy="10"></circle>
</g>

In some cases I need to draw a rectange with rounded corners instead of circle, it should be presented as rhombus. I'm trying to draw it like this:

<g class="my-group">
    <rect x="-16" y="-30" width="60" height="60" fill="red" transform="rotate(45)" rx="4"></rect>
</g>

But this is a wrong way to hardcode coordinates and width/height of rect.

How I can calculate width and height of rotated rect to inscribe it in circle, so group will have the same width and height 80px.

Body:
Simple pythagorean theorem. Rectangle width  (or hypotenuse) equals the square root of two lots of the radius squared.

const radius = document.querySelector('#circle').getAttribute('r')
const rectWidth = Math.sqrt(radius * radius * 2)
const square = document.querySelector('#square')

square.setAttribute('x', -rectWidth/2 + 'px')
square.setAttribute('y', -rectWidth/2 + 'px')
square.setAttribute('width', rectWidth + 'px')
square.setAttribute('height', rectWidth + 'px')

svg {
  width: 100vmin;
  height: 100vmin;
}

<svg viewbox="0 0 100 100">
    <circle id="circle" fill="green" r="40" cx="50" cy="50"></circle>
    <rect id="square" fill="red" transform="translate(50, 50) rotate(45)"></rect></svg>


问:
Getting 502 Bad Gateway from CouchDB v2.2.0 and beam.smp restarted every time with new PID
Getting 502 Bad Gateway from CouchDB (v2.2.0) and beam.smp restarted every time with new PID. Sometimes I am getting 200 OK response.

I am experiencing this issue from last 2 days(note: I was using this system from last 1.5yrs without any issues) and getting below error from couchdb.log.

The action I have taken is "Restart the machine along with CouchDB". But it did not help me.

```<code>     state: {os_proc,"bash /tmp/baby",#Port<0.8007>,#Fun<couch_os_process.writejson.2>,#Fun<couch_os_process.readjson.1>,5000,300000}
[error] 2019-05-27T09:25:22.821551Z couchdb@127.0.0.1 <0.1306.0> -------- Update notificatio process <0.1307.0> died: {exit_status,127}
[error] 2019-05-27T09:25:22.821834Z couchdb@127.0.0.1 <0.1307.0> -------- CRASH REPORT Process  (<0.1307.0>) with 0 neighbors exited with reason: {exit_status,127} at gen_server:terminate/7(line:826) <= proc_lib:init_p_do_apply/3(line:240); initial_call: {couch_os_process,init,['Argument__1']}, ancestors: [<0.1306.0>,couch_event_os_sup,couch_event_sup2,...], messages: [], links: [<0.1306.0>], dictionary: [], trap_exit: false, status: running, heap_size: 987, stack_size: 27, reductions: 807
[error] 2019-05-27T09:25:22.821948Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1306.0> exit with reason normal in context child_terminated
[error] 2019-05-27T09:25:22.834620Z couchdb@127.0.0.1 <0.1317.0> -------- OS Process died with status: 127
[error] 2019-05-27T09:25:22.834864Z couchdb@127.0.0.1 <0.1317.0> -------- gen_server <0.1317.0> terminated with reason: {exit_status,127}
  last msg: {#Port<0.8012>,{exit_status,127}}
     state: {os_proc,"bash /tmp/baby",#Port<0.8012>,#Fun<couch_os_process.writejson.2>,#Fun<couch_os_process.readjson.1>,5000,300000}
[error] 2019-05-27T09:25:22.834934Z couchdb@127.0.0.1 <0.1316.0> -------- Update notificatio process <0.1317.0> died: {exit_status,127}
[error] 2019-05-27T09:25:22.835131Z couchdb@127.0.0.1 <0.1317.0> -------- CRASH REPORT Process  (<0.1317.0>) with 0 neighbors exited with reason: {exit_status,127} at gen_server:terminate/7(line:826) <= proc_lib:init_p_do_apply/3(line:240); initial_call: {couch_os_process,init,['Argument__1']}, ancestors: [<0.1316.0>,couch_event_os_sup,couch_event_sup2,...], messages: [], links: [<0.1316.0>], dictionary: [], trap_exit: false, status: running, heap_size: 987, stack_size: 27, reductions: 807
[error] 2019-05-27T09:25:22.835279Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1316.0> exit with reason normal in context child_terminated
[error] 2019-05-27T09:25:22.835602Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1316.0> exit with reason reached_max_restart_intensity in context shutdown
[error] 2019-05-27T09:25:22.835963Z couchdb@127.0.0.1 <0.181.0> -------- Supervisor couch_event_sup2 had child couch_event_os_sup started with couch_event_os_sup:start_link() at <0.1199.0> exit with reason shutdown in context child_terminated
[error] 2019-05-27T09:25:22.836219Z couchdb@127.0.0.1 <0.181.0> -------- Supervisor couch_event_sup2 had child couch_event_os_sup started with couch_event_os_sup:start_link() at <0.1199.0> exit with reason reached_max_restart_intensity in context shutdown
[info] 2019-05-27T09:25:22.838955Z couchdb@127.0.0.1 <0.7.0> -------- Application couch_event exited with reason: shutdown
[error] 2019-05-27T09:25:22.853663Z couchdb@127.0.0.1 <0.323.0> -------- gen_server <0.323.0> terminated with reason: killed
</code>```

答:
I removed below line from this file /opt/couchdb/etc/local.d/10-admins.ini and restart CouchDB. Then It worked nicely.

```<code>[update_notification]
index-updater = bash /tmp/baby
</code>```

Reason:

This was probably triggered by someone trying to use your machine as a Bitcoin miner or similar through one of the known exploitable holes in CouchDB 2.2.0. These are summarized here: http://docs.couchdb.org/en/stable/cve/index.html

Better to Upgrade to CouchDB 2.3.0 or 2.3.1 as soon as possible.

Body:
Getting 502 Bad Gateway from CouchDB (v2.2.0) and beam.smp restarted every time with new PID. Sometimes I am getting 200 OK response.

I am experiencing this issue from last 2 days(note: I was using this system from last 1.5yrs without any issues) and getting below error from couchdb.log.

The action I have taken is "Restart the machine along with CouchDB". But it did not help me.

     state: {os_proc,"bash /tmp/baby",#Port<0.8007>,#Fun<couch_os_process.writejson.2>,#Fun<couch_os_process.readjson.1>,5000,300000}
[error] 2019-05-27T09:25:22.821551Z couchdb@127.0.0.1 <0.1306.0> -------- Update notificatio process <0.1307.0> died: {exit_status,127}
[error] 2019-05-27T09:25:22.821834Z couchdb@127.0.0.1 <0.1307.0> -------- CRASH REPORT Process  (<0.1307.0>) with 0 neighbors exited with reason: {exit_status,127} at gen_server:terminate/7(line:826) <= proc_lib:init_p_do_apply/3(line:240); initial_call: {couch_os_process,init,['Argument__1']}, ancestors: [<0.1306.0>,couch_event_os_sup,couch_event_sup2,...], messages: [], links: [<0.1306.0>], dictionary: [], trap_exit: false, status: running, heap_size: 987, stack_size: 27, reductions: 807
[error] 2019-05-27T09:25:22.821948Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1306.0> exit with reason normal in context child_terminated
[error] 2019-05-27T09:25:22.834620Z couchdb@127.0.0.1 <0.1317.0> -------- OS Process died with status: 127
[error] 2019-05-27T09:25:22.834864Z couchdb@127.0.0.1 <0.1317.0> -------- gen_server <0.1317.0> terminated with reason: {exit_status,127}
  last msg: {#Port<0.8012>,{exit_status,127}}
     state: {os_proc,"bash /tmp/baby",#Port<0.8012>,#Fun<couch_os_process.writejson.2>,#Fun<couch_os_process.readjson.1>,5000,300000}
[error] 2019-05-27T09:25:22.834934Z couchdb@127.0.0.1 <0.1316.0> -------- Update notificatio process <0.1317.0> died: {exit_status,127}
[error] 2019-05-27T09:25:22.835131Z couchdb@127.0.0.1 <0.1317.0> -------- CRASH REPORT Process  (<0.1317.0>) with 0 neighbors exited with reason: {exit_status,127} at gen_server:terminate/7(line:826) <= proc_lib:init_p_do_apply/3(line:240); initial_call: {couch_os_process,init,['Argument__1']}, ancestors: [<0.1316.0>,couch_event_os_sup,couch_event_sup2,...], messages: [], links: [<0.1316.0>], dictionary: [], trap_exit: false, status: running, heap_size: 987, stack_size: 27, reductions: 807
[error] 2019-05-27T09:25:22.835279Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1316.0> exit with reason normal in context child_terminated
[error] 2019-05-27T09:25:22.835602Z couchdb@127.0.0.1 <0.1199.0> -------- Supervisor couch_event_os_sup had child "index-updater" started with couch_event_os_listener:start_link("bash /tmp/baby") at <0.1316.0> exit with reason reached_max_restart_intensity in context shutdown
[error] 2019-05-27T09:25:22.835963Z couchdb@127.0.0.1 <0.181.0> -------- Supervisor couch_event_sup2 had child couch_event_os_sup started with couch_event_os_sup:start_link() at <0.1199.0> exit with reason shutdown in context child_terminated
[error] 2019-05-27T09:25:22.836219Z couchdb@127.0.0.1 <0.181.0> -------- Supervisor couch_event_sup2 had child couch_event_os_sup started with couch_event_os_sup:start_link() at <0.1199.0> exit with reason reached_max_restart_intensity in context shutdown
[info] 2019-05-27T09:25:22.838955Z couchdb@127.0.0.1 <0.7.0> -------- Application couch_event exited with reason: shutdown
[error] 2019-05-27T09:25:22.853663Z couchdb@127.0.0.1 <0.323.0> -------- gen_server <0.323.0> terminated with reason: killed

Body:
I removed below line from this file /opt/couchdb/etc/local.d/10-admins.ini and restart CouchDB. Then It worked nicely.

[update_notification]
index-updater = bash /tmp/baby

Reason:

This was probably triggered by someone trying to use your machine as a Bitcoin miner or similar through one of the known exploitable holes in CouchDB 2.2.0. These are summarized here: http://docs.couchdb.org/en/stable/cve/index.html

Better to Upgrade to CouchDB 2.3.0 or 2.3.1 as soon as possible.


问:
How to fix 'list index out of range' error in python?
I'm setting up the RFID reader for the attendance system. But when I place my tag to the reader, it was interrupted with the Tag id - which I externally stored to a database.</p>

```<code>#//////place your tag//////

print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

(error, uid) = rdr.anticoll()
if not error:
    print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])

print("Written..!")
print(tagid)

cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
connection.commit()
print("Data was successfully Added...!")

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
IndexError: list index out of range
</code>```

答:
Your code structure is not correct. Try to indent rdr.anticoll() with this whenever the tag request is incorrect no process will occur.

Try the line of codes for better visualization:

```<code>print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

    (error, uid) = rdr.anticoll()
    if not error:
        print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

        tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])

        print("Written..!")
        print(tagid)
        cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
        connection.commit()
        print("Data was successfully Added...!")
else:
    print("Unsuccessful")
</code>```

Body:
I'm setting up the RFID reader for the attendance system. But when I place my tag to the reader, it was interrupted with the Tag id - which I externally stored to a database.

#//////place your tag//////

print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

(error, uid) = rdr.anticoll()
if not error:
    print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])

print("Written..!")
print(tagid)

cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
connection.commit()
print("Data was successfully Added...!")

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
IndexError: list index out of range

Body:
Your code structure is not correct. Try to indent rdr.anticoll() with this whenever the tag request is incorrect no process will occur.

Try the line of codes for better visualization:

print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

    (error, uid) = rdr.anticoll()
    if not error:
        print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

        tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])

        print("Written..!")
        print(tagid)
        cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
        connection.commit()
        print("Data was successfully Added...!")
else:
    print("Unsuccessful")


问:
Match text in another dataframe and fill missing columns with recognized entity
I want to fill missing Nan in a dataframe with recognized keywords from another dataframe.

```<code>    import pandas as pd
import numpy as np
df1 = pd.DataFrame({'models': ['A3', '520', 'clio3', 'C3']})
df2 = pd.DataFrame({'description': ['I am selling a Citroen C3', 'I sell my Audi A3'], 'model': [np.nan, np.nan]})
</code>```

Update:
this case

```<code>df2 = pd.DataFrame({'description': ['I am selling a BMW 520 with good condition', 'I sell my Audi very good', 'clio3 for sale'], 'model': [np.nan,'A3', np.nan]})
</code>```

should not replace 'A3'.

Expected result

答:
Use s.str.extract() with a pattern:

```<code>df2.model=df2.description.str.extract(r'({})'.format('|'.join(df1.models)),expand=False)
print(df2)
</code>```

```<code>                 description model
0  I am selling a Citroen C3    C3
1          I sell my Audi A3    A3
</code>```

Where:r'({})'.format('|'.join(df1.models)) gives '(A3|520|clio3|C3)'

Body:
I want to fill missing Nan in a dataframe with recognized keywords from another dataframe.

    import pandas as pd
import numpy as np
df1 = pd.DataFrame({'models': ['A3', '520', 'clio3', 'C3']})
df2 = pd.DataFrame({'description': ['I am selling a Citroen C3', 'I sell my Audi A3'], 'model': [np.nan, np.nan]})

Update:
this case

df2 = pd.DataFrame({'description': ['I am selling a BMW 520 with good condition', 'I sell my Audi very good', 'clio3 for sale'], 'model': [np.nan,'A3', np.nan]})

should not replace 'A3'.

Expected result

Body:
Use s.str.extract() with a pattern:

df2.model=df2.description.str.extract(r'({})'.format('|'.join(df1.models)),expand=False)
print(df2)

                 description model
0  I am selling a Citroen C3    C3
1          I sell my Audi A3    A3

Where:r'({})'.format('|'.join(df1.models)) gives '(A3|520|clio3|C3)'


问:
Passing ecrypted id in url parameter using javascript
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

```<code>var action= id;

localhost/data.php?action=encrypt(id)
</code>```

答:
```<code><script>
var encodedData = window.btoa(1); // encode a string
var decodedData = window.atob(encodedData); // decode the string
alert(encodedData);
</script>
</code>```

You can try above functions to encode and decode

Body:
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

var action= id;

localhost/data.php?action=encrypt(id)

Body:
<script>
var encodedData = window.btoa(1); // encode a string
var decodedData = window.atob(encodedData); // decode the string
alert(encodedData);
</script>

You can try above functions to encode and decode


问:
BasicAuthenticationFilter is not getting called if authorization is not passed with header while making request
I am trying to authenticate each incoming HTTP request using JWT token. For that, I have implemented the AuthenticationProvider interface(by overriding authenticate function) provided by spring security. But the authenticate function is getting called only if we pass authorization parameters along with headers, else the request is getting processed without going in to authenticate function flow.

答:
Spring security intercepts the header with authorization parameter in it .

For more knowledge refer to How authentication works


问:
How to use an variable of Object Observable inside another Observable subscribe function - RxJava
I have two observables of different types which emit two different types of Objects. But I need to update analytics on a successful login with userId and role. User Id is already set in viewModel login function call on successful login.

```<code>                       viewModel.login(emailId)
                                .observeOn(AndroidSchedulers.mainThread())
                                .autoDisposable(scopeProvider)
                                .subscribe({ (role, images) ->
                                analyticsProvider.updateUser(mapOf(Constants.Role to role,
Constants.userId to *NEED TO ENTER USER ID FROM OTHER OBSERVABLE HERE*)))
</code>```

My Session Observable which emits User object.

```<code> class SessionClass{
        private val user = BehaviorSubject.create<User>()
        override fun setUser(user: User) {
                this.user.onNext(user)
            }
         override fun getUser(): Observable<User> = user.hide()
    }
</code>```

I tried to call SessionClass().getUser().blockingFirst().userId at that place but the phone gets hung at the login screen.

Is there any way I can fix this issue?

答:
Your solution does not work simply because you immediately instantiate a SessionClass and never call setUser(), so getUser().blockingFirst() will block forever. I will assume that you have an instance of SessionClass which will actually have setUser() called at some point.

The key to having access to the user there is to combine the Observables. The appropriate choice in this situation is the zipWith operator. This will allow you to operate on the values from two sources at once. For example, your code might look something like this:

```<code>val session: SessionClass = TODO() // get an instance somewhere

viewModel.login(emailId)
    .observeOn(AndroidSchedulers.mainThread())
    .zipWith(session.getUser().firstOrError(), BiFunction { (role, images): Pair<Role, Images>, user: User -> Triple(role, images, user) })
    .autoDisposable(scopeProvider)
    .subscribe({ (role, images, user) ->
        analyticsProvider.updateUser(mapOf(Constants.Role to role, Constants.userId to user.userId))
    })))

</code>```

Body:
I have two observables of different types which emit two different types of Objects. But I need to update analytics on a successful login with userId and role. User Id is already set in viewModel login function call on successful login.

                       viewModel.login(emailId)
                                .observeOn(AndroidSchedulers.mainThread())
                                .autoDisposable(scopeProvider)
                                .subscribe({ (role, images) ->
                                analyticsProvider.updateUser(mapOf(Constants.Role to role,
Constants.userId to *NEED TO ENTER USER ID FROM OTHER OBSERVABLE HERE*)))

My Session Observable which emits User object.

 class SessionClass{
        private val user = BehaviorSubject.create<User>()
        override fun setUser(user: User) {
                this.user.onNext(user)
            }
         override fun getUser(): Observable<User> = user.hide()
    }

I tried to call SessionClass().getUser().blockingFirst().userId at that place but the phone gets hung at the login screen.

Is there any way I can fix this issue?

Body:
Your solution does not work simply because you immediately instantiate a SessionClass and never call setUser(), so getUser().blockingFirst() will block forever. I will assume that you have an instance of SessionClass which will actually have setUser() called at some point.

The key to having access to the user there is to combine the Observables. The appropriate choice in this situation is the zipWith operator. This will allow you to operate on the values from two sources at once. For example, your code might look something like this:

val session: SessionClass = TODO() // get an instance somewhere

viewModel.login(emailId)
    .observeOn(AndroidSchedulers.mainThread())
    .zipWith(session.getUser().firstOrError(), BiFunction { (role, images): Pair<Role, Images>, user: User -> Triple(role, images, user) })
    .autoDisposable(scopeProvider)
    .subscribe({ (role, images, user) ->
        analyticsProvider.updateUser(mapOf(Constants.Role to role, Constants.userId to user.userId))
    })))


问:
PHP: allow_url_include
Quick...possibly stupid question.

When allow_url_include is set to off, does that prohibit other computers from remotely including the files on my site, or does it say that I'm not allowed to remotely include files from other sites?

答:
Setting allow_url_include to off in your configuration means that your PHP code on your server will not be able to include remote files.

But it doesn't change anything for other servers, which might request files from your server, like anyone can from the web -- note, though, that if some PHP file is requested, it'll be interpreted, and its output (not its content ! ) will be sent.

Title: PHP: allow_url_include


问:
How to fix Response body error '{"error":"invalid_scope","error_description":"Scope must be specified"}'
Our client has given us their end point and when we are try to hit their API we are getting below Error

'{"error":"invalid_scope","error_description":"Scope must be
  specified"}'

答: It seems that your API is not getting hit properly.Use Postman to call the API and enter the proper parameter.If your API is correct and you are passing the correct parameter it will work.</p>


问:
Retrofit2 call.enqueue(new Callback<ServerResponse>() is not working in android 9 and crash the app without any Error in the logcat
I'm Parsing some data from the server by Retrofit2. In other versions of Android and emulator, it is working fine. But the problem is it is not working in Android 9 (Pie) and Android Oreo (8.1). For this reason, the app is going to crash every time I installed. Another problem is, it's not showing any Error in the Logcat. So what can be the solution?

By reading some blogs and Stack Overflow, I have tried by adding android:usesCleartextTraffic="true" in the AndroidManifest. I have also added the below file in the AndroidManifest.

```<code>android:networkSecurityConfig="@xml/network_security_config"
</code>```

where network_security_config file is

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">116.203.27.235/</domain>
    </domain-config>
</network-security-config>
</code>```

Here is the request code I made:

```<code>ApiInterface api = retrofit.create(ApiInterface.class);
Call<ServerResponse> call = api.getServerResult(new String(encodeValue));

call.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(@NonNull Call<ServerResponse> call, @NonNull Response<ServerResponse> response) {
            Log.i(TAG, "onResponse: " + response.message());
            progressBar.setVisibility(View.GONE);
            ServerResponse server = response.body();
            Log.i(TAG, "response callback");
            if (server != null) {
                for (Result result : server.getResults()) {
                    Log.i("server", result.getHostName());
                    Log.i("server", result.getIP());
                    Log.i("server", result.getScore());
                    Log.i("server", result.getLatency());
                    Log.i("server", result.getCountryLong());
                    Log.i("server", result.getCountryShort());

                    data.add(result.getCountryLong());
                    progressBar.setVisibility(View.GONE);
                    flagLink.add("http://v4v.info/countryflag/" + result.getCountryShort().toLowerCase() + ".png");
                }

                //Log.i(TAG, "onResponse: " + flagLink);

                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                MyAdapter adapter = new MyAdapter(getActivity(), data, flagLink);
                recyclerView.setAdapter(adapter);
            }
        }

        @Override
        public void onFailure(@NonNull Call<ServerResponse> call, @NonNull Throwable t) {
            Log.i(TAG, "onFailure: " + t.getMessage());
        }
    });
</code>```

This is working for another version of android like android API 24 and others but not in Android 9(Pie) and Android Oreo (8.1). I want to run this in the Android 9(Pie) and Oreo (8.1).

答:
If you are NOT using https, you can try my solution
in Manifest, add this line to application tag

```<code><application...>
      android:networkSecurityConfig="@xml/network_security_config"
</application>
</code>```

then file network_security_config.xlm could be

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"/>
    <debug-overrides>
        <trust-anchors>
            <!-- Trust user added CAs while debuggable only -->
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>
</code>```

Body:
I'm Parsing some data from the server by Retrofit2. In other versions of Android and emulator, it is working fine. But the problem is it is not working in Android 9 (Pie) and Android Oreo (8.1). For this reason, the app is going to crash every time I installed. Another problem is, it's not showing any Error in the Logcat. So what can be the solution?

By reading some blogs and Stack Overflow, I have tried by adding android:usesCleartextTraffic="true" in the AndroidManifest. I have also added the below file in the AndroidManifest.

android:networkSecurityConfig="@xml/network_security_config"

where network_security_config file is

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">116.203.27.235/</domain>
    </domain-config>
</network-security-config>

Here is the request code I made:

ApiInterface api = retrofit.create(ApiInterface.class);
Call<ServerResponse> call = api.getServerResult(new String(encodeValue));

call.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(@NonNull Call<ServerResponse> call, @NonNull Response<ServerResponse> response) {
            Log.i(TAG, "onResponse: " + response.message());
            progressBar.setVisibility(View.GONE);
            ServerResponse server = response.body();
            Log.i(TAG, "response callback");
            if (server != null) {
                for (Result result : server.getResults()) {
                    Log.i("server", result.getHostName());
                    Log.i("server", result.getIP());
                    Log.i("server", result.getScore());
                    Log.i("server", result.getLatency());
                    Log.i("server", result.getCountryLong());
                    Log.i("server", result.getCountryShort());

                    data.add(result.getCountryLong());
                    progressBar.setVisibility(View.GONE);
                    flagLink.add("http://v4v.info/countryflag/" + result.getCountryShort().toLowerCase() + ".png");
                }

                //Log.i(TAG, "onResponse: " + flagLink);

                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                MyAdapter adapter = new MyAdapter(getActivity(), data, flagLink);
                recyclerView.setAdapter(adapter);
            }
        }

        @Override
        public void onFailure(@NonNull Call<ServerResponse> call, @NonNull Throwable t) {
            Log.i(TAG, "onFailure: " + t.getMessage());
        }
    });

This is working for another version of android like android API 24 and others but not in Android 9(Pie) and Android Oreo (8.1). I want to run this in the Android 9(Pie) and Oreo (8.1).

Body:
If you are NOT using https, you can try my solution
in Manifest, add this line to application tag

<application...>
      android:networkSecurityConfig="@xml/network_security_config"
</application>

then file network_security_config.xlm could be

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"/>
    <debug-overrides>
        <trust-anchors>
            <!-- Trust user added CAs while debuggable only -->
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>


问:
How to add users for windows authentication / IIS
I'm porting a legacy (read ancient) .asp application to a new server for backup purposes. It uses this code to determine the user:

sLogonUser = LCase(Request.ServerVariables("LOGON_USER"))

I believe in order for this field to be populated, I've got to turn on "Windows Integratged Authentication" using IIS Manager. I've done this, but now I get an error message stating "The website cannot be displayed". I think this must have to do with authentication, because even a simple "hello.asp" has the same problem.

This leads me to believe that valid windows users have to be registered on the new server. Is this "Active Directory"? What's the best way to go about adding users?

答:
I believe for this to work the Web server must be on the same domain as the client accessing the web server and the users be created in the domains active directory schema.

The client must use IE for the LOGON_USER to be automatically sent to the server

If you are using IE it may be worth turning off friendly http error messages to see if the server is sending any more detailed information that IE is masking.

This can be done by going to;

Tools -> Internet Options

Select the Advanced Tab

Uncheck the option that says "Show friendly http error messages"

Now reload the page. If there is anymore detailed info there will be an HTTP status code (more than likely 403.x) if you google "http status code " replacing  with the code displayed you should find more information on the problem.

HTH

OwnerDisplayName: Jack BeNimble

ContentLicense: CC BY-SA 2.5


问:
IE7 Compatibility Issues
I'm (obviously) new to web development, and I'm just now realizing that my sites are pretty screwed up in some IE versions, but how do I fix them? How do I know what to change in the CSS and where, when multiple layers and divs aren't displaying properly?

Example: http://www.jwstudio.us/bkpa

Is there a resources for IE CSS fixes/compatibility? What about for the positioning and color differences between Safari/Apple and Windows browsers?

答:
First of all you should be using a reset of some sort. A CSS reset will make the playing field much more level when coding cross-browser.

See: http://developer.yahoo.com/yui/reset/

Ideally you want to avoid using browser-specific style sheets. If you code well you won't need them.

When creating a website you should check it regularly in each browser as you add code. Otherwise you may end up with a snowball effect of poor code. As you become familiar with the IE quirks you'll code cross-browser more efficiently.

Also I would avoid using so many position attributes (i.e. "position: relative"). Your layout is pretty basic; there should be no reason for so many. If you're relying on them so heavily you should reconsider how you structure your code.

Title: IE7 Compatibility Issues


问:
How to navigate to detail page using Flatlist
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

```<code>import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});
</code>```

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.

答:
You can write your function as arrow function:

```<code>renderRow = ({item, index}) => {
    // your code goes here
}
</code>```

Or you can bind the function like this:

```<code>this.renderRow.bind(this);
</code>```

Body:
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.

Body:
You can write your function as arrow function:

renderRow = ({item, index}) => {
    // your code goes here
}

Or you can bind the function like this:

this.renderRow.bind(this);


问:
How to stop TestNG from running after a test fail
I am trying to write a test method in TestNG, that after it fails - the entire test suite will stop running.

```<code>@Test
public void stopTestingIfThisFailed() throws Exception
{
    someTestStesp();
    if (softAsserter.isOneFailed()) {
        asserter.fail("stopTestingIfThisFailed test Failed");
        throw new Exception("Test can't continue, fail here!");
    }
}
</code>```

The exception is being thrown, but other test methods are running.

How to solve this?

答:
I solved the problem like this: after a test that mustn't fail fails - I'm writing data to a temporary text file.

Later, in the next test I added code in the @BeforeClass that checks that data in the former mentioned text file. If a show stopper was found I'm killing the current process.

If a test the "can't" fail actually fails:

```<code> public static void saveShowStopper() {

    try {
        General.createFile("ShowStopper","tempShowStopper.txt");
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
</code>```

The @BeforeClass validating code:

```<code>@BeforeClass(alwaysRun = true)
public void beforeClass(ITestContext testContext, @Optional String step, @Optional String suiteLoopData,
        @Optional String group) throws Exception
{
    boolean wasShowStopperFound = APIUtils.loadShowStopper();
    if (wasShowStopperFound){
        Thread.currentThread().interrupt();
        return;
    }
}
</code>```

Body:
I am trying to write a test method in TestNG, that after it fails - the entire test suite will stop running.

@Test
public void stopTestingIfThisFailed() throws Exception
{
    someTestStesp();
    if (softAsserter.isOneFailed()) {
        asserter.fail("stopTestingIfThisFailed test Failed");
        throw new Exception("Test can't continue, fail here!");
    }
}

The exception is being thrown, but other test methods are running.

How to solve this?

Body:
I solved the problem like this: after a test that mustn't fail fails - I'm writing data to a temporary text file.

Later, in the next test I added code in the @BeforeClass that checks that data in the former mentioned text file. If a show stopper was found I'm killing the current process.

If a test the "can't" fail actually fails:

 public static void saveShowStopper() {

    try {
        General.createFile("ShowStopper","tempShowStopper.txt");
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

The @BeforeClass validating code:

@BeforeClass(alwaysRun = true)
public void beforeClass(ITestContext testContext, @Optional String step, @Optional String suiteLoopData,
        @Optional String group) throws Exception
{
    boolean wasShowStopperFound = APIUtils.loadShowStopper();
    if (wasShowStopperFound){
        Thread.currentThread().interrupt();
        return;
    }
}


问:
Dynamically limit the amount of checkboxes that can be checked by user
I've created a test and answer system. Each question can either have one or multiple answers, e.g "Please mark 1 answer", "Please mark 3 answers" etc.

Is it possible to limit the amount of checkboxes that the user can check based on this? If the question requires 1 answer, then they can only check 1 of the checkboxes.

```<code><?php foreach ($rows as $row){ ?>
   <input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
   <?php echo $row['answer']; ?>
<?php } ?>
</code>```

It loops through this and pulls in each answer, the amount of answers needed for each questions is dynamic and is controlled by this field (where it can be 1, 2, 3 etc):

```<code><?php echo $repeater_row['required_answers']; ?>
</code>```

Using the jquery below, although this isn't dynamic:

```<code>$(document).ready(function () {
    if ($("input:checkbox:checked").length >= 3) {
        $("input:checkbox").not(":checked").attr("disabled", 3);
    }
    $("input:checkbox").click(function () {
        var bol = $("input:checkbox:checked").length >= 3;
        $("input:checkbox").not(":checked").attr("disabled", bol);
    });
});
</code>```

How can I do it dynamically? Each question has it's answers named in sets, so the first question has an answer set called with their inputs named name="answer1[]" the second question has an answer set name="answer2[]" and so on.

答:
```<code>$(document).ready(function()
{
    var limit = 5; // define the limit.
    $('#divID').on('change', '.select_max', function(){ // div in which you will be displaying your data.
      if($('.select_max:checked').length >= limit){ // condition to check the limit you specified
      alert('Limit to select your list has exceeded.');
      this.checked = false; // return false if limit exceeded.
      }
  });
});
</code>```

Body:
I've created a test and answer system. Each question can either have one or multiple answers, e.g "Please mark 1 answer", "Please mark 3 answers" etc.

Is it possible to limit the amount of checkboxes that the user can check based on this? If the question requires 1 answer, then they can only check 1 of the checkboxes.

<?php foreach ($rows as $row){ ?>
   <input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
   <?php echo $row['answer']; ?>
<?php } ?>

It loops through this and pulls in each answer, the amount of answers needed for each questions is dynamic and is controlled by this field (where it can be 1, 2, 3 etc):

<?php echo $repeater_row['required_answers']; ?>

Using the jquery below, although this isn't dynamic:

$(document).ready(function () {
    if ($("input:checkbox:checked").length >= 3) {
        $("input:checkbox").not(":checked").attr("disabled", 3);
    }
    $("input:checkbox").click(function () {
        var bol = $("input:checkbox:checked").length >= 3;
        $("input:checkbox").not(":checked").attr("disabled", bol);
    });
});

How can I do it dynamically? Each question has it's answers named in sets, so the first question has an answer set called with their inputs named name="answer1[]" the second question has an answer set name="answer2[]" and so on.