问:
Schema validation failed
After attempting ionic cordova build android --release
I receive the following error:

```<code>  Data path ".builders['cordova-build']" should have required property 'class'.
</code>```

The app serves to Ionic Labs with working simulations in both ios and android inside the browser but fails on release build.
I have changed "@angular-devkit/build-angular" to a number of different versions as per other answers on stack, to no avail.
This is an existing angular app that I need to wrap in Ionic for native ios/android so I have tried to ensure all dependencies are compatible.

Dev dependencies in package.json:

```<code>"devDependencies": {
    "@angular-devkit/architect": "~0.13.8",
    "@angular-devkit/build-angular": "^0.10.0",
    "@angular-devkit/core": "~7.3.8",
    "@angular-devkit/schematics": "~7.3.8",
    "@angular/cli": "~7.3.8",
    "@angular/compiler": "~7.2.2",
    "@angular/compiler-cli": "~7.2.2",
    "@angular/language-service": "~7.2.2",
    "@ionic/angular-toolkit": "~1.5.1",
    "@ionic/lab": "^2.0.5",
    "@ngrx/schematics": "^7.2.0",
    "@ngrx/store-devtools": "^7.2.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/lodash": "^4.14.123",
    "@types/node": "~12.0.0",
    "codelyzer": "~4.5.0",
    "cordova-plugin-device": "^2.0.3",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^4.1.1",
    "cordova-plugin-splashscreen": "^5.0.3",
    "cordova-plugin-statusbar": "^2.4.3",
    "cordova-plugin-whitelist": "^1.3.4",
    "cz-conventional-changelog": "^2.1.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "jest": "^24.1.0",
    "jest-preset-angular": "^6.0.2",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "opencollective": "^1.0.3",
    "protractor": "~5.4.0",
    "serverless-apigw-binary": "^0.4.4",
    "ts-loader": "4.2.0",
    "ts-node": "~8.3.0",
    "tslint": "~5.17.0",
    "typescript": "~3.1.6",
    "webpack-bundle-analyzer": "^3.3.2",
    "webpack-cli": "^3.1.2"
  },
</code>```

My angular.json:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "defaultProject": "app",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "dfl",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/assets",
                "output": "/"
              },
              {
                "glob": "robots.txt",
                "input": "src/assets/meta",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ],
            "styles": [
              "src/app/styles/styles.scss"
            ],
            "scripts": []

          },
          "configurations": {
            "development": {
              "fileReplacements": [

              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": true,
              "extractCss": true,
              "namedChunks": true,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "integration": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.int.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.int.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.prod.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "serverless": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.serverless.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.serverless.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "baseHref": "/production/",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/app/styles/styles.scss"
            ],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/assets",
                "output": "/"
              },
              {
                "glob": "robots.txt",
                "input": "src/assets/meta",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "development": {
              "optimization": true,
              "sourceMap": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false
            },
            "integration": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.int.ts"
                }
              ]
            },
            "production": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "serverless": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.serverless.ts"
                }
              ]
            }
          }
        }
      }
    },
    "app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  }
}
</code>```

答:
Add the following information in Environment variables.
_JAVA_OPTIONS = -Xmx512M

Update the following packages,
"@ionic/angular-toolkit": "^1.5.1" => For Angular 7
"@ionic/angular-toolkit": "^2.0.1",=> For Angular 8

Title: Schema validation failed

Body:
After attempting ionic cordova build android --release
I receive the following error:

  Data path ".builders['cordova-build']" should have required property 'class'.

The app serves to Ionic Labs with working simulations in both ios and android inside the browser but fails on release build.
I have changed "@angular-devkit/build-angular" to a number of different versions as per other answers on stack, to no avail.
This is an existing angular app that I need to wrap in Ionic for native ios/android so I have tried to ensure all dependencies are compatible.

Dev dependencies in package.json:

"devDependencies": {
    "@angular-devkit/architect": "~0.13.8",
    "@angular-devkit/build-angular": "^0.10.0",
    "@angular-devkit/core": "~7.3.8",
    "@angular-devkit/schematics": "~7.3.8",
    "@angular/cli": "~7.3.8",
    "@angular/compiler": "~7.2.2",
    "@angular/compiler-cli": "~7.2.2",
    "@angular/language-service": "~7.2.2",
    "@ionic/angular-toolkit": "~1.5.1",
    "@ionic/lab": "^2.0.5",
    "@ngrx/schematics": "^7.2.0",
    "@ngrx/store-devtools": "^7.2.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/lodash": "^4.14.123",
    "@types/node": "~12.0.0",
    "codelyzer": "~4.5.0",
    "cordova-plugin-device": "^2.0.3",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^4.1.1",
    "cordova-plugin-splashscreen": "^5.0.3",
    "cordova-plugin-statusbar": "^2.4.3",
    "cordova-plugin-whitelist": "^1.3.4",
    "cz-conventional-changelog": "^2.1.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "jest": "^24.1.0",
    "jest-preset-angular": "^6.0.2",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "opencollective": "^1.0.3",
    "protractor": "~5.4.0",
    "serverless-apigw-binary": "^0.4.4",
    "ts-loader": "4.2.0",
    "ts-node": "~8.3.0",
    "tslint": "~5.17.0",
    "typescript": "~3.1.6",
    "webpack-bundle-analyzer": "^3.3.2",
    "webpack-cli": "^3.1.2"
  },

My angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "defaultProject": "app",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "dfl",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/assets",
                "output": "/"
              },
              {
                "glob": "robots.txt",
                "input": "src/assets/meta",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ],
            "styles": [
              "src/app/styles/styles.scss"
            ],
            "scripts": []

          },
          "configurations": {
            "development": {
              "fileReplacements": [

              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": true,
              "extractCss": true,
              "namedChunks": true,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "integration": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.int.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.int.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.prod.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "serverless": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.serverless.ts"
                },
                {
                  "replace": "src/assets/meta/robots.txt",
                  "with": "src/assets/meta/robots.serverless.txt"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "baseHref": "/production/",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/app/styles/styles.scss"
            ],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/assets",
                "output": "/"
              },
              {
                "glob": "robots.txt",
                "input": "src/assets/meta",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "development": {
              "optimization": true,
              "sourceMap": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false
            },
            "integration": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.int.ts"
                }
              ]
            },
            "production": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "serverless": {
              "optimization": true,
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.serverless.ts"
                }
              ]
            }
          }
        }
      }
    },
    "app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  }
}


来源: stackexchange

问:
In React Query, How to get data if i'm using two mutate functions in a component?
I'm on a component where a api call exists on componentdidmount and one when use clicks on a button of that page so how can get the data of that particular api call?

```<code>const [mutate, { data, error }] = useMutation(handlefunction);
componentDidMount(){
mutate({api:api, data:{email:"email});
}
return(
<button onClick = {()=>{mutate({api:api2, data:{}})}>click</button>
}
</code>```

how can i get data for button click mutate?

答:
```<code>onClickHandler = (e) => {
   e.preventDefault();
   mutate({api:api2, data:{}})
}
</code>```

In return function:

```<code><button onClick = {onClickHandler}>click</button>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm on a component where a api call exists on componentdidmount and one when use clicks on a button of that page so how can get the data of that particular api call?

const [mutate, { data, error }] = useMutation(handlefunction);
componentDidMount(){
mutate({api:api, data:{email:"email});
}
return(
<button onClick = {()=>{mutate({api:api2, data:{}})}>click</button>
}

how can i get data for button click mutate?

Body:
onClickHandler = (e) => {
   e.preventDefault();
   mutate({api:api2, data:{}})
}

In return function:

<button onClick = {onClickHandler}>click</button>


问:
extjs checkbox grid delete rails
i am using ExtJS with Rails...I am trying to delete records selected in grid through "Checkbox column"...i dnt have any idea as to how can i handle "Array" of selected records of grid through rails controller...plzz guide me...
the code on delete button is as follows :

```<code>var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();
    Ext.Ajax.request({
        url: 'products/delete',
        //   method:'DELETE',
        params: {
            'prodid': sel
        }

    });

});
</code>```

How can i iterate through "sel" array in my Rails controller?? plzz help

答:
You cannot pass arrays into Rails controller directly. This article should help you in understanding parameter passing into rails controllers.

That said, you need to convert the array into a string. You can use a function similar to this for converting the array to string:

```<code>function array_params(arry) {
    var paramvar = "";
    arry.each(function(s){
    paramvar = paramvar.concat("arr[]=",s,"&");});
    paramvar = paramvar.replace(/&$/,"");
    return paramvar;
}
</code>```

and finally call:

```<code>Ext.Ajax.request({
    url: 'products/delete',
    //   method:'DELETE',
    params: {
        'prodid': array_params(sel)
    }

});
</code>```

ContentLicense: CC BY-SA 3.0

Title: extjs checkbox grid delete rails

Body:
i am using ExtJS with Rails...I am trying to delete records selected in grid through "Checkbox column"...i dnt have any idea as to how can i handle "Array" of selected records of grid through rails controller...plzz guide me...
the code on delete button is as follows :

var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();
    Ext.Ajax.request({
        url: 'products/delete',
        //   method:'DELETE',
        params: {
            'prodid': sel
        }

    });

});

How can i iterate through "sel" array in my Rails controller?? plzz help

Body:
You cannot pass arrays into Rails controller directly. This article should help you in understanding parameter passing into rails controllers.

That said, you need to convert the array into a string. You can use a function similar to this for converting the array to string:

function array_params(arry) {
    var paramvar = "";
    arry.each(function(s){
    paramvar = paramvar.concat("arr[]=",s,"&");});
    paramvar = paramvar.replace(/&$/,"");
    return paramvar;
}

and finally call:

Ext.Ajax.request({
    url: 'products/delete',
    //   method:'DELETE',
    params: {
        'prodid': array_params(sel)
    }

});


问:
Data from Realtime Firebase is displaying in console but not in html page
Component.ts

plats is the root node of my Firebase database,I want to display every child of my root node in
angular page.The data is displayed in console but not in angular page. Thank you for your helps in
advance.

```<code>    itemValue = '';
    name: string;
    plats: Observable<any[]>;
    itemRef: AngularFireObject<any>;

    constructor(public db: AngularFireDatabase)
    {
    this.itemRef = db.object('plats');
    this.itemRef.snapshotChanges().subscribe(action => {
    const data = action.payload.val();
    console.log(action.payload.val());
    return { ...data };
    });

 }
</code>```

component.html

```<code>    <div class="container">
      <table>
        <tr>
          <th>Community</th>
        </tr>
       <tr *ngFor="let item of plats | async">
          <td>{{item}}</td>
      </tr>
     </table>
   </div>
</code>```

答:
Assign data to plats

.ts

```<code>const data = action.payload.val();
this.plats = data;
</code>```

template:

```<code><tr *ngFor="let item of plats">
  <td>{{item}}</td>
</tr>
</code>```

OR

Keep your .ts file as it is and in template, use itemRef

```<code><tr *ngFor="let item of itemRef | async">
   <td>{{item}}</td>
</tr>
</code>```

Body:
Component.ts

plats is the root node of my Firebase database,I want to display every child of my root node in
angular page.The data is displayed in console but not in angular page. Thank you for your helps in
advance.

    itemValue = '';
    name: string;
    plats: Observable<any[]>;
    itemRef: AngularFireObject<any>;

    constructor(public db: AngularFireDatabase)
    {
    this.itemRef = db.object('plats');
    this.itemRef.snapshotChanges().subscribe(action => {
    const data = action.payload.val();
    console.log(action.payload.val());
    return { ...data };
    });

 }

component.html

          Community

          {{item}}

Body:
Assign data to plats

.ts

const data = action.payload.val();
this.plats = data;

template:

<tr *ngFor="let item of plats">
  <td>{{item}}</td>
</tr>

OR

Keep your .ts file as it is and in template, use itemRef

<tr *ngFor="let item of itemRef | async">
   <td>{{item}}</td>
</tr>


问:
Syncing a random variable in ruby
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

```<code>$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end
</code>```

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

```<code>def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end
</code>```

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

答:
Here is another approach. This code imitates game computer against itself. You can easily replace one computer's move with user input. </p>

```<code>ROWS = 3
COLUMNS = 3
MAX_TURNS = ROWS * COLUMNS

def random_cell
  { row: rand(ROWS), column: rand(COLUMNS) }
end

def empty_random_cell(board)
  while true
    cell = random_cell
    return cell if board_value(board, cell).nil?
  end
end

def board_value(board, cell)
  board[cell[:row]][cell[:column]]
end

def turn(board, cell, value)
  row = cell[:row]
  column = cell[:column]
  board[row][column] = value
end

def print_board(board)
  ROWS.times do |row|
    COLUMNS.times do |column|
      value = board[row][column]
      print value.nil? ? '_' : value
      print ' '
    end
    puts
  end
end

board = Array.new(ROWS) { Array.new(COLUMNS) }
print_board(board)
turns_counter = 0
while true
  cell = empty_random_cell(board)
  turn(board, cell, 'X')
  turns_counter += 1
  break if turns_counter == MAX_TURNS
  cell = empty_random_cell(board)
  turn(board, cell, '0')
  turns_counter += 1
  break if turns_counter == MAX_TURNS
end

print_board(board)
</code>```

Title: Syncing a random variable in ruby

Body:
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

Body:
Here is another approach. This code imitates game computer against itself. You can easily replace one computer's move with user input.

ROWS = 3
COLUMNS = 3
MAX_TURNS = ROWS * COLUMNS

def random_cell
  { row: rand(ROWS), column: rand(COLUMNS) }
end

def empty_random_cell(board)
  while true
    cell = random_cell
    return cell if board_value(board, cell).nil?
  end
end

def board_value(board, cell)
  board[cell[:row]][cell[:column]]
end

def turn(board, cell, value)
  row = cell[:row]
  column = cell[:column]
  board[row][column] = value
end

def print_board(board)
  ROWS.times do |row|
    COLUMNS.times do |column|
      value = board[row][column]
      print value.nil? ? '_' : value
      print ' '
    end
    puts
  end
end

board = Array.new(ROWS) { Array.new(COLUMNS) }
print_board(board)
turns_counter = 0
while true
  cell = empty_random_cell(board)
  turn(board, cell, 'X')
  turns_counter += 1
  break if turns_counter == MAX_TURNS
  cell = empty_random_cell(board)
  turn(board, cell, '0')
  turns_counter += 1
  break if turns_counter == MAX_TURNS
end

print_board(board)


问:
function st_contains(sde.st_geometry, sde.st_geometry) does not exist
Please help, I tried using PostGIS ST_Contains function on Laravel

SQLSTATE[42883]: Undefined function: 7 ERROR:  function st_contains(sde.st_geometry, sde.st_geometry) does not exist

HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

Laravel Framework 6:13.1

PostgreSQL 9.6.15

PostGIS 2.4

This SQL query works fine if run in pgAdmin.

答:
You probably have to qualify the function with the name of the schema that contains it: sde.st_contains

The explanation is that the schema is not on your search_path.


问:
Difference between Angular's canLoad and canActivate?
What is the difference between canLoad and canActivate?

```<code>export interface Route {
  path?: string;
  pathMatch?: string;
  matcher?: UrlMatcher;
  component?: Type<any>;
  redirectTo?: string;
  outlet?: string;
  canActivate?: any[];
  canActivateChild?: any[];
  canDeactivate?: any[];
  canLoad?: any[];
  data?: Data;
  resolve?: ResolveData;
  children?: Routes;
  loadChildren?: LoadChildren;
}
</code>```

When I should which one of them?

答:
The CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized user to navigate to any of the routes of the module and also stop then even see the source code of the module.

The Angular provides canActivate Guard, which prevents unauthorized user from accessing the route. But it does not stop the module from being downloaded. The user can use the chrome developer console to see the source code. The CanLoad Guard prevents the module from being downloaded.

Actually,CanLoad protects a module to be loaded but once module is loaded then CanLoad guard will do nothing. Suppose we have protected a module loading using CanLoad guard for unauthenticated user. When user is logged-in then that module will be applicable to be loaded and we will be able to navigate children paths configured by that module. But when user is logged-out, still user will be able to navigate those children paths because module is already loaded. In this case if we want to protect children paths from unauthorized users, we also need to use CanActivate guard.

Use CanLoad before loading AdminModule:

```<code>  {
        path: 'admin',
        loadChildren: 'app/admin/admin.module#AdminModule',
        canLoad: [ AuthGuardService ]
      },
</code>```

After loading AdminModule, in AdminRouting module we can use CanActivate to protect childs from unauthorized users like bellow:

```<code>{
      path: '',
      component: AdminComponent,
      children: [
        {
          path: 'person-list',
          component: PersonListComponent,
          canActivate: [ AuthGuardService ]
        }
      ]
    }
</code>```

Body:
What is the difference between canLoad and canActivate?

export interface Route {
  path?: string;
  pathMatch?: string;
  matcher?: UrlMatcher;
  component?: Type<any>;
  redirectTo?: string;
  outlet?: string;
  canActivate?: any[];
  canActivateChild?: any[];
  canDeactivate?: any[];
  canLoad?: any[];
  data?: Data;
  resolve?: ResolveData;
  children?: Routes;
  loadChildren?: LoadChildren;
}

When I should which one of them?

Body:
The CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized user to navigate to any of the routes of the module and also stop then even see the source code of the module.

The Angular provides canActivate Guard, which prevents unauthorized user from accessing the route. But it does not stop the module from being downloaded. The user can use the chrome developer console to see the source code. The CanLoad Guard prevents the module from being downloaded.

Actually,CanLoad protects a module to be loaded but once module is loaded then CanLoad guard will do nothing. Suppose we have protected a module loading using CanLoad guard for unauthenticated user. When user is logged-in then that module will be applicable to be loaded and we will be able to navigate children paths configured by that module. But when user is logged-out, still user will be able to navigate those children paths because module is already loaded. In this case if we want to protect children paths from unauthorized users, we also need to use CanActivate guard.

Use CanLoad before loading AdminModule:

  {
        path: 'admin',
        loadChildren: 'app/admin/admin.module#AdminModule',
        canLoad: [ AuthGuardService ]
      },

After loading AdminModule, in AdminRouting module we can use CanActivate to protect childs from unauthorized users like bellow:

{
      path: '',
      component: AdminComponent,
      children: [
        {
          path: 'person-list',
          component: PersonListComponent,
          canActivate: [ AuthGuardService ]
        }
      ]
    }


问:
Getting undefined value for input control
In the following html and javascript code(codepen - https://codepen.io/manuchadha/pen/OJVXdzb), I wan to print the value of the input control but I am getting the value as undefined - filename is  undefined. Why?

```<code><!DOCTYPE html>
<html>
  <head>
    <title>some title</title>
    <script src="jquery/jquery-3.3.1.min.js"></script>
    <script src="index.js"></script>
  </head>
  <body>
    <div id="add-more-answer-div">
      <div id="answer-filename-div">
        <label id="filename-label" for="answer-filename">Name</label>
        <input type="text" id="answer-filename" />
        <button
          type="button"
          id="more-answer-button"
          onclick="createNewAnswerSection()"
        >
          Add More Sections
        </button>
      </div>
    </div>
  </body>
</html>
</code>```

```<code>function createNewAnswerSection() {
  console.log("will create new answer section");
  var answerNameControl = $("#answer-filename");

  console.log("answer name control is ", answerNameControl);
  if (answerNameControl.value === "") {
    alert("give a filename to the answer");
  } else {
    console.log("filename is ", answerNameControl.value);
  }
}
</code>```

答:
You should use val() at all !

    Name
    <input type="text" id="answer-filename">
    <button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>

```

Body:
In the following html and javascript code(codepen - https://codepen.io/manuchadha/pen/OJVXdzb), I wan to print the value of the input control but I am getting the value as undefined - filename is  undefined. Why?

<!DOCTYPE html>

    <title>some title</title>

        Name
        <input type="text" id="answer-filename" />
        <button
          type="button"
          id="more-answer-button"
          onclick="createNewAnswerSection()"
        >
          Add More Sections
        </button>

function createNewAnswerSection() {
  console.log("will create new answer section");
  var answerNameControl = $("#answer-filename");

  console.log("answer name control is ", answerNameControl);
  if (answerNameControl.value === "") {
    alert("give a filename to the answer");
  } else {
    console.log("filename is ", answerNameControl.value);
  }
}

Body:
You should use val() at all !

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-more-answer-div">
  <div id="answer-filename-div">
    <label id="filename-label" for="answer-filename">Name</label>
    <input type="text" id="answer-filename">
    <button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>
  </div>
</div>

<script>
  function createNewAnswerSection() {
    console.log("will create new answer section");
    var answerNameControl = $("#answer-filename").val();

    console.log("answer name control is ", answerNameControl);
    if (answerNameControl === '') {
      alert("give a filename to the answer");
    } else {
      console.log("filename is ", answerNameControl);
    }
  }
</script>


问:
enable working with different timezones
I have an asp.net + c# application that uses System.DateTime.now for logging working hours of employees. the application is online and recently I have users connecting to it from outside of my country.

I have a client that wants his employees working abroad to log their working hours according to their timezone.

All the dates and hours that are documented in the db are not in universal time so I don't want to try and change backwards everything to UTC (I also think that's not applicable).

I'm aware of ways to detect the user's timezone- js and geo-location. the thing is I don't trust the accuracy level of both. in conclusion I thought i'd let the admin define through an interface time-zones and the user will pick the one he wishes to use.

Is this a proper way? What is the best practice for this?
10q very much.

答:
Having the DateTimes stored in UTC is definitely a best practice in my book.  It may be quite a bit of work to convert your existing data, but it's probably going to be worth it in the long term if you already have a few users in different time zones (today it's two, but soon it could be three, four....)  It's also going to make it easier to avoid problems around things like daylight savings time conversions, especially if the groups are in regions where the start and end of daylight savings is different, which is the case between the US and UK (I have to deal with these DateTime issues in my system).

I would not rely on any automatic detection of a user's timezone when data is entered into your UI.  The first thing I'd do is associate users in the database with a timezone property.  It doesn't sound like your users are changing their timezones much, if ever.

It shouldn't be too difficult to associate locations with either users or groups of users if you're not already doing it.  Just add the timezone information along with their location, and use that in your code when creating a DateTime object from the input from your.  It means one more piece of data that someone will have to manage, but it's going to be less troublesome than trying to automatically detect the timezone through code.

It's going to be very easy to miss conversions now that you're adding a new time zone.  I would recommend making sure all your DateTime logic is centralized (extension methods or a helper class, depending on your framework version). Keep all your conversions and string formatting in a single place and make sure all your code references it.

Good luck, and write lots of unit tests around your conversions.

Title: enable working with different timezones


问:
How does Java ZoneId.systemDefault() know about TimeZone if my computer doesn't connect to the Internet?
I'm new to Java8 Date And Time API and really curious about how a computer is aware of the time zones.

I already know a computer is aware of time by a small battery in its motherboard. Is the TimeZone similar?

答: Your time, date and timezone is locally saved on your computer. Internet is used occasionally to sync with a global trusted time so your computer does not get out of sync. </p>


问:
istio error: Details: java.io.IOException: Unknown apiVersionKind
I receive this error message in jenkins when trying to deploy my application to kubernetes. Is there something I am missing?

istio-gateway.yml ERROR: ERROR: java.io.IOException: ERROR: YAML file
  istio-gateway.yml is invalid, please check it. Details:
  java.io.IOException: Unknown apiVersionKind:
  networking.istio.io/v1alpha3/Gateway known kinds are...

I am using Spring Boot with Java

答: You are trying to create a Istio Geteway using that yaml. You probably don't have istio installed in your Kubernetes cluster. If it's not installed then you need to install it.</p>


问:
Add css style using Javascript when a select option is selected
Is there a way to append a style to an existing class using Javascript, based on which option you have selected in an html select option drop down?

For example, in the below table, I would like the appropriate number the become bold or highlighted when that number has been selected from the option box.

Thanks so much!

Finder

Show category:

<select type="search" class="select-table-filter" data-table="order-table" id="searchInput">
  <option value="">All</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />

      Category
      Name
      Last Name
      Phone
      Email

      1
      Taylor
      Swift
      1234 5678
      taytay@gmail.com

      2, 3
      John
      Smith
      1234 5678
      johnnyboy@gmail.com

      3
      Jane
      Doh
      1234 5678
      dohnut@gmail.com

      3, 4
      Taylor
      Doh
      1234 5678
      td@gmail.com

```

答:
You can do that with contains selector.

HTML

```<code><select type="search" class="select-table-filter" data-table="order-table" id="searchInput">
   <option value="">All</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />
<table class="order-table" id="myTable">
<thead>
 <tr class="header">
  <th>Category</th>
  <th>Name</th>
  <th>Last Name</th>
  <th>Phone</th>
  <th>Email</th>
</tr>
</thead>
<tbody>
<tr>
  <td class="td">1</td>
  <td>Taylor</td>
  <td>Swift</td>
  <td>1234 5678</td>
  <td>taytay@gmail.com</td>
</tr>
<tr>
  <td class="td">2, 3</td>
  <td>John</td>
  <td>Smith</td>
  <td>1234 5678</td>
  <td>johnnyboy@gmail.com</td>
</tr>
<tr>
  <td class="td">3</td>
  <td>Jane</td>
  <td>Doh</td>
  <td>1234 5678</td>
  <td>dohnut@gmail.com</td>
</tr>
<tr>
  <td class="td">3, 4</td>
  <td>Taylor</td>
  <td>Doh</td>
  <td>1234 5678</td>
  <td>td@gmail.com</td>
</tr>
</tbody>
</table>
</code>```

JQUERY

```<code><script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

$('#searchInput').on('change',function(){
    let val=$(this).val();
    $( ".td" ).css( "font-weight", "400" );
    $( ".td:contains('"+val+"') " ).css( "font-weight", "800" );
});
</code>```

Body:
You can do that with contains selector.

HTML

<select type="search" class="select-table-filter" data-table="order-table" id="searchInput">
   <option value="">All</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

<input type="search" class="light-table-filter" data-table="order-table" placeholder="Search ..." />
<table class="order-table" id="myTable">
<thead>
 <tr class="header">
  <th>Category</th>
  <th>Name</th>
  <th>Last Name</th>
  <th>Phone</th>
  <th>Email</th>
</tr>
</thead>
<tbody>
<tr>
  <td class="td">1</td>
  <td>Taylor</td>
  <td>Swift</td>
  <td>1234 5678</td>
  <td>taytay@gmail.com</td>
</tr>
<tr>
  <td class="td">2, 3</td>
  <td>John</td>
  <td>Smith</td>
  <td>1234 5678</td>
  <td>johnnyboy@gmail.com</td>
</tr>
<tr>
  <td class="td">3</td>
  <td>Jane</td>
  <td>Doh</td>
  <td>1234 5678</td>
  <td>dohnut@gmail.com</td>
</tr>
<tr>
  <td class="td">3, 4</td>
  <td>Taylor</td>
  <td>Doh</td>
  <td>1234 5678</td>
  <td>td@gmail.com</td>
</tr>
</tbody>
</table>

JQUERY

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

$('#searchInput').on('change',function(){
    let val=$(this).val();
    $( ".td" ).css( "font-weight", "400" );
    $( ".td:contains('"+val+"') " ).css( "font-weight", "800" );
});


问:
BFG Repo-Cleaner states my github repo is not a valid Git repository
This is a follow-up question from a previous question on Stackoverflow.

I've tried to remove large files from my local git history, but the tool (BFG Repo-Cleaner) suggested in this question states that my private GitHub repository is not a valid git repository.

The command I use is:

```<code>java -jar bfg-1.12.12.jar  --strip-blobs-bigger-than 99M https://github.com/name/repo.git
</code>```

Which eventually results in:

```<code>Aborting : https://github.com/name/repo.git is not a valid Git repository.
</code>```

I couldn't find a solution. Is the tool not compatible with private or https GitHub repositories?
How would I use the alternative tool git-filter-branch, to remove all files larger than 99MB from my local git history?

The project is about 6MB large and only about 50 commits were made up to now and no other people are working on it.

答:
I have fixed this using the following commands:

STEP 1

```<code>cd some-big-repo.git
</code>```

STEP 2

```<code>java -jar path/bfg.jar --strip-blobs-bigger-than 100M
</code>```

No need to mention repo name explicitly if you are in the repo directory and it will automatically detect repo and do its job.

Body:
This is a follow-up question from a previous question on Stackoverflow.

I've tried to remove large files from my local git history, but the tool (BFG Repo-Cleaner) suggested in this question states that my private GitHub repository is not a valid git repository.

The command I use is:

java -jar bfg-1.12.12.jar  --strip-blobs-bigger-than 99M https://github.com/name/repo.git

Which eventually results in:

Aborting : https://github.com/name/repo.git is not a valid Git repository.

I couldn't find a solution. Is the tool not compatible with private or https GitHub repositories?
How would I use the alternative tool git-filter-branch, to remove all files larger than 99MB from my local git history?

The project is about 6MB large and only about 50 commits were made up to now and no other people are working on it.

Body:
I have fixed this using the following commands:

STEP 1

cd some-big-repo.git

STEP 2

java -jar path/bfg.jar --strip-blobs-bigger-than 100M

No need to mention repo name explicitly if you are in the repo directory and it will automatically detect repo and do its job.


问:
apollostack/graphql-server - how to get the fields requested in a query from resolver
I am trying to figure out a clean way to work with queries and mongdb projections so I don't have to retrieve excessive information from the database.
So assuming I have:

```<code>// the query
type Query {
  getUserByEmail(email: String!): User
}
</code>```

And I have a User with an email and a username, to keep things simple. If I send a query and I only want to retrieve the email, I can do the following:

```<code>query { getUserByEmail(email: "test@test.com") { email } }
</code>```

But in the resolver, my DB query still retrieves both username and email, but only one of those is passed back by apollo server as the query result.

I only want the DB to retrieve what the query asks for:

```<code>// the resolver
getUserByEmail(root, args, context, info) {
  // check what fields the query requested
  // create a projection to only request those fields
  return db.collection('users').findOne({ email: args.email }, { /* projection */ });
}
</code>```

Of course the problem is, getting information on what the client is requesting isn't so straightforward.

Assuming I pass in request as context - I considered using context.payload (hapi.js), which has the query string, and searching it through various .split()s, but that feels kind of dirty. As far as I can tell, info.fieldASTs[0].selectionSet.selections has the list of fields, and I could check for it's existence in there. I'm not sure how reliable this is. Especially when I start using more complex queries.

Is there a simpler way?

In case you don't use mongDB, a projection is an additional argument you pass in telling it explicitly what to retrieve:

```<code>// telling mongoDB to not retrieve _id
db.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })
</code>```

As always, thanks to the amazing community.

答:
You can generate MongoDB projection from info argument. Here is the sample code that you can follow

```<code> /**
 * @description - Gets MongoDB projection from graphql query
 *
 * @return { object }
 * @param { object } info
 * @param { model } model - MongoDB model for referencing
 */

function getDBProjection(info, model) {
  const {
    schema: { obj }
  } = model;
  const keys = Object.keys(obj);
  const projection = {};

  const { selections } = info.fieldNodes[0].selectionSet;

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const isSelected = selections.some(
      selection => selection.name.value === key
    );

    projection[key] = isSelected;
  }

  console.log(projection);
}

module.exports = getDBProjection;

</code>```

Body:
I am trying to figure out a clean way to work with queries and mongdb projections so I don't have to retrieve excessive information from the database.
So assuming I have:

// the query
type Query {
  getUserByEmail(email: String!): User
}

And I have a User with an email and a username, to keep things simple. If I send a query and I only want to retrieve the email, I can do the following:

query { getUserByEmail(email: "test@test.com") { email } }

But in the resolver, my DB query still retrieves both username and email, but only one of those is passed back by apollo server as the query result.

I only want the DB to retrieve what the query asks for:

// the resolver
getUserByEmail(root, args, context, info) {
  // check what fields the query requested
  // create a projection to only request those fields
  return db.collection('users').findOne({ email: args.email }, { /* projection */ });
}

Of course the problem is, getting information on what the client is requesting isn't so straightforward.

Assuming I pass in request as context - I considered using context.payload (hapi.js), which has the query string, and searching it through various .split()s, but that feels kind of dirty. As far as I can tell, info.fieldASTs[0].selectionSet.selections has the list of fields, and I could check for it's existence in there. I'm not sure how reliable this is. Especially when I start using more complex queries.

Is there a simpler way?

In case you don't use mongDB, a projection is an additional argument you pass in telling it explicitly what to retrieve:

// telling mongoDB to not retrieve _id
db.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })

As always, thanks to the amazing community.

Body:
You can generate MongoDB projection from info argument. Here is the sample code that you can follow

 /**
 * @description - Gets MongoDB projection from graphql query
 *
 * @return { object }
 * @param { object } info
 * @param { model } model - MongoDB model for referencing
 */

function getDBProjection(info, model) {
  const {
    schema: { obj }
  } = model;
  const keys = Object.keys(obj);
  const projection = {};

  const { selections } = info.fieldNodes[0].selectionSet;

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const isSelected = selections.some(
      selection => selection.name.value === key
    );

    projection[key] = isSelected;
  }

  console.log(projection);
}

module.exports = getDBProjection;


问:
How to merge two intersecting arrays via es6
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

```<code>export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});
</code>```

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.

答:
Use Object.assign()

Ex: oldArray = Object.assign(oldArray, newArray)

Body:
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.


问:
Pytorch custom Dataset class giving wrong output
I am trying to use this class I built for a dataset but it saying that it should be a PIL or ndarray. I'm not quite sure what's wrong with it.  Here is the class that I am using:

```<code>class RotateDataset(Dataset):
    def __init__(self, image_list, size,transform = None):
        self.image_list = image_list
        self.size = size
        self.transform = transform
    def __len__(self):
        return len(self.image_list)
    def __getitem__(self, idx):

        img = cv2.imread(self.image_list[idx])
        image_height, image_width = img.shape[:2]
        print("ID: ", idx)
        if idx % 2 == 0:
            label = 0 # Set label
            # chose negative or positive rotation
            rotation_degree = random.randrange(35, 50, 1)
            posnegrot = np.random.randint(2)
            if posnegrot == 0:
                #positive rotation
                #rotation_matrix = cv2.getRotationMatrix2D((num_cols/2, num_rows/2), rotation_degree, 1)
                #img = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows))

                img = rotate_image(img, rotation_degree)
                img = crop_around_center(img, *largest_rotated_rect(image_width,
                                                                image_height,
                                                                math.radians(rotation_degree)))
            else:
                # Negative rotation
                rotation_degree = -rotation_degree
                img = crop_around_center(img, *largest_rotated_rect(image_width,
                                                                image_height,
                                                                math.radians(rotation_degree)))

        else:
           label = 1
        img = cv2.resize(img, self.size, cv2.INTER_AREA)
        return self.transform(img), self.transform(label)
</code>```

The error that it is giving me is

```
TypeError: pic should be PIL Image or ndarray. Got class 'int'
```

It should give me a img (tensor) and a label (tensor)
but I don't think it is doing it correctly.

TypeError                                 Traceback (most recent call last)
<ipython-input-34-f47943b2600c> in <module>
      2     train_loss = 0.0
      3     net.train()
----> 4     for image, label in enumerate(train_loader):
      5         if train_on_gpu:
      6             image, label = image.cuda(), label.cuda()

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\dataloader.py in __next__(self)
    343
    344     def __next__(self):
--> 345         data = self._next_data()
    346         self._num_yielded += 1
    347         if self._dataset_kind == _DatasetKind.Iterable and \

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\dataloader.py in _next_data(self)
    383     def _next_data(self):
    384         index = self._next_index()  # may raise StopIteration
--> 385         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    386         if self._pin_memory:
    387             data = _utils.pin_memory.pin_memory(data)

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\_utils\fetch.py in fetch(self, possibly_batched_index)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\_utils\fetch.py in <listcomp>(.0)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

<ipython-input-28-6c77357ff619> in __getitem__(self, idx)
     35             label = 1
     36         img = cv2.resize(img, self.size, cv2.INTER_AREA)
---> 37         return self.transform(img), self.transform(label)

~\Anaconda3\envs\TF2\lib\site-packages\torchvision\transforms\transforms.py in __call__(self, pic)
     99             Tensor: Converted image.
    100         """
--> 101         return F.to_tensor(pic)
    102
    103     def __repr__(self):

~\Anaconda3\envs\TF2\lib\site-packages\torchvision\transforms\functional.py in to_tensor(pic)
     53     """
     54     if not(_is_pil_image(pic) or _is_numpy(pic)):
---> 55         raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
     56
     57     if _is_numpy(pic) and not _is_numpy_image(pic):

TypeError: pic should be PIL Image or ndarray. Got <class 'int'>```

答:
As discussed in the comments, the problem was applying transform on label as well. The label should instead simply be written as tensor:

```<code>return self.transform(img), torch.tensor(label)
</code>```

Body:
I am trying to use this class I built for a dataset but it saying that it should be a PIL or ndarray. I'm not quite sure what's wrong with it.  Here is the class that I am using:

class RotateDataset(Dataset):
    def __init__(self, image_list, size,transform = None):
        self.image_list = image_list
        self.size = size
        self.transform = transform
    def __len__(self):
        return len(self.image_list)
    def __getitem__(self, idx):

        img = cv2.imread(self.image_list[idx])
        image_height, image_width = img.shape[:2]
        print("ID: ", idx)
        if idx % 2 == 0:
            label = 0 # Set label
            # chose negative or positive rotation
            rotation_degree = random.randrange(35, 50, 1)
            posnegrot = np.random.randint(2)
            if posnegrot == 0:
                #positive rotation
                #rotation_matrix = cv2.getRotationMatrix2D((num_cols/2, num_rows/2), rotation_degree, 1)
                #img = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows))

                img = rotate_image(img, rotation_degree)
                img = crop_around_center(img, *largest_rotated_rect(image_width,
                                                                image_height,
                                                                math.radians(rotation_degree)))
            else:
                # Negative rotation
                rotation_degree = -rotation_degree
                img = crop_around_center(img, *largest_rotated_rect(image_width,
                                                                image_height,
                                                                math.radians(rotation_degree)))

        else:
           label = 1
        img = cv2.resize(img, self.size, cv2.INTER_AREA)
        return self.transform(img), self.transform(label)

The error that it is giving me is

TypeError: pic should be PIL Image or ndarray. Got class 'int'

It should give me a img (tensor) and a label (tensor)
but I don't think it is doing it correctly.

TypeError                                 Traceback (most recent call last)
<ipython-input-34-f47943b2600c> in <module>
      2     train_loss = 0.0
      3     net.train()
----> 4     for image, label in enumerate(train_loader):
      5         if train_on_gpu:
      6             image, label = image.cuda(), label.cuda()

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\dataloader.py in __next__(self)
    343
    344     def __next__(self):
--> 345         data = self._next_data()
    346         self._num_yielded += 1
    347         if self._dataset_kind == _DatasetKind.Iterable and \

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\dataloader.py in _next_data(self)
    383     def _next_data(self):
    384         index = self._next_index()  # may raise StopIteration
--> 385         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    386         if self._pin_memory:
    387             data = _utils.pin_memory.pin_memory(data)

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\_utils\fetch.py in fetch(self, possibly_batched_index)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

~\Anaconda3\envs\TF2\lib\site-packages\torch\utils\data\_utils\fetch.py in <listcomp>(.0)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

<ipython-input-28-6c77357ff619> in __getitem__(self, idx)
     35             label = 1
     36         img = cv2.resize(img, self.size, cv2.INTER_AREA)
---> 37         return self.transform(img), self.transform(label)

~\Anaconda3\envs\TF2\lib\site-packages\torchvision\transforms\transforms.py in __call__(self, pic)
     99             Tensor: Converted image.
    100         """
--> 101         return F.to_tensor(pic)
    102
    103     def __repr__(self):

~\Anaconda3\envs\TF2\lib\site-packages\torchvision\transforms\functional.py in to_tensor(pic)
     53     """
     54     if not(_is_pil_image(pic) or _is_numpy(pic)):
---> 55         raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
     56
     57     if _is_numpy(pic) and not _is_numpy_image(pic):

TypeError: pic should be PIL Image or ndarray. Got <class 'int'>

Body:
As discussed in the comments, the problem was applying transform on label as well. The label should instead simply be written as tensor:

return self.transform(img), torch.tensor(label)


问:
Adding Cells to Dynamic UITableView DataSource | Swift
I have a dynamic UITableViewDataSource that takes in a Model and a UITableViewCell

I would like to insert a different UITableViewCell into the 'nth' (10th for example) row... (for Google Ads)

DATASOURCE

```<code>class ModelTableViewDataSource<Model, Cell: UITableViewCell>: NSObject, UITableViewDataSource {

    typealias CellConfigurator = (Model, Cell) -> Void

    var models: [Model]

    private let reuseIdentifier: String
    private let cellConfigurator: CellConfigurator

    init(models: [Model], reuseIdentifier: String, cellConfigurator: @escaping CellConfigurator) {
        self.models = models
        self.reuseIdentifier = reuseIdentifier
        self.cellConfigurator = cellConfigurator
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = models[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! Cell
        cellConfigurator(model, cell)
        return cell
    }
}
</code>```

I then add an extension for each Model

MODEL

```<code>extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {
    static func make(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
        return ModelTableViewDataSource(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
            someCell.model = someModel
        }
    }
}
</code>```

What is the best way to implement this keeping the re-usable functionality of the UITableViewDataSource

答:
I thought of this:

create a subclass

override numberOfRowsInSection to return number of rows + 1

override cellForRowAt to handle the 10th row

class ModelTableViewDataSourceWithAd: ModelTableViewDataSource {

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return super.tableView(tableView, numberOfRowsInSection:section) + 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.row == 9) {
        // return Google ad cell
    } else {
        return super.tableView(tableView, cellForRowAt:indexPath)
    }
}
</code>```

}

and then the creator:

```<code>extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {

// ...

    static func makeWithAd(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
        return ModelTableViewDataSourceWithAd(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
            someCell.model = someModel
        }
    }

}
</code>```

Body:
I have a dynamic UITableViewDataSource that takes in a Model and a UITableViewCell

I would like to insert a different UITableViewCell into the 'nth' (10th for example) row... (for Google Ads)

DATASOURCE

class ModelTableViewDataSource<Model, Cell: UITableViewCell>: NSObject, UITableViewDataSource {

    typealias CellConfigurator = (Model, Cell) -> Void

    var models: [Model]

    private let reuseIdentifier: String
    private let cellConfigurator: CellConfigurator

    init(models: [Model], reuseIdentifier: String, cellConfigurator: @escaping CellConfigurator) {
        self.models = models
        self.reuseIdentifier = reuseIdentifier
        self.cellConfigurator = cellConfigurator
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = models[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! Cell
        cellConfigurator(model, cell)
        return cell
    }
}

I then add an extension for each Model

MODEL

extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {
    static func make(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
        return ModelTableViewDataSource(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
            someCell.model = someModel
        }
    }
}

What is the best way to implement this keeping the re-usable functionality of the UITableViewDataSource

Body:
I thought of this:

create a subclass

override numberOfRowsInSection to return number of rows + 1

override cellForRowAt to handle the 10th row

class ModelTableViewDataSourceWithAd: ModelTableViewDataSource {

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return super.tableView(tableView, numberOfRowsInSection:section) + 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.row == 9) {
        // return Google ad cell
    } else {
        return super.tableView(tableView, cellForRowAt:indexPath)
    }
}

}

and then the creator:

extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {

// ...

    static func makeWithAd(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
        return ModelTableViewDataSourceWithAd(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
            someCell.model = someModel
        }
    }

}


问:
C++, templates with default parameters
A simplified example:

There is an abstract template class GCont representing a general container

```<code>template <typename Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <typename Item>
class GCont
{
    protected:
            typename TList <Item>::Type items;

    public:
            typedef Item type;
            virtual ~GCont() = 0 {};
};
</code>```

and derived abstract template class having one implicit parameter

```<code>template < typename Item, const bool par = true>
class GCont2 : public GCont <Item>
{
    public:
            GCont2 () : GCont <Item> () {}
    virtual ~GCont2() = 0 {};
};
</code>```

and its specialization for pointers

```<code>template <typename Item, const bool par>
class GCont2 <Item *, par> : public GCont <Item *>
{
    public:
            GCont2 () : GCont <Item *> () {}
            virtual ~Cont() {}
};
</code>```

The derived template class Cont

```<code>template <typename Point, const bool par = true>
class Cont : public GCont2 <Point, par>
{
    public:
            Cont() : GCont2 <Point, par>() {}
            virtual ~Cont() {}
};
</code>```

and specialization for pointers

```<code>template <typename Point, const bool par>
class Cont <Point *, par> : public GCont2 <Point *, par>
{
    public:
            Cont() : GCont2 <Point *, par> () {}
};
</code>```

Class Point:

```<code>template <typename T>
class Point
{
    protected:
            T x, y, z;
};
</code>```

Is it possible to write a function test() having an universal formal parameter alowing to use both

```<code>Cont <Point <T> *> *points
</code>```

and

```<code>Cont <Point <T> *, false> *points
</code>```

In my program

```<code>template <typename T>
void test (Cont <Point <T> *> *points)
{
std::cout << "test";
}

template <typename T>
void test2 (Cont <Point <T> *, false> *points)
{
std::cout << "test2";
}

int _tmain(int argc, _TCHAR* argv[])
{
Point <double> * p = new Point <double>();
Cont <Point <double> *, false> points;

    test(&points); //Error
     test2(&points); //OK

return 0;
}
</code>```

During the translation the following error appears:

```<code>Error   1   error C2784: 'void test(Cont<Point<T>*> *)' : could not deduce template argument for 'Cont<Point<T>*> *' from 'Cont<Point,par> *'   g:\templates_example.cpp    27
</code>```

Thanks for your help...

Updated status:

I trimmed the code... But the problem remains... My code does not compile with the same error using MSVS 2010.

I found the partial solution-templatization of the container.

```<code>template <typename Container>
void test (Container *points)
{
std::cout << "test";
}
</code>```

答:
Your code compiles totally fine for me, you're not giving us the code you really have. Aside from that, your problem seems to be that you want to provide the wrong input. Your test function expects a container of pointers to points (Cont< Point<T>* >), but you provide a container of points (Cont< Point<T> >):

```<code>Cont< Point<int> >* pc;
// ...
test(pc);
</code>```

This will of course produce the error you get. You need a

```<code>Cont< Point<int>* >* pc;
</code>```

That is, a container of pointers. You do this correctly in your question, but your real code doesn't seem to be that.

Title: C++, templates with default parameters

Body:
A simplified example:

There is an abstract template class GCont representing a general container

template <typename Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <typename Item>
class GCont
{
    protected:
            typename TList <Item>::Type items;

    public:
            typedef Item type;
            virtual ~GCont() = 0 {};
};

and derived abstract template class having one implicit parameter

template < typename Item, const bool par = true>
class GCont2 : public GCont <Item>
{
    public:
            GCont2 () : GCont <Item> () {}
    virtual ~GCont2() = 0 {};
};

and its specialization for pointers

template <typename Item, const bool par>
class GCont2 <Item *, par> : public GCont <Item *>
{
    public:
            GCont2 () : GCont <Item *> () {}
            virtual ~Cont() {}
};

The derived template class Cont

template <typename Point, const bool par = true>
class Cont : public GCont2 <Point, par>
{
    public:
            Cont() : GCont2 <Point, par>() {}
            virtual ~Cont() {}
};

and specialization for pointers

template <typename Point, const bool par>
class Cont <Point *, par> : public GCont2 <Point *, par>
{
    public:
            Cont() : GCont2 <Point *, par> () {}
};

Class Point:

template <typename T>
class Point
{
    protected:
            T x, y, z;
};

Is it possible to write a function test() having an universal formal parameter alowing to use both

Cont <Point <T> *> *points

and

Cont <Point <T> *, false> *points

In my program

template <typename T>
void test (Cont <Point <T> *> *points)
{
std::cout << "test";
}

template <typename T>
void test2 (Cont <Point <T> *, false> *points)
{
std::cout << "test2";
}

int _tmain(int argc, _TCHAR* argv[])
{
Point <double> * p = new Point <double>();
Cont <Point <double> *, false> points;

    test(&points); //Error
     test2(&points); //OK

return 0;
}

During the translation the following error appears:

Error   1   error C2784: 'void test(Cont<Point<T>*> *)' : could not deduce template argument for 'Cont<Point<T>*> *' from 'Cont<Point,par> *'   g:\templates_example.cpp    27

Thanks for your help...

Updated status:

I trimmed the code... But the problem remains... My code does not compile with the same error using MSVS 2010.

I found the partial solution-templatization of the container.

template <typename Container>
void test (Container *points)
{
std::cout << "test";
}

Body:
Your code compiles totally fine for me, you're not giving us the code you really have. Aside from that, your problem seems to be that you want to provide the wrong input. Your test function expects a container of pointers to points (Cont< Point<T>* >), but you provide a container of points (Cont< Point<T> >):

Cont< Point<int> >* pc;
// ...
test(pc);

This will of course produce the error you get. You need a

Cont< Point<int>* >* pc;

That is, a container of pointers. You do this correctly in your question, but your real code doesn't seem to be that.


问:
AWS Greengrass. Can't trigger core's lambda function from device mqtt client in local network
What I want to have is to send some metrics from greengrass device to greengrass lambda function in the local network.

I'm using the subscribe mode of basicDiscovery.py to send some device metrics to the amazon greengrass core device and invoke the lambda function deployed on the core. The lambda function simply prints the event.
My confusion is when I use a subscription from IoT Cloud -> lambda function it work's fine but It's not working when I configure a subscription from device -> lambda function.

Also when I disconnect the device the device from the internet (in case 1), it buffers the messages and sends them when it gets connected to the internet again.
I know that I'm passing xxxxxxx.iot.us-west-2.amazonaws.com as the endpoint and it's accessible over the internet, but not sure how to have an endpoint for the core.

答:
I have tried sending data from device to lambda and lambda to cloud.As per my understanding you have to take care of the following points:
1.The device that is connected to greengrass should be publishing data for a topic
2.For the same topic subscription has to created between device and lambda
3.To test this behavior,create another subscription between lambda and cloud

Reference:https://medium.com/tensoriot/aws-greengrass-on-raspberry-pi-creating-core-and-node-devices-707a38452293


问:
missing } after property list error in javascript
I am encountering the above mentioned error, I wonder why it is popping up. All my curly brackets are correct as far as I see. Given below is the code segment:

```<code>var mapped = data.map(d => {

    return {
        date: d.date;
        value: d.count;
    }
});
</code>```

The console is pointing to this line:

```<code>date: d.date;
</code>```

I wonder why this is popping up. Any help is appreciated. thanks!

答:
Every objects can contains multiple attributes/properties and each must be separated with <code>,</code>.
Please adopt the following code and you'll be good to go. </p>

```<code>var mapped = data.map(d => {
    return {
        date: d.date,
        value: d.count
    }
});
</code>```

Body:
I am encountering the above mentioned error, I wonder why it is popping up. All my curly brackets are correct as far as I see. Given below is the code segment:

var mapped = data.map(d => {

    return {
        date: d.date;
        value: d.count;
    }
});

The console is pointing to this line:

date: d.date;

I wonder why this is popping up. Any help is appreciated. thanks!

Body:
Every objects can contains multiple attributes/properties and each must be separated with ,.
Please adopt the following code and you'll be good to go.

var mapped = data.map(d => {
    return {
        date: d.date,
        value: d.count
    }
});


问:
Scala: Printing a Binary Tree That's a Class
Hello I am new to Scala and I'm having a hard time getting my class to print some values out.

```<code>class TreeDemo[T](implicit o : T => Ordered[T]) {

      sealed trait BinaryTree
      case object Empty extends BinaryTree
      case class Node(left:BinaryTree, d:T, right:BinaryTree) extends BinaryTree

      // construct a "leaf" node
      def Leaf(d : T) : BinaryTree = Node(Empty,d,Empty)

      // remove all nodes equal to x from tree t
      def remove(t : BinaryTree, x : T) : BinaryTree = {
        replace(t, x, Empty)
      }

      val myTree = Node(Node(Leaf(1),2,Leaf(3)),4,Leaf(5))
      val x = remove(myTree, 2)

      def main (args: Array[String]) {
       println(x)
      }
}
</code>```

From the code above I am trying to print the remove def but I am getting errors.

答:
If you want remove to remove nodes in place from the tree, then you will want var values. I was not sure because replace is missing from your snippet

As comments point out, Node can only take T until you instantiate an actual TreeDemo, so at the time of definition of the class, you cannot create Nodes of specific types, such as Leaf(1) etc. because it would be a type mismatch.

It seems the type variable should be on BinaryTree itself, since you want your demo to try out specific trees, and it can be covariant (+T) to allow for Empty to be any other valid BinaryTree.

Left and right trees of a node should have the same types as the node.

You can override toString to allow for more informative printing

A method called main inside of a class doesn't serve as an entry-point. In Java, only a static void main will serve as an application entry-point. In Scala, main should also be in static (in an object instead of a class) in order to run.

sealed trait BinaryTree[+T]
case object Empty extends BinaryTree[Nothing]
class Node[T](var left:BinaryTree[T], var d:T, var right:BinaryTree[T])(implicit val ordering: Ordering[T]) extends BinaryTree[T] {
  override def toString: String = (left, right) match {
    case (Empty, Empty) => s"(${d})"
    case (Empty, right) => s"(${left},${d})"
    case (left, Empty) => s"(${d}, ${right})"
    case _ => s"(${left}, ${d}, ${right})"
  }
}
object Node{
  // define remove here (if static) or in the class
  def apply[T:Ordering](t: T) = new Node[T](Empty, t, Empty)
  def apply[T:Ordering](left:BinaryTree[T], t: T) = new Node[T](left, t, Empty)
  def apply[T:Ordering](left:BinaryTree[T], t: T, right:BinaryTree[T]) = new Node[T](left, t, right)
  def apply[T:Ordering](t: T, right:BinaryTree[T]) = new Node[T](Empty, t, right)
}
// either extend App, or have a main method, but use an object
object TreeApp extends App {
  val myTree = Node(Node(Node(1),2,Node(3)),4,Node(5))
  println(myTree)
}
```

Body:
Hello I am new to Scala and I'm having a hard time getting my class to print some values out.

class TreeDemo[T](implicit o : T => Ordered[T]) {

      sealed trait BinaryTree
      case object Empty extends BinaryTree
      case class Node(left:BinaryTree, d:T, right:BinaryTree) extends BinaryTree

      // construct a "leaf" node
      def Leaf(d : T) : BinaryTree = Node(Empty,d,Empty)

      // remove all nodes equal to x from tree t
      def remove(t : BinaryTree, x : T) : BinaryTree = {
        replace(t, x, Empty)
      }

      val myTree = Node(Node(Leaf(1),2,Leaf(3)),4,Leaf(5))
      val x = remove(myTree, 2)

      def main (args: Array[String]) {
       println(x)
      }
}

From the code above I am trying to print the remove def but I am getting errors.


问:
Webscraper in python where I provide a webpage that has a list of links which the scraper then visits individually
I am a beginner in programming and I am trying to make a scraper. As of right now I'm using the requests library and BeautifulSoup. I provide the program a link and I am able to extract any information I want from that single web page. What I am trying to accomplish is as follows... I want to provide a web page to the program, the web page that I provide is a search result where there is a list of links that could be clicked. I want the program to be able to get the links of those search results, and then scrape some information from each of those specific pages from the main web page that I provide.

If anyone can give me some sort of guidance on how I could achieve this I would appreciate it greatly! Are there some other libraries I should be using? Is there some reading material you could refer me to, maybe a video?

答:
You can put all the url links in a list then have your request-sending function loop through it. Use the requests or urllib package for this.

For the search logic, you would want to look for the  tag with href property.

Body:
You can put all the url links in a list then have your request-sending function loop through it. Use the requests or urllib package for this.

For the search logic, you would want to look for the <a> tag with href property.


问:
Filter a List Then Change the Type
How can I cast a list and filter at the same time? I could do this with for loops, but there has to be a Kotlin way that makes it better.

```<code>fun getList(): List<Animal> = animals

fun test() {
    val list: Dog = getList().filter {
        it.age > 5
    }
}
</code>```

list cannot be assigned because it is of type Animal.

How can I transform the list to Dog type and still do the filtering?

答:
First of all, your code is wrong. According to docs, filter function returns a list containing only elements matching the given predicate. So, instead of val list: Dog you should use val list: List<Dog>.

As far as I understood, you want to get list of dogs from animals list which satisfies it.age > 5 condition. To fix the issue, you can use filterIsInstance():

```<code>open class Animal(val age: Int)

class Dog(age: Int) : Animal(age)

fun test() {
    val animals = mutableListOf<Animal>()
    animals.add(Dog(6))
    animals.add(Animal(7))
    animals.add(Dog(8))

    val list: List<Dog> = animals
        .filterIsInstance(Dog::class.java)
        .filter {
            it.age > 5
        }
}
</code>```

Title: Filter a List Then Change the Type

Body:
How can I cast a list and filter at the same time? I could do this with for loops, but there has to be a Kotlin way that makes it better.

fun getList(): List<Animal> = animals

fun test() {
    val list: Dog = getList().filter {
        it.age > 5
    }
}

list cannot be assigned because it is of type Animal.

How can I transform the list to Dog type and still do the filtering?

Body:
First of all, your code is wrong. According to docs, filter function returns a list containing only elements matching the given predicate. So, instead of val list: Dog you should use val list: List<Dog>.

As far as I understood, you want to get list of dogs from animals list which satisfies it.age > 5 condition. To fix the issue, you can use filterIsInstance():

open class Animal(val age: Int)

class Dog(age: Int) : Animal(age)

fun test() {
    val animals = mutableListOf<Animal>()
    animals.add(Dog(6))
    animals.add(Animal(7))
    animals.add(Dog(8))

    val list: List<Dog> = animals
        .filterIsInstance(Dog::class.java)
        .filter {
            it.age > 5
        }
}


问:
How to use transaction across multiple method calls with Dapper?
I need to wrap some calls to methods that are doing async updates and inserts into my database.  All of the methods use this pattern for running the code:

```<code> using (IDbConnection conn = Connection)
            {
                conn.Open();
                //TODO:  Table item quantity for the QTYALLOC field
                var sql = //sql statement;
                int x = await conn.ExecuteAsync(sql);
                return x > 0;
            }
</code>```

Right now all of the methods return a boolean.  I want to wrap the calls in a transaction and either commit or rollback

```<code>                    await [InsertRecord];
                    //add the audit record
                    var addAudit = await [Insert Audit Record];
                    var updateOrd = await [Update Record]
                    var changePickStatus = await [Update Record]
                    if (locs.First().QTYTOTAL - ord.QTYPICKED <= 0)
                    {
                        await [Delete Record]; //delete the record

                    }
                    else
                    {
                        //decrement the quantity for the location and update.
                        locs.First().QTYTOTAL -= ord.QTYPICKED;
                        await [Update Record]

                    }
</code>```

I put the calls to the methods in the square [] brackets.  Right now each call returns a boolean to indicate it was successful or failed, I would like to wrap all these calls in one transaction to commit or rollback based on the outcome of each call.  I don't want to put all the SQL statements into one large call if I can help it, they are long and complex.  Can I pass in a transaction to each method call and apply it to each ExecuteAsync operation?  If so what would I pass back from the method to indicate success or failure?

答:
You can inject the connection/transaction in each method call as parameter.

Following is a sort of pseudo code (syntax may not be accurate):

```<code>using (IDbConnection conn = Connection)
{
    using(var transaction = conn.BeginTransaction())//Begin here
    {
        var addAudit = await [YourMethod(conn)];//Inject as parameter
        if(addAudit == false)
            transaction.Rollback();//Rollback if method call failed
        ...
        ...
        //Repeat same pattern for all method calls
        ...
        transaction.Commit();//Commit when all methods returned success
    }
}
</code>```

The better solution is to use Unit Of Work. But, this is only worth if you are implementing it on much broader level.

Body:
I need to wrap some calls to methods that are doing async updates and inserts into my database.  All of the methods use this pattern for running the code:

 using (IDbConnection conn = Connection)
            {
                conn.Open();
                //TODO:  Table item quantity for the QTYALLOC field
                var sql = //sql statement;
                int x = await conn.ExecuteAsync(sql);
                return x > 0;
            }

Right now all of the methods return a boolean.  I want to wrap the calls in a transaction and either commit or rollback

                    await [InsertRecord];
                    //add the audit record
                    var addAudit = await [Insert Audit Record];
                    var updateOrd = await [Update Record]
                    var changePickStatus = await [Update Record]
                    if (locs.First().QTYTOTAL - ord.QTYPICKED <= 0)
                    {
                        await [Delete Record]; //delete the record

                    }
                    else
                    {
                        //decrement the quantity for the location and update.
                        locs.First().QTYTOTAL -= ord.QTYPICKED;
                        await [Update Record]

                    }

I put the calls to the methods in the square [] brackets.  Right now each call returns a boolean to indicate it was successful or failed, I would like to wrap all these calls in one transaction to commit or rollback based on the outcome of each call.  I don't want to put all the SQL statements into one large call if I can help it, they are long and complex.  Can I pass in a transaction to each method call and apply it to each ExecuteAsync operation?  If so what would I pass back from the method to indicate success or failure?

Body:
You can inject the connection/transaction in each method call as parameter.

Following is a sort of pseudo code (syntax may not be accurate):

using (IDbConnection conn = Connection)
{
    using(var transaction = conn.BeginTransaction())//Begin here
    {
        var addAudit = await [YourMethod(conn)];//Inject as parameter
        if(addAudit == false)
            transaction.Rollback();//Rollback if method call failed
        ...
        ...
        //Repeat same pattern for all method calls
        ...
        transaction.Commit();//Commit when all methods returned success
    }
}

The better solution is to use Unit Of Work. But, this is only worth if you are implementing it on much broader level.