问:
How to accurately calculate age in redshift from a date of birth?
I ran this in Redshift:

```<code>SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-01')/365) as age --1 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-01')/365.25) as age --0 (this seems to undercount)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-02')/365.25) as age --1 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-01')/365) as age --58 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-01')/365.25) as age --57 (this seems to undercount)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-02')/365.25) as age --58 (this seems right)
</code>```

It seems like dividing by 365 just... works which is strange to me and that dividing by 365.25 undercounts the age on the exact birthdate. Is that right? Does redshift just account for leapyears automatically?

Body:
I ran this in Redshift:

SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-01')/365) as age --1 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-01')/365.25) as age --0 (this seems to undercount)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2023-01-02')/365.25) as age --1 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-01')/365) as age --58 (this seems right)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-01')/365.25) as age --57 (this seems to undercount)
SELECT FLOOR(DATEDIFF(day, '2022-01-01', '2080-01-02')/365.25) as age --58 (this seems right)

It seems like dividing by 365 just... works which is strange to me and that dividing by 365.25 undercounts the age on the exact birthdate. Is that right? Does redshift just account for leapyears automatically?


来源: stackexchange

问:
Copying data from an excel to another one using pandas
I have two files that contains data.
The main file has some messy data. The second file already has formulas and it will arrange everything from the messy data.
The problem is: when I'm trying to copy data from the main file, it deletes everything for the second file. I already have the sheet that I need in the second file, I only need to copy the messy data from main file in a specific range.
So it should look like this:
Main file copy data -> Insert into second file with the already sheet created but starting with Row 2 and without deleting anything else.
I couldn't find any solution on this. I am currently at this one but it deletes everything:

df.to_excel(filename_out, sheet_name = sheet_name1, startrow = len(df)+1, header=False, index=False)
```

Searching google, found an incomplete solution and deletes everything.

ContentLicense: CC BY-SA 4.0

Body:
I have two files that contains data.
The main file has some messy data. The second file already has formulas and it will arrange everything from the messy data.
The problem is: when I'm trying to copy data from the main file, it deletes everything for the second file. I already have the sheet that I need in the second file, I only need to copy the messy data from main file in a specific range.
So it should look like this:
Main file copy data -> Insert into second file with the already sheet created but starting with Row 2 and without deleting anything else.
I couldn't find any solution on this. I am currently at this one but it deletes everything:

df.to_excel(filename_out, sheet_name = sheet_name1, startrow = len(df)+1, header=False, index=False)

Searching google, found an incomplete solution and deletes everything.


问:
Unable to Debug Angular 12 project in Chrome Dev tools after upgrade
This project has been upgraded from Angular 6 to Angular 12, one version at a time. The project compiles and works, but I cannot debug it in Chrome dev tools anymore. I do not see my source code. I tried to 'Add folder to Workspace' in Chrome, but then my file gets locked. Obviously, I'm doing something wrong. The Chrome version I have is Version 108.0.5359.95 (Official Build) (64-bit)

I have tried to change my angular.json after reading another post Angular 12 Debug source code not available in Chrome Developer tools was fine in Angular 11

but it is not working for me.
Here's my angular.json

```<code>  {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app-name": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "aot": true,
            "allowedCommonJsDependencies": [
              "xlsx",
              "rxjs/BehaviorSubject",
              "rxjs/add/observable/throw",
              "rxjs/add/operator/catch",
              "rxjs/Observable",
              "rxjs/operators/map",
              "rxjs/operators/tap"
            ],
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.scss",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ],
            "vendorChunk": true,
            "extractLicenses": false,
            "buildOptimizer": false,
            "sourceMap": true,
            "optimization": false,
            "namedChunks": true
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          },
          "development": {
            "optimization": false,
            "sourceMap": true
          },
          "defaultConfiguration": ""
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app-name:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app-name:build:production"
            },
            "development": {
              "browserTarget": "app-name:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app-name:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.js",
              "node_modules/bootstrap/dist/js/bootstrap.js"
            ],
            "styles": [
              {
                "input": "node_modules/@progress/kendo-theme-default/dist/all.css",
                "inject": true
              },
              "src/styles.scss",
              "node_modules/bootstrap/dist/css/bootstrap.css"
            ],
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "app-name-e2e": {
      "root": "",
      "sourceRoot": "",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "app-name:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "e2e/tsconfig.e2e.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "app-name",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "style": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}
</code>```

and my package.json

```<code>{
  "name": "hierarchy",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "prodbuild": "ng build --configuration production --aot=true --output-hashing none",
    "build": "ng build --output-hashing none",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^12.2.15",
    "@angular/common": "^12.2.15",
    "@angular/compiler": "^12.2.15",
    "@angular/core": "^12.2.15",
    "@angular/forms": "^12.2.15",
    "@angular/platform-browser": "^12.2.15",
    "@angular/platform-browser-dynamic": "^12.2.15",
    "@angular/router": "^12.2.15",
    "@progress/kendo-angular-buttons": "^7.0.2",
    "@progress/kendo-angular-common": "^2.0.2",
    "@progress/kendo-angular-dateinputs": "^6.0.0",
    "@progress/kendo-angular-dialog": "^6.0.0",
    "@progress/kendo-angular-dropdowns": "^6.0.0",
    "@progress/kendo-angular-excel-export": "^4.0.3",
    "@progress/kendo-angular-grid": "^6.0.1",
    "@progress/kendo-angular-inputs": "^8.0.0",
    "@progress/kendo-angular-intl": "^3.1.2",
    "@progress/kendo-angular-l10n": "^3.0.3",
    "@progress/kendo-angular-label": "^3.1.2",
    "@progress/kendo-angular-pdf-export": "^3.0.3",
    "@progress/kendo-angular-popup": "^4.0.4",
    "@progress/kendo-angular-tooltip": "^3.1.3",
    "@progress/kendo-angular-treeview": "^6.0.0",
    "@progress/kendo-data-query": "^1.5.5",
    "@progress/kendo-drawing": "^1.16.1",
    "@progress/kendo-licensing": "^1.2.1",
    "@progress/kendo-theme-default": "latest",
    "angular2-notifications": "^12.0.0",
    "bootstrap": "^4.3.1",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.12",
    "dns-packet": "^5.3.0",
    "file-saver": "^2.0.5",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "npm-check": "^5.9.2",
    "popper.js": "^1.16.1",
    "rxjs": "^6.6.7",
    "rxjs-compat": "6.2.2",
    "sass": "^1.49.0",
    "tslib": "^2.0.0",
    "web-animations-js": "^2.3.2",
    "xlsx": "^0.14.5",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.15",
    "@angular/cli": "^12.2.15",
    "@angular/compiler-cli": "^12.2.15",
    "@angular/language-service": "^12.2.15",
    "@angular/localize": "^12.2.15",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "^2.0.10",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.11",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~5.0.1",
    "tslint": "~6.1.0",
    "typescript": "~4.3.5",
    "webpack": "^5.30.0"
  }
}
</code>```

Also, I'm building using command ng build --watch and it is still working. Is this command still appropriate or would you suggest something else?

Body:
This project has been upgraded from Angular 6 to Angular 12, one version at a time. The project compiles and works, but I cannot debug it in Chrome dev tools anymore. I do not see my source code. I tried to 'Add folder to Workspace' in Chrome, but then my file gets locked. Obviously, I'm doing something wrong. The Chrome version I have is Version 108.0.5359.95 (Official Build) (64-bit)

I have tried to change my angular.json after reading another post Angular 12 Debug source code not available in Chrome Developer tools was fine in Angular 11

but it is not working for me.
Here's my angular.json

  {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app-name": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "aot": true,
            "allowedCommonJsDependencies": [
              "xlsx",
              "rxjs/BehaviorSubject",
              "rxjs/add/observable/throw",
              "rxjs/add/operator/catch",
              "rxjs/Observable",
              "rxjs/operators/map",
              "rxjs/operators/tap"
            ],
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.scss",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ],
            "vendorChunk": true,
            "extractLicenses": false,
            "buildOptimizer": false,
            "sourceMap": true,
            "optimization": false,
            "namedChunks": true
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          },
          "development": {
            "optimization": false,
            "sourceMap": true
          },
          "defaultConfiguration": ""
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app-name:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app-name:build:production"
            },
            "development": {
              "browserTarget": "app-name:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app-name:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/popper.js/dist/umd/popper.js",
              "node_modules/bootstrap/dist/js/bootstrap.js"
            ],
            "styles": [
              {
                "input": "node_modules/@progress/kendo-theme-default/dist/all.css",
                "inject": true
              },
              "src/styles.scss",
              "node_modules/bootstrap/dist/css/bootstrap.css"
            ],
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "app-name-e2e": {
      "root": "",
      "sourceRoot": "",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "app-name:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "e2e/tsconfig.e2e.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "app-name",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "style": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

and my package.json

{
  "name": "hierarchy",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "prodbuild": "ng build --configuration production --aot=true --output-hashing none",
    "build": "ng build --output-hashing none",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^12.2.15",
    "@angular/common": "^12.2.15",
    "@angular/compiler": "^12.2.15",
    "@angular/core": "^12.2.15",
    "@angular/forms": "^12.2.15",
    "@angular/platform-browser": "^12.2.15",
    "@angular/platform-browser-dynamic": "^12.2.15",
    "@angular/router": "^12.2.15",
    "@progress/kendo-angular-buttons": "^7.0.2",
    "@progress/kendo-angular-common": "^2.0.2",
    "@progress/kendo-angular-dateinputs": "^6.0.0",
    "@progress/kendo-angular-dialog": "^6.0.0",
    "@progress/kendo-angular-dropdowns": "^6.0.0",
    "@progress/kendo-angular-excel-export": "^4.0.3",
    "@progress/kendo-angular-grid": "^6.0.1",
    "@progress/kendo-angular-inputs": "^8.0.0",
    "@progress/kendo-angular-intl": "^3.1.2",
    "@progress/kendo-angular-l10n": "^3.0.3",
    "@progress/kendo-angular-label": "^3.1.2",
    "@progress/kendo-angular-pdf-export": "^3.0.3",
    "@progress/kendo-angular-popup": "^4.0.4",
    "@progress/kendo-angular-tooltip": "^3.1.3",
    "@progress/kendo-angular-treeview": "^6.0.0",
    "@progress/kendo-data-query": "^1.5.5",
    "@progress/kendo-drawing": "^1.16.1",
    "@progress/kendo-licensing": "^1.2.1",
    "@progress/kendo-theme-default": "latest",
    "angular2-notifications": "^12.0.0",
    "bootstrap": "^4.3.1",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.12",
    "dns-packet": "^5.3.0",
    "file-saver": "^2.0.5",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "npm-check": "^5.9.2",
    "popper.js": "^1.16.1",
    "rxjs": "^6.6.7",
    "rxjs-compat": "6.2.2",
    "sass": "^1.49.0",
    "tslib": "^2.0.0",
    "web-animations-js": "^2.3.2",
    "xlsx": "^0.14.5",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.15",
    "@angular/cli": "^12.2.15",
    "@angular/compiler-cli": "^12.2.15",
    "@angular/language-service": "^12.2.15",
    "@angular/localize": "^12.2.15",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "^2.0.10",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.11",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~5.0.1",
    "tslint": "~6.1.0",
    "typescript": "~4.3.5",
    "webpack": "^5.30.0"
  }
}

Also, I'm building using command ng build --watch and it is still working. Is this command still appropriate or would you suggest something else?


问:
SvelteKit: Unrecoverable HMR error in <+page>: next update will trigger a full reload
I am building a small website and in a page there are a form and a table that displays some query output based on the user input. On first loading, I have no problems because I inserted some code in the onMount function that set up the page. When the used submits the form a second time, the webpage remains the same, but onMount is not triggered. For this reason, I used the $: notation so that each time a new form is submitted, I can set up the page accordingly. The issue is that when I insert the update_buttons() function in the $: part, I get the error displayed in the thread title. Why do I get this error?

```<code><script>
import {onMount} from 'svelte';
import Table from './Table.svelte';
import Criteria from './Criteria.svelte';
import {init_page, update_buttons} from './update-shipments.js';

export let data;

$: {
    document.page=0;
    document.shipments_num=data.shipments_num;
    document.form_input = data.form_input;
    update_buttons();
}

onMount(() => {
    init_page();
    update_buttons();
});
</script>
</code>```

update_buttons function

```<code>export function update_buttons() {
if (document.page==0) {
    document.getElementById("prev-button").disabled=true;
} else {
    document.getElementById("prev-button").disabled=false;
}

if (document.page*30+30>=document.shipments_num) {
    document.getElementById("next-button").disabled=true;
} else {
    document.getElementById("next-button").disabled=false;
}
}
</code>```

Alternatively, is there any way to run some code each time a new form is submitted, even when the page remains the same and the only thing changing are the URL parameters?

As suggested by @Stephane Vanraes i refactored the whole page to to take advantage of the svelte functionalities and now everything works. To be more specific now the buttons are set up like this

```<code><button id="prev-button" class="btn {data.page == 0 ? "disabled" : null}" on:click={() => update_shipments("prev")}>back</button>
<button id="next-button" class="btn {data.page*30+30 >= data.shipments_num ? "disabled" : null}" on:click={() => update_shipments("next")}>forw</button>
</code>```

Meanwhile the query output, like shipments_num is now solely managed as an attributed of the data variable.

Body:
I am building a small website and in a page there are a form and a table that displays some query output based on the user input. On first loading, I have no problems because I inserted some code in the onMount function that set up the page. When the used submits the form a second time, the webpage remains the same, but onMount is not triggered. For this reason, I used the $: notation so that each time a new form is submitted, I can set up the page accordingly. The issue is that when I insert the update_buttons() function in the $: part, I get the error displayed in the thread title. Why do I get this error?

update_buttons function

export function update_buttons() {
if (document.page==0) {
    document.getElementById("prev-button").disabled=true;
} else {
    document.getElementById("prev-button").disabled=false;
}

if (document.page*30+30>=document.shipments_num) {
    document.getElementById("next-button").disabled=true;
} else {
    document.getElementById("next-button").disabled=false;
}
}

Alternatively, is there any way to run some code each time a new form is submitted, even when the page remains the same and the only thing changing are the URL parameters?

As suggested by @Stephane Vanraes i refactored the whole page to to take advantage of the svelte functionalities and now everything works. To be more specific now the buttons are set up like this

<button id="prev-button" class="btn {data.page == 0 ? "disabled" : null}" on:click={() => update_shipments("prev")}>back</button>
<button id="next-button" class="btn {data.page*30+30 >= data.shipments_num ? "disabled" : null}" on:click={() => update_shipments("next")}>forw</button>

Meanwhile the query output, like shipments_num is now solely managed as an attributed of the data variable.


问:
Spatial analysis with R: average linear distance per city
I want to calculate the average linear distance of the households in a given city (city variable) from the city center (coordinates specified in the "city_centre" df) with R.

The city centres are defined in this dataframe.

```<code>city_centre <- dplyr::tibble(
  city = c("a", "b", "c", "d"),
  longitude = c(1,10,1,0),
  latitude = c(1,12,11,22))
</code>```

The household location is defined in this dataframe.

```<code>df <- dplyr::tibble(
  household=(as,aw,as,ae,rt,ag,re,sfr,rt,sd)
  city_centre = c("a","a","b","b","c","c","d","d","d","d"),
  longitude = c(1,4,5,6,7,8,9,10,1,0),
  latitude = c(1,5,6,7,8,9,9,12,11,22))
</code>```

Any ideas?

Body:
I want to calculate the average linear distance of the households in a given city (city variable) from the city center (coordinates specified in the "city_centre" df) with R.

The city centres are defined in this dataframe.

city_centre <- dplyr::tibble(
  city = c("a", "b", "c", "d"),
  longitude = c(1,10,1,0),
  latitude = c(1,12,11,22))

The household location is defined in this dataframe.

df <- dplyr::tibble(
  household=(as,aw,as,ae,rt,ag,re,sfr,rt,sd)
  city_centre = c("a","a","b","b","c","c","d","d","d","d"),
  longitude = c(1,4,5,6,7,8,9,10,1,0),
  latitude = c(1,5,6,7,8,9,9,12,11,22))

Any ideas?


问:
Completely mask query URLs with folder structure URLs using Nginx
I use a ecommerce platform where I do not have access to their hosting space, but I do own and control the domain name and point the nameservers for instance to the third party.

My goal is to mask search query URLs with non-query URLs

I would like to standup a nginx server in front of that platform and rewrite URLs

The browser should ideally not know be aware of the rewrite

Example:

URL with query string is https://website.com/store?search=red+shirts

URL without query string is https://website.com/store/red_shirts

I would like to go to the URL without a query string and the search results page from the URL with query string to appear

Moreover, I would like the URL that is visible in the browser to be the URL without query string

And I would like to be able to adjust the canonical to reflect the URL without the query string

Essentially I would like the browser to be unaware of the URL with query string and in all cases use the URL without query string

Is this possible in Nginx where I control the domain name (and DNS for example) but not the hosting of the store?

I tried a test running Nginx on my computer and writing a proxy_pass however this did not change the way that the browser displayed the URL once it landed on the website, that is to say the URL without query did redirect to the URL with query string, but the URL displayed in browser was the URL with query string, which does not really hide that its a query string, which is my goal.

Any more experienced voice that could point me in the right direction would be great,

Thanks!


问:
How to convert JSX to a string that represents it's original code, not the rendered output?
I can covert JSX to a rendered output like so:

```<code>import { renderToString } from 'react-dom/server'

renderToString(<YourAwesomeComponent props1="value1" props2={{ value: '2' }} />)
</code>```

which yields:

```<code><div> ... </div>
</code>```

In other words, the text is what would end up in the browser.

The text I want to get is the original code:

```<code>"<YourAwesomeComponent props1=\"value1\" props2={{ value: '2' }} />"
</code>```

How can this be done?

Thanks,

Eduardo

Body:
I can covert JSX to a rendered output like so:

import { renderToString } from 'react-dom/server'

renderToString(<YourAwesomeComponent props1="value1" props2={{ value: '2' }} />)

which yields:

 ...

In other words, the text is what would end up in the browser.

The text I want to get is the original code:

"<YourAwesomeComponent props1=\"value1\" props2={{ value: '2' }} />"

How can this be done?

Thanks,

Eduardo


问:
Script not executing on click
I have a python script on my desktop that I want to execute by clicking on it. I have permissions set and all that, but it won't launch by clicking on it.
I can start it using the terminal and everything works as expected.

Here's the script:

```<code>#!/usr/bin/env/python
import subprocess

subprocess.run(['python', '/filepath/EDITOR.py'])

subprocess.run(['python', '/filepath/ULTRASOUND_SIMULATOR.py'])
</code>```

I've been able to launch the "ULTRASOUND_SIMULATOR.py" script from the desktop with a click.

Title: Script not executing on click

Body:
I have a python script on my desktop that I want to execute by clicking on it. I have permissions set and all that, but it won't launch by clicking on it.
I can start it using the terminal and everything works as expected.

Here's the script:

#!/usr/bin/env/python
import subprocess

subprocess.run(['python', '/filepath/EDITOR.py'])

subprocess.run(['python', '/filepath/ULTRASOUND_SIMULATOR.py'])

I've been able to launch the "ULTRASOUND_SIMULATOR.py" script from the desktop with a click.


问:
Ng Select is not showing, Cannot read Properties of null
I am working with Angular 11 and I have installed ng select module version 6 since the latest one did not work with my current Angular version for this project, and according to their table this is the best fitting version for Angular 11.

The problem I am facing is that even after doing the right imports with no errors on app.module nor on the component I am working on, the console throws this error claiming there is a null property:

I am just testing with the default example given on their github page but still, no success. Although, I have tried following the same steps on another project (running Angular 15 with the latest version of ng select) and it worked just well.

Here is the the HTML code:

```<code><ng-select [items]="cars" bindLabel="name" bindValue="id" [(ngModel)]="selectedCar">
</ng-select>
</code>```

The .ts of this component:

```<code>  selectedCar: number;

  cars = [
    { id: 1, name: 'Volvo' },
    { id: 2, name: 'Saab' },
    { id: 3, name: 'Opel' },
    { id: 4, name: 'Audi' },
  ];
</code>```

The imports:

```<code>import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { ReactiveFormsModule } from '@angular/forms';
</code>```

I've also imported the style file on my styles.scss (the global style file for the project):

```<code>@import '~@ng-select/ng-select/themes/default.theme.css';
</code>```

I would appreciate any help to understand the cause of this issue. Thanks in advance.

Body:
I am working with Angular 11 and I have installed ng select module version 6 since the latest one did not work with my current Angular version for this project, and according to their table this is the best fitting version for Angular 11.

The problem I am facing is that even after doing the right imports with no errors on app.module nor on the component I am working on, the console throws this error claiming there is a null property:

I am just testing with the default example given on their github page but still, no success. Although, I have tried following the same steps on another project (running Angular 15 with the latest version of ng select) and it worked just well.

Here is the the HTML code:

<ng-select [items]="cars" bindLabel="name" bindValue="id" [(ngModel)]="selectedCar">
</ng-select>

The .ts of this component:

  selectedCar: number;

  cars = [
    { id: 1, name: 'Volvo' },
    { id: 2, name: 'Saab' },
    { id: 3, name: 'Opel' },
    { id: 4, name: 'Audi' },
  ];

The imports:

import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { ReactiveFormsModule } from '@angular/forms';

I've also imported the style file on my styles.scss (the global style file for the project):

@import '~@ng-select/ng-select/themes/default.theme.css';

I would appreciate any help to understand the cause of this issue. Thanks in advance.


问:
Rename files to match other file by matching first part of file name with eg. PowerShell
OK, this was hard to put into title, needs more explaining.

I have two folders with 1000+ files (and I'll need to do this multiple times).

One folder (let's say "folder1") has file for example:
Banner_1_border_n-sharedassets1.assets-2101.png

Other folder (let's say "folder2") has file that's very similar in name eg:
Banner_1_border_n-sharedassets1.assets-1022.png

Now, to the best of my knowledge:

all files are always .png

only last 4 numbers after dash "-" and before .png are "variable"

other dashes "-" will also occur in file in other places

there will never be two files with same name in same folder, eg, same folder will never have banner-1234.png and banner-4321.png at any point in time

files would generally be named -sharedassets.assets-.png

My idea was to do something like this:

fetch all children of the folder1 (there aren't any subfolders)

parse file names with regex (I'm really bad at regex) and split them to prefix + 4-numbers + .png

do same with folder2

go through list item by item

find files in folder2 that match files in folder1 and change that 4-number part to what's in folder1

I think I could do this using Excel and bat file, but something tells me few lines of PowerShell would do it faster than me manually or doing the manual "mail-merge" like procedure using batch files and Excel ;D

I'd appreciate any help! Specially with regex, as I'm pretty sure regex will be part of it (mighty tool, but my brain keeps rejecting it's logic)

I've started to manually change names, but it would take several hours every time I do this.

Thanks!


问:
Check if generic extends shape, keep shape
I am trying to create a function that accepts generic type only of certain shape

```<code>interface RequiredVars {
  foo: number
}

interface Config<Query, QueryVars> {
  query: TypedDocumentNode<Query, QueryVars>;
  queryOptions: QueryHookOptions<Query, QueryVars>;
}

function foo<Query, QueryVars>(config: Config<Query, QueryVars>) {
  // function body
}
</code>```

TypedDocumentNode and QueryHookOptions are types from @apollo/client, but this i believe is not relevant in this situation.

First thing that came to my mind is narrowing like this:

```<code>function foo<Query, QueryVars extends RequiredVars>(config: Config)
</code>```

but doing this means losing original shape of QueryVars and type passed to QueryHookOptions includes only foo: number

Is it possible to allow only QueryVars that has foo: number but keep its original shape?

If I call foo like this:

```<code>const query: TypedDocumentNode<{...}, {foo: number; bar: string}>

foo({
  query,
  queryOptions: {
    // this keeps bar: string in its type
  }
})
</code>```

And if by mistake I pass QueryVars without foo:number I get a typescript error?

Body:
I am trying to create a function that accepts generic type only of certain shape

interface RequiredVars {
  foo: number
}

interface Config<Query, QueryVars> {
  query: TypedDocumentNode<Query, QueryVars>;
  queryOptions: QueryHookOptions<Query, QueryVars>;
}

function foo<Query, QueryVars>(config: Config<Query, QueryVars>) {
  // function body
}

TypedDocumentNode and QueryHookOptions are types from @apollo/client, but this i believe is not relevant in this situation.

First thing that came to my mind is narrowing like this:

function foo<Query, QueryVars extends RequiredVars>(config: Config)

but doing this means losing original shape of QueryVars and type passed to QueryHookOptions includes only foo: number

Is it possible to allow only QueryVars that has foo: number but keep its original shape?

If I call foo like this:

const query: TypedDocumentNode<{...}, {foo: number; bar: string}>

foo({
  query,
  queryOptions: {
    // this keeps bar: string in its type
  }
})

And if by mistake I pass QueryVars without foo:number I get a typescript error?


问:
How to set props of original component?
I hope I'm making sense. I am trying to implement a MathLive component in react. There is a react-mathlive library however I believe that it is outdated and to use it I would need to install an older version of math live. https://github.com/concludio/react-mathlive/issues/34

I have been trying to implement a solution for hours and I was never able to get anything to work. All that I want to do is add an onChange attribute to a <math-field> "component". The <math-field> is not an actual react component but an actual html element. I have read the math live docs and to detect change all you need to do is set the onChange attribute. However, this does nothing when added directly into the react compoment. <math-field onChange={() => alert("alert")} value={"x"}></math-field>. I believe this to be due to the onChange prop being a react prop and not a prop of the actual html element, although I may be way off. All I want to do is set the onChange of the original html element. Such that in the actual html file the component will render to look like <math-field onChange="myFunc" value="x"></math-field> where myFunc is the function called when changed.

My code is essentially:

```<code>import * as React from 'react';

const App = () => {
    return (
        <math-field onChange={() => alert("hi")} value={"x"}></math-field>
    )
}

export default App
</code>```

edit: I have imported the Mathlive library correctly in the base html file such that

```<code><script defer src="//unpkg.com/mathlive"></script>
</code>```

Title: How to set props of original component?

Body:
I hope I'm making sense. I am trying to implement a MathLive component in react. There is a react-mathlive library however I believe that it is outdated and to use it I would need to install an older version of math live. https://github.com/concludio/react-mathlive/issues/34

I have been trying to implement a solution for hours and I was never able to get anything to work. All that I want to do is add an onChange attribute to a <math-field> "component". The <math-field> is not an actual react component but an actual html element. I have read the math live docs and to detect change all you need to do is set the onChange attribute. However, this does nothing when added directly into the react compoment. <math-field onChange={() => alert("alert")} value={"x"}></math-field>. I believe this to be due to the onChange prop being a react prop and not a prop of the actual html element, although I may be way off. All I want to do is set the onChange of the original html element. Such that in the actual html file the component will render to look like <math-field onChange="myFunc" value="x"></math-field> where myFunc is the function called when changed.

My code is essentially:

import * as React from 'react';

const App = () => {
    return (
        <math-field onChange={() => alert("hi")} value={"x"}></math-field>
    )
}

export default App

edit: I have imported the Mathlive library correctly in the base html file such that


问:
How do I get the y value of an axisRange in amcharts?
I have a line series chart and I want to add a draggable series range label. On drag event of the label, I want to print the Y value of the chart where the range label is. How can I achieving this?

I've attached an image to make it easier to visualize and understand what I am trying to achieve.

This is what I have tried in code but the value i'm getting is not consistently correct.

const cursorPosition = {
  x: 0,
  y: 0,
}

chart.cursor.events.on('cursorpositionchanged', (ev: any) => {
  const xAxis = ev.target.chart.xAxes.getIndex(0)
  const yAxis = ev.target.chart.yAxes.getIndex(0)
  cursorPosition.x = xAxis.positionToDate(xAxis.toAxisPosition(ev.target.xPosition))
  cursorPosition.y = yAxis.positionToValue(yAxis.toAxisPosition(ev.target.yPosition))
})

const maxRange = valueAxis.axisRanges.create()
maxRange.value = props.max
maxRange.grid.stroke = am4core.color('#00695C')
maxRange.grid.strokeWidth = 2
maxRange.grid.strokeOpacity = 1
maxRange.label.text = 'max'
maxRange.label.fontSize = '18px'
maxRange.label.scale = 0.7
maxRange.label.background.fill = maxRange.grid.stroke
maxRange.label.fill = am4core.color('#fff')
maxRange.label.draggable = true
maxRange.label.inside = true
maxRange.label.x = 0
maxRange.label.y = 0
maxRange.label.isMeasured = true

// Position of max label maxRange.label.maxX = 58
maxRange.label.minX = 58

maxRange.label.events.on('dragged', () => {
  maxRange.value = valueAxis.positionToValue(
    valueAxis.renderer.coordinateToPosition(valueAxis.renderer.pixelHeight - maxRange.label.pixelY)
  )

  console.log(cursorPosition.x)
})
```


问:
Stop Direct Access pop up messages
Windows 10 active directory shows a pop up message remembering me to reconnect a machine to Direct Access every time

is there any way to stop this annoying pop up?

I would like to know how to stop this pop up notification

Title: Stop Direct Access pop up messages


问:
VS Code - Git "Please enter the commit message for your changes". I do, I can't get it to to commit
I had a complex merge that ended up in Visual Studio Code's output that starts with this:

Please enter the commit message for your changes. Lines starting with
'#' will be ignored, and an empty message aborts the commit. On branch
master Your branch and 'origin/master' have diverged, and have 12 and
27 different commits each, respectively. (use "git pull" to merge the
remote branch into yours)

This is a remote branch being merged to master, so I can't merge "the remote branch into yours", I already am).

No matter what I do to modify this file, it won't commit.  I notice in the VS Code output that it just seems to loop?

I've seen examples of how to easily get around this in editors like Vim but this is VS Code, and have not seen any answers.


问:
Migrate to Next JS using Next Auth for existing hashed and encrypted passwords in mongo DB using JWT and Crypto
I already devlep an app using MERN Stack.

But I want to migrate the app to NEXT JS.

The problem is that I have a lot of active users that logs in with MAIL and PASSWORD. And I do not know how to migrate from the current process to NEXT AUTH without causing any problem to the active users on the log in process.

Right now the process I follow to authenticate users is:

I got a signout route where I extract the data from the user

```<code> exports.signup = (req, res) => {
 //Obtain data from body
 const { name, email, password } =
     req.body;

 //Validate if mail exists
 User.findOne({ email }).exec(async (err, user) => {
     if (user) {
         //Send errror message if exists
         return res.status(400).json({
             error: "Correo electronico ya registrado!",
         });
     }

     //Gen token with JWT
     const token = jwt.sign(
         { name, email, password, colNum, specialty, cellPhone, gender, currency },
         process.env.JWT_ACCOUNT_ACTIVATION,
         { expiresIn: "59m" },
     );

     //Email Template
     //Send email to verify mail and activate account, the email contains the token in the clicleable URL
     const { subject, body, message } = mailRegister(token, email);

     //AWS Email Sender
     const responseEmailAWS = await emailSenderAWS(body, subject, email, message);

     return res.json({
         message: responseEmailAWS,
     });
 });
</code>```

};

From here the user receives an email in the INBOX from the app with a clickeable link
When the user clics the URL calls an api to "Activate"the account.

```<code>exports.accountActivation = (req, res) => {
    //get the token from the req
    const { token } = req.body;

    if (token) {
        jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION, function (err, decoded) {
            if (err) {
                console.log("ERROR MSG --> JWT VERIFY IN ACCOUNT ACTIVATION ERROR", err);
                return res.status(401).json({
                    error: "Link EXPIRADO. Ingrese de nuevo",
                });
            }

            const { name, email, password } =
                jwt.decode(token);

            const user = User({
                name,
                email,
                password,
            });

            user.save((err, user) => {
                if (err) {
                    console.log("ERROR MSG --> SAVE USER IN ACCOUNT ACTIVATION ERROR", err);
                    return res.status(401).json({
                        error: "Error guardando el usuario en la base de datos. Intente de nuevo por favor!",
                    });
                }

                return res.json({
                    message: "Registro EXITOSO! por favor ingrese a su cuenta en INGRESAR!",
                });
            });
        });
    } else {
        return res.json({
            message: "Algo ocurrio!... intente de nuevo por favor!",
        });
    }
};
</code>```

Now the Model of Mongo DB has some trick code to never know the password the user uses in DB
This is the model:

```<code>const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const crypto = require('crypto');

const userSchema = new mongoose.Schema(
    {
        //Basic Data
        name: {
            type: String,
            trim: true,
            required: true,
            maxlength: 32,
        },
        email: {
            type: String,
            trim: true,
            required: true,
            unique: true,
        },
        hashed_password: {
            type: String,
            required: true,
        },
        salt: {
            type: String,
        },
        resetPasswordLink: {
            type: String,
            default: '',
        },

    },
    { timestamps: true }
);

// virtual field
userSchema
    .virtual('password')
    .set(function (password) {
        // create a temporarity variable called _password
        this._password = password;
        // generate salt
        this.salt = this.makeSalt();
        // encryptPassword
        this.hashed_password = this.encryptPassword(password);
    })
    .get(function () {
        return this._password;
    });

//  Methods
userSchema.methods = {
    // Method Authenticate User
    authenticate: function (plainText) {
        return this.encryptPassword(plainText) === this.hashed_password; //  Ture or False
    },
    // Method Encrypt Pass
    encryptPassword: function (password) {
        if (!password) return '';
        try {
            return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
        } catch (err) {
            return '';
        }
    },

    // Method Make Salt
    makeSalt: function () {
        return Math.round(new Date().valueOf() * Math.random()) + '';
    },
};

module.exports = mongoose.model('User', userSchema);
</code>```

What makes the code above is give some functions to encrypt passwords using Crypto and make some functions to make more secure the "Forgot" password.

Somebody can help me, to migrate from MERN to NEXT JS???
I dont know if I can implament the same logic of authentication in NEXT JS or using NEXT Auth or if there are a better choice?

The objective is make "Transparent" the migration for the active users that already have a mail and password (Encrypted) saved on the DB.

Body:
I already devlep an app using MERN Stack.

But I want to migrate the app to NEXT JS.

The problem is that I have a lot of active users that logs in with MAIL and PASSWORD. And I do not know how to migrate from the current process to NEXT AUTH without causing any problem to the active users on the log in process.

Right now the process I follow to authenticate users is:

I got a signout route where I extract the data from the user

 exports.signup = (req, res) => {
 //Obtain data from body
 const { name, email, password } =
     req.body;

 //Validate if mail exists
 User.findOne({ email }).exec(async (err, user) => {
     if (user) {
         //Send errror message if exists
         return res.status(400).json({
             error: "Correo electronico ya registrado!",
         });
     }

     //Gen token with JWT
     const token = jwt.sign(
         { name, email, password, colNum, specialty, cellPhone, gender, currency },
         process.env.JWT_ACCOUNT_ACTIVATION,
         { expiresIn: "59m" },
     );

     //Email Template
     //Send email to verify mail and activate account, the email contains the token in the clicleable URL
     const { subject, body, message } = mailRegister(token, email);

     //AWS Email Sender
     const responseEmailAWS = await emailSenderAWS(body, subject, email, message);

     return res.json({
         message: responseEmailAWS,
     });
 });

};

From here the user receives an email in the INBOX from the app with a clickeable link
When the user clics the URL calls an api to "Activate"the account.

exports.accountActivation = (req, res) => {
    //get the token from the req
    const { token } = req.body;

    if (token) {
        jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION, function (err, decoded) {
            if (err) {
                console.log("ERROR MSG --> JWT VERIFY IN ACCOUNT ACTIVATION ERROR", err);
                return res.status(401).json({
                    error: "Link EXPIRADO. Ingrese de nuevo",
                });
            }

            const { name, email, password } =
                jwt.decode(token);

            const user = User({
                name,
                email,
                password,
            });

            user.save((err, user) => {
                if (err) {
                    console.log("ERROR MSG --> SAVE USER IN ACCOUNT ACTIVATION ERROR", err);
                    return res.status(401).json({
                        error: "Error guardando el usuario en la base de datos. Intente de nuevo por favor!",
                    });
                }

                return res.json({
                    message: "Registro EXITOSO! por favor ingrese a su cuenta en INGRESAR!",
                });
            });
        });
    } else {
        return res.json({
            message: "Algo ocurrio!... intente de nuevo por favor!",
        });
    }
};

Now the Model of Mongo DB has some trick code to never know the password the user uses in DB
This is the model:

const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const crypto = require('crypto');

const userSchema = new mongoose.Schema(
    {
        //Basic Data
        name: {
            type: String,
            trim: true,
            required: true,
            maxlength: 32,
        },
        email: {
            type: String,
            trim: true,
            required: true,
            unique: true,
        },
        hashed_password: {
            type: String,
            required: true,
        },
        salt: {
            type: String,
        },
        resetPasswordLink: {
            type: String,
            default: '',
        },

    },
    { timestamps: true }
);

// virtual field
userSchema
    .virtual('password')
    .set(function (password) {
        // create a temporarity variable called _password
        this._password = password;
        // generate salt
        this.salt = this.makeSalt();
        // encryptPassword
        this.hashed_password = this.encryptPassword(password);
    })
    .get(function () {
        return this._password;
    });

//  Methods
userSchema.methods = {
    // Method Authenticate User
    authenticate: function (plainText) {
        return this.encryptPassword(plainText) === this.hashed_password; //  Ture or False
    },
    // Method Encrypt Pass
    encryptPassword: function (password) {
        if (!password) return '';
        try {
            return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
        } catch (err) {
            return '';
        }
    },

    // Method Make Salt
    makeSalt: function () {
        return Math.round(new Date().valueOf() * Math.random()) + '';
    },
};

module.exports = mongoose.model('User', userSchema);

What makes the code above is give some functions to encrypt passwords using Crypto and make some functions to make more secure the "Forgot" password.

Somebody can help me, to migrate from MERN to NEXT JS???
I dont know if I can implament the same logic of authentication in NEXT JS or using NEXT Auth or if there are a better choice?

The objective is make "Transparent" the migration for the active users that already have a mail and password (Encrypted) saved on the DB.


问:
Gower distance with KNeighborsClassifier sklearn
To use KNN with mixed dataset, I decided to use Gower distance.
However, my implementation doesn't work.

```<code>import gower
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
titanic_df = pd.read_csv("https://raw.githubusercontent.com/ID2223KTH/id2223kth.github.io/master/assignments/lab1/titanic.csv")
# removing columns not useful for prediction
titanic_df.drop(["PassengerId","Cabin","Name","Ticket"],inplace=True,axis = 1)
# removing rows with null values
titanic_df = titanic_df.dropna()
y = titanic_df["Survived"].values
titanic_df.drop(["Survived"],inplace=True,axis = 1)
X = titanic_df.values
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=42)
X_train = X_train.tolist()
#convert X_train into a dataframe so that can be used as input to gower_matrix()
Xd = pd.DataFrame({'Pclass':[],'Sex':[],'Age':[], 'SibSp':[], 'Parch':[],'Fare':[],'Embarked':[]})
for i in range(len(X_train)):
    Xd.at[i,'Pclass'] = X_train[i][0]
    Xd.at[i,'Sex'] = X_train[i][1]
    Xd.at[i,'Age'] = X_train[i][2]
    Xd.at[i,'SibSp'] = X_train[i][3]
    Xd.at[i,'Parch'] = X_train[i][4]
    Xd.at[i,'Fare'] = X_train[i][5]
    Xd.at[i,'Embarked'] = X_train[i][6]
model = KNeighborsClassifier(metric="precomputed").fit(gower.gower_matrix(Xd), y_train)
#convert X_test into a dataframe so that can be used as input to gower_matrix()
Xd = pd.DataFrame({'Pclass':[],'Sex':[],'Age':[], 'SibSp':[], 'Parch':[],'Fare':[],'Embarked':[]})
for i in range(len(X_test)):
    Xd.at[i,'Pclass'] = X_test[i][0]
    Xd.at[i,'Sex'] = X_test[i][1]
    Xd.at[i,'Age'] = X_test[i][2]
    Xd.at[i,'SibSp'] = X_test[i][3]
    Xd.at[i,'Parch'] = X_test[i][4]
    Xd.at[i,'Fare'] = X_test[i][5]
    Xd.at[i,'Embarked'] = X_test[i][6]
print(model.score(gower.gower_matrix(Xd), y_test)) #ERROR: Precomputed metric requires shape (n_queries, n_indexed). Got (235, 235) for 477 indexed.
</code>```

I don't fully understand how to work with 'precomputed' distance metric and I cannot find a resource that explains this well in detail, perhaps with an example.

Body:
To use KNN with mixed dataset, I decided to use Gower distance.
However, my implementation doesn't work.

import gower
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
titanic_df = pd.read_csv("https://raw.githubusercontent.com/ID2223KTH/id2223kth.github.io/master/assignments/lab1/titanic.csv")
# removing columns not useful for prediction
titanic_df.drop(["PassengerId","Cabin","Name","Ticket"],inplace=True,axis = 1)
# removing rows with null values
titanic_df = titanic_df.dropna()
y = titanic_df["Survived"].values
titanic_df.drop(["Survived"],inplace=True,axis = 1)
X = titanic_df.values
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=42)
X_train = X_train.tolist()
#convert X_train into a dataframe so that can be used as input to gower_matrix()
Xd = pd.DataFrame({'Pclass':[],'Sex':[],'Age':[], 'SibSp':[], 'Parch':[],'Fare':[],'Embarked':[]})
for i in range(len(X_train)):
    Xd.at[i,'Pclass'] = X_train[i][0]
    Xd.at[i,'Sex'] = X_train[i][1]
    Xd.at[i,'Age'] = X_train[i][2]
    Xd.at[i,'SibSp'] = X_train[i][3]
    Xd.at[i,'Parch'] = X_train[i][4]
    Xd.at[i,'Fare'] = X_train[i][5]
    Xd.at[i,'Embarked'] = X_train[i][6]
model = KNeighborsClassifier(metric="precomputed").fit(gower.gower_matrix(Xd), y_train)
#convert X_test into a dataframe so that can be used as input to gower_matrix()
Xd = pd.DataFrame({'Pclass':[],'Sex':[],'Age':[], 'SibSp':[], 'Parch':[],'Fare':[],'Embarked':[]})
for i in range(len(X_test)):
    Xd.at[i,'Pclass'] = X_test[i][0]
    Xd.at[i,'Sex'] = X_test[i][1]
    Xd.at[i,'Age'] = X_test[i][2]
    Xd.at[i,'SibSp'] = X_test[i][3]
    Xd.at[i,'Parch'] = X_test[i][4]
    Xd.at[i,'Fare'] = X_test[i][5]
    Xd.at[i,'Embarked'] = X_test[i][6]
print(model.score(gower.gower_matrix(Xd), y_test)) #ERROR: Precomputed metric requires shape (n_queries, n_indexed). Got (235, 235) for 477 indexed.

I don't fully understand how to work with 'precomputed' distance metric and I cannot find a resource that explains this well in detail, perhaps with an example.


问:
Running Start-Job from cmd.exe without having to wait with Wait-Job
I was assuming that it is possible to start a process in PowerShell using Start-Job without having to wait for its completion. But apparently is not the case when I'm starting PowerShell from cmd.exe because I have to use the Wait-Job cmdlet.

So I have two files:

my-hook-runner.cmd

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\mydir\my-hook-ps.ps1
</code>```

my-hook-ps.ps1

```<code>Start-Job -ScriptBlock { gci C:\mydir | Out-File C:\mydir\test.txt }
</code>```

The script my-hook-ps.ps1 creates a job and it adds the test.txt file when I run it from PowerShell console. But when I run my-hook-runner.cmd or powershell.exe C:\mydir\my-hook-ps.ps1 in cmd.exe, the file text.txt is not added although the job is created.

It works when I pipe Start-Job into Wait-Job but this negates all the benefits of using these jobs because I have to wait for their completion.

Since the ps1 file is not executable on Windows, I have to start it from cmd.exe, and I want to spawn a detached process that lives on its own (because of this Running another program in Windows bat file and not create child process).

The behavior is similar or identical to the one described at https://social.technet.microsoft.com/Forums/ie/en-US/a2c4741d-8c6b-4277-afcd-bbdc73ca8deb/startjob-works-from-powershell-but-not-from-cmd?forum=winserverpowershell.

I'd appreciate any comments, suggestions and also answers to the following questions:

Why the PowerShell job works when I run it from PowerShell but does not work when I run it from cmd.exe? Is this about closing the job's PSSession when it hasn't yet finished running?

Is it possible to start PowerShell jobs from cmd.exe without waiting for their completion?

Body:
I was assuming that it is possible to start a process in PowerShell using Start-Job without having to wait for its completion. But apparently is not the case when I'm starting PowerShell from cmd.exe because I have to use the Wait-Job cmdlet.

So I have two files:

my-hook-runner.cmd

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\mydir\my-hook-ps.ps1

my-hook-ps.ps1

Start-Job -ScriptBlock { gci C:\mydir | Out-File C:\mydir\test.txt }

The script my-hook-ps.ps1 creates a job and it adds the test.txt file when I run it from PowerShell console. But when I run my-hook-runner.cmd or powershell.exe C:\mydir\my-hook-ps.ps1 in cmd.exe, the file text.txt is not added although the job is created.

It works when I pipe Start-Job into Wait-Job but this negates all the benefits of using these jobs because I have to wait for their completion.

Since the ps1 file is not executable on Windows, I have to start it from cmd.exe, and I want to spawn a detached process that lives on its own (because of this Running another program in Windows bat file and not create child process).

The behavior is similar or identical to the one described at https://social.technet.microsoft.com/Forums/ie/en-US/a2c4741d-8c6b-4277-afcd-bbdc73ca8deb/startjob-works-from-powershell-but-not-from-cmd?forum=winserverpowershell.

I'd appreciate any comments, suggestions and also answers to the following questions:

Why the PowerShell job works when I run it from PowerShell but does not work when I run it from cmd.exe? Is this about closing the job's PSSession when it hasn't yet finished running?

Is it possible to start PowerShell jobs from cmd.exe without waiting for their completion?


问:
How to know when handle returned by CfOpenFileWithOplock has been closed
CfOpenFileWithOplock is documented to have the following behavior:

When the oplock is broken, the API will handle the break notification
automatically on behalf of the caller by draining all active requests
and then closing the underneath Win32 handle.

This aims to removing the complexity related to oplock usages.

How do clients of this API understand when the handle they have been given has been closed implicitly?

In all practical cases, the client will receive ERROR_INVALID_HANDLE as the result of any further operations utilizing the handle, but this isn't very robust since handle values can eventually be reused (and then operating on the handle may succeed but may not be working on the file that it was intended to operate on).

Is there some way that the client code can detect or get notified that the handle was closed?


问:
Jenkins Gerrit trigger on all branches except master/main/origin and other's branches
I have a build in Jenkins triggered by Gerrit and it is being triggered by every change patchset that is being pushed by every user. I am testing my changes and just want to trigger this only my change for now and then I will open for others.

so I would like to trigger NOT on all branches or master or main but ONLY on my pushed change. What regex should I use for this? or is there other approach?

example: my private unmerged change on gerrit looks like this and I want jenkins to trigger only when there is a change to 95001 and it should only affect this change.

https://gerrit.company.com/r/c/honda/+/95001

below is my trigger that is triggering for everything. how would i set it to do only for my change and not trouble others.?

on gerrit gui i see

```<code>Repo | Branch   honda | main
</code>```
```<code>       gerrit(
         buildCancellationPolicy: buildCancellationPolicy(abortManualPatchsets: false, abortNewPatchsets: false, abortSameTopic: false),
         customUrl: '',
         gerritProjects: [[
             branches: [[compareType: 'PLAIN', pattern: 'main']],
             compareType: 'PLAIN',
             disableStrictForbiddenFileVerification: false,
             pattern: 'honda'
         ]],
         serverName: 'gerrit.company.com',
         silentMode: true,
         silentStartMode: true,
         skipVote: [onAborted: true, onFailed: true, onNotBuilt: true, onSuccessful: true, onUnstable: true],
         triggerOnEvents: [patchsetCreated(excludeDrafts: true)],
       )
     }
</code>```

Body:
I have a build in Jenkins triggered by Gerrit and it is being triggered by every change patchset that is being pushed by every user. I am testing my changes and just want to trigger this only my change for now and then I will open for others.

so I would like to trigger NOT on all branches or master or main but ONLY on my pushed change. What regex should I use for this? or is there other approach?

example: my private unmerged change on gerrit looks like this and I want jenkins to trigger only when there is a change to 95001 and it should only affect this change.

https://gerrit.company.com/r/c/honda/+/95001

below is my trigger that is triggering for everything. how would i set it to do only for my change and not trouble others.?

on gerrit gui i see

Repo | Branch   honda | main

       gerrit(
         buildCancellationPolicy: buildCancellationPolicy(abortManualPatchsets: false, abortNewPatchsets: false, abortSameTopic: false),
         customUrl: '',
         gerritProjects: [[
             branches: [[compareType: 'PLAIN', pattern: 'main']],
             compareType: 'PLAIN',
             disableStrictForbiddenFileVerification: false,
             pattern: 'honda'
         ]],
         serverName: 'gerrit.company.com',
         silentMode: true,
         silentStartMode: true,
         skipVote: [onAborted: true, onFailed: true, onNotBuilt: true, onSuccessful: true, onUnstable: true],
         triggerOnEvents: [patchsetCreated(excludeDrafts: true)],
       )
     }


问:
npm ERR - gyp ERR
I was trying to install packages using npm. I am getting this long error and tried multiple ways but no luck. I downloaded the source code from https://github.com/creativetimofficial/argon-dashboard-react-nodejs/fork

I have installed node : Node.js v19.3.0.

Error:

```<code>npm ERR! gyp verb get node dir target node version installed: 19.3.0
npm ERR! gyp verb build dir attempting to create "build" dir: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build
npm ERR! gyp verb build dir "build" dir needed to be created? /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build
npm ERR! gyp verb build/config.gypi creating config file
npm ERR! gyp verb build/config.gypi writing out config file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build/config.gypi
npm ERR! gyp verb config.gypi checking for gypi file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/config.gypi
npm ERR! gyp verb common.gypi checking for gypi file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/common.gypi
npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! gyp info spawn /usr/bin/python2
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/root/.node-gyp/19.3.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/root/.node-gyp/19.3.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/root/.node-gyp/19.3.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding.gyp
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/lib/configure.js:345:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:293:12)
npm ERR! gyp ERR! System Linux 5.4.0-135-generic
npm ERR! gyp ERR! command "/usr/local/bin/node" "/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass
npm ERR! gyp ERR! node -v v19.3.0
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-21T21_40_45_359Z-debug-0.log
</code>```

My package.json file

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-free": "5.12.1",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "chart.js": "2.9.3",
    "classnames": "2.2.6",
    "moment": "2.24.0",
    "node-sass": "4.13.1",
    "nouislider": "14.1.1",
    "react": "16.12.0",
    "react-bootstrap": "^1.4.0",
    "react-chartjs-2": "2.9.0",
    "react-copy-to-clipboard": "5.0.2",
    "react-datetime": "2.16.3",
    "react-dom": "16.12.0",
    "react-google-maps": "9.4.5",
    "react-router": "^5.2.0",
    "react-router-dom": "5.1.2",
    "react-scripts": "^4.0.1",
    "reactstrap": "8.4.1"
  },
  "devDependencies": {
    "@types/googlemaps": "3.39.2",
    "@types/markerclustererplus": "2.1.33",
    "@types/react": "16.9.19",
    "eslint-plugin-flowtype": "3.13.0",
    "gulp": "4.0.2",
    "gulp-append-prepend": "1.0.8",
    "typescript": "3.7.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I am running on Linux mint. Any help appreciated

Thanks

Title: npm ERR - gyp ERR

Body:
I was trying to install packages using npm. I am getting this long error and tried multiple ways but no luck. I downloaded the source code from https://github.com/creativetimofficial/argon-dashboard-react-nodejs/fork

I have installed node : Node.js v19.3.0.

Error:

npm ERR! gyp verb get node dir target node version installed: 19.3.0
npm ERR! gyp verb build dir attempting to create "build" dir: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build
npm ERR! gyp verb build dir "build" dir needed to be created? /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build
npm ERR! gyp verb build/config.gypi creating config file
npm ERR! gyp verb build/config.gypi writing out config file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build/config.gypi
npm ERR! gyp verb config.gypi checking for gypi file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/config.gypi
npm ERR! gyp verb common.gypi checking for gypi file: /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/common.gypi
npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! gyp info spawn /usr/bin/python2
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/root/.node-gyp/19.3.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/root/.node-gyp/19.3.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/root/.node-gyp/19.3.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding.gyp
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/lib/configure.js:345:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:293:12)
npm ERR! gyp ERR! System Linux 5.4.0-135-generic
npm ERR! gyp ERR! command "/usr/local/bin/node" "/home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /home/siyum/Documents/MERNAffTrack/client/node_modules/node-sass
npm ERR! gyp ERR! node -v v19.3.0
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-21T21_40_45_359Z-debug-0.log

My package.json file

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-free": "5.12.1",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "chart.js": "2.9.3",
    "classnames": "2.2.6",
    "moment": "2.24.0",
    "node-sass": "4.13.1",
    "nouislider": "14.1.1",
    "react": "16.12.0",
    "react-bootstrap": "^1.4.0",
    "react-chartjs-2": "2.9.0",
    "react-copy-to-clipboard": "5.0.2",
    "react-datetime": "2.16.3",
    "react-dom": "16.12.0",
    "react-google-maps": "9.4.5",
    "react-router": "^5.2.0",
    "react-router-dom": "5.1.2",
    "react-scripts": "^4.0.1",
    "reactstrap": "8.4.1"
  },
  "devDependencies": {
    "@types/googlemaps": "3.39.2",
    "@types/markerclustererplus": "2.1.33",
    "@types/react": "16.9.19",
    "eslint-plugin-flowtype": "3.13.0",
    "gulp": "4.0.2",
    "gulp-append-prepend": "1.0.8",
    "typescript": "3.7.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I am running on Linux mint. Any help appreciated

Thanks


问:
How can I recover my deleted Heroku Database
I was using the free dyno plan of Heroku for my personal project. Now Heroku stopped providing free service. and in a few days Heroku also deleted the database of my application. I want to recover and back up that database so I can deploy my app again on another free platform like railway.app.

I have a Github student program but I am not able to use that for Heroku as I have a Debit Card(Master Card) of India. and due to regulations of the Reserve Bank of India. Heroku is not verifying my card and billing method and it's mandatory for students also to verify billing method.

I have transferred my app to railway.app and added database variables directly from Heroku. I was able use the database on Railway.app for a few days after that Railway stopped working due to a database issue. Then I checked the database and It was Heroku's Database just being used there and Heroku has deleted that database. Now I want to recover my data.

I have no other option than to recover my database and move to another platform. So please find me a way to solve my issue. Thank You


问:
Why azcopy mention permission denied
I would like to download a dataset with this provided link

```<code>https://aimistanforddatasets01.blob.core.windows.net/chexpertchestxrays-u20210408?sv=2019-02-02&sr=c&sig=mc587rwVNBFZp0uP3JKmaJLnyirIRA%2B9zomVS52hn%2B0%3D&st=2022-12-21T21%3A25%3A12Z&se=2023-01-20T21%3A30%3A12Z&sp=rl
</code>```

The webpage mention that :

the dataset download link cannot be used directly in a browser.
A download link for an entire dataset provides the location of the dataset in Azure as well as a special time-limited key that allows you to download the entire dataset. This link can be used with tools that can copy files from Azure.

Because I have any idea on AzCopy command Line, I start with installing Azcopy by executing those lines on terminal:

```<code>## Heading ##
#Download AzCopy
wget https://aka.ms/downloadazcopy-v10-linux

#Expand Archive
tar -xvf downloadazcopy-v10-linux

#(Optional) Remove existing AzCopy version
sudo rm /usr/bin/azcopy

#Move AzCopy to the destination you want to store it
sudo cp ./azcopy_linux_amd64_*/azcopy /usr/bin/
azcopy login

</code>```

It display:

```<code>bash: /usr/bin/azcopy: Permission denied
</code>```

So please how can I do to download the link above with azcopy?

Title: Why azcopy mention permission denied

Body:
I would like to download a dataset with this provided link

https://aimistanforddatasets01.blob.core.windows.net/chexpertchestxrays-u20210408?sv=2019-02-02&sr=c&sig=mc587rwVNBFZp0uP3JKmaJLnyirIRA%2B9zomVS52hn%2B0%3D&st=2022-12-21T21%3A25%3A12Z&se=2023-01-20T21%3A30%3A12Z&sp=rl

The webpage mention that :

the dataset download link cannot be used directly in a browser.
A download link for an entire dataset provides the location of the dataset in Azure as well as a special time-limited key that allows you to download the entire dataset. This link can be used with tools that can copy files from Azure.

Because I have any idea on AzCopy command Line, I start with installing Azcopy by executing those lines on terminal:

## Heading ##
#Download AzCopy
wget https://aka.ms/downloadazcopy-v10-linux

#Expand Archive
tar -xvf downloadazcopy-v10-linux

#(Optional) Remove existing AzCopy version
sudo rm /usr/bin/azcopy

#Move AzCopy to the destination you want to store it
sudo cp ./azcopy_linux_amd64_*/azcopy /usr/bin/
azcopy login

It display:

bash: /usr/bin/azcopy: Permission denied

So please how can I do to download the link above with azcopy?


问:
Why if condition return false on equal same values
```<code>public static Boolean parfait(Integer k) {
    Integer s = 0;
    for (Integer i = 1; i < k; i++) {
        if (k % i == 0) {
            s=s+i;
            System.out.println(i);
            //return true;
        }
    }
    System.out.println("sum:"+s);
    System.out.println("val:"+k);
    if(s==k){// why 496 != 496
        return true;
    }else{
        return false;
    }
}
</code>```
```<code>System.out.println("Nombre parfait: " + parfait(496));
</code>```

We make the sum of its positive divisors and we try to check if this number is perfect. With the number 6 and 28 it works perfect but it isn't with other perfect digits like 496 or 8128. Event if we have sum of this divisors which is equal number in parameter it returns false.

Body:
public static Boolean parfait(Integer k) {
    Integer s = 0;
    for (Integer i = 1; i < k; i++) {
        if (k % i == 0) {
            s=s+i;
            System.out.println(i);
            //return true;
        }
    }
    System.out.println("sum:"+s);
    System.out.println("val:"+k);
    if(s==k){// why 496 != 496
        return true;
    }else{
        return false;
    }
}

System.out.println("Nombre parfait: " + parfait(496));

We make the sum of its positive divisors and we try to check if this number is perfect. With the number 6 and 28 it works perfect but it isn't with other perfect digits like 496 or 8128. Event if we have sum of this divisors which is equal number in parameter it returns false.


问:
Rmarkdown chunk code resulting in too many errors in console (I want to see them, just not all of them printed to the console)
I am running a piece of a chunk of code (i.e., I'm not just clicking "Run" for the entire chunk) in an RMarkdown document. Normally, when I run this code in a normal script (which reads in a large dataset), the console indicates there are warnings, and gives me the option to see the first 50 by running the command

```<code>warnings()
</code>```

However, when running this same code in RMarkdown, the console prints every single one of the warnings in the console. I want to know there are warnings and be able to quickly review the first 50 of them, but I don't want the console to print all of them.

Please note, I am aware of the

```<code>warning = FALSE
</code>```

argument in knitr::opts_chunk$set() command. This is not helpful in my situation because I want to see that there are warnings and quickly preview them; I just don't want the console to print *all *of them.

I double checked my warning settings using

```<code>getOption("nwarnings")
</code>```

and the result was 50. However, the console is printing way more than 50 warnings when I run this piece of the code chunk.

Body:
I am running a piece of a chunk of code (i.e., I'm not just clicking "Run" for the entire chunk) in an RMarkdown document. Normally, when I run this code in a normal script (which reads in a large dataset), the console indicates there are warnings, and gives me the option to see the first 50 by running the command

warnings()

However, when running this same code in RMarkdown, the console prints every single one of the warnings in the console. I want to know there are warnings and be able to quickly review the first 50 of them, but I don't want the console to print all of them.

Please note, I am aware of the

warning = FALSE

argument in knitr::opts_chunk$set() command. This is not helpful in my situation because I want to see that there are warnings and quickly preview them; I just don't want the console to print *all *of them.

I double checked my warning settings using

getOption("nwarnings")

and the result was 50. However, the console is printing way more than 50 warnings when I run this piece of the code chunk.


问:
IIFE in JavaScript
Recently, while writing a business card site, in order to create a gallery, I used JavaScript. I created the window.number variable in it, but realized that in this case it is better to avoid the global variable. In search for a solution, I came across IIFE. So, I would like to know how exactly the construct (function(){ })() works in JS

I tried to use IIFE, succeeded, but without understanding what I am doing.

Title: IIFE in JavaScript


问:
Base64 returning empty
I'm trying to upload images to the backend using base64, my upload is fine, but the backend receives an empty string. When I use  console log, I get the data. I don't know what went wrong here.

```<code>export default function NewPost() {

    const [title, setTitle] = useState("");
    const [file, setFile] = useState("");
    const [baseImage, setBaseImage] = useState("");

    const [newPost, setNewPost] = useState({
        userId: '',
        title: '',
        content: '',
        photo: '',
    });

      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');

        } catch (err) {
          console.log(err);
        }
    }

    const uploadImage = async (e) => {
        const file = e.target.files[0];
        const base64 = await convertBase64(file);
        setBaseImage(base64);
        console.log(base64);
        setNewPost({ ...newPost, photo: baseImage });
      };

      const convertBase64 = (file) => {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.readAsDataURL(file);
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.onerror = (error) => {
            reject(error);
          };
        });
      };

  return (
    <div className="newPostPageContainer">
    <form className="newPostForm" onSubmit={handleSubmit}>
          <div className="newPostTitleImageUploadCont">
          <div className="newPostTitleContainer">
            <label className="newPostFormLabel">Post Title:</label>
            <input dir="auto" type="text"
            onChange={e => setNewPost({ ...newPost, title: e.target.value })} />
            </div>
            <div className="newPostUploadImgContainer">
                <img src={baseImage} alt="" className="newPostUploadImg" />
                <label for="file">
                    <PublishIcon />
                </label>

              <input
              type="file"
              id="file"
              onChange={(e) => { uploadImage(e); }}
              style={{display: "none"}} />

            </div>
            </div>

            <button className="newPostCreateButton" type="submit">
              <p className="newPostCreateButtonText">Create</p>
            </button>
    </form>
</div>

  );
}
</code>```

Before that I used <FileBase64 /> and it was working perfectly. But since it can't be customized I changed to this, trying to do my own function, some help here would be appreciated.

Title: Base64 returning empty

Body:
I'm trying to upload images to the backend using base64, my upload is fine, but the backend receives an empty string. When I use  console log, I get the data. I don't know what went wrong here.

export default function NewPost() {

    const [title, setTitle] = useState("");
    const [file, setFile] = useState("");
    const [baseImage, setBaseImage] = useState("");

    const [newPost, setNewPost] = useState({
        userId: '',
        title: '',
        content: '',
        photo: '',
    });

      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');

        } catch (err) {
          console.log(err);
        }
    }

    const uploadImage = async (e) => {
        const file = e.target.files[0];
        const base64 = await convertBase64(file);
        setBaseImage(base64);
        console.log(base64);
        setNewPost({ ...newPost, photo: baseImage });
      };

      const convertBase64 = (file) => {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.readAsDataURL(file);
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.onerror = (error) => {
            reject(error);
          };
        });
      };

  return (

    <form className="newPostForm" onSubmit={handleSubmit}>

            Post Title:
            <input dir="auto" type="text"
            onChange={e => setNewPost({ ...newPost, title: e.target.value })} />

                    <PublishIcon />

              <input
              type="file"
              id="file"
              onChange={(e) => { uploadImage(e); }}
              style={{display: "none"}} />

            <button className="newPostCreateButton" type="submit">

Create

            </button>
    </form>

  );
}

Before that I used <FileBase64 /> and it was working perfectly. But since it can't be customized I changed to this, trying to do my own function, some help here would be appreciated.


问:
Problem with UI width-height : "%" vs dimension.get('window')
So im trying to do a responsive UI ,when i put width or height "100%" in my component its not working in my screen correctly ,but when i put Dimensions.get('window').width * 1 works perfect but i dont understand why.I have read some other questions too in the forum but i still dont get it .Thats not static data?

My component name is books at the near the start of CSS code. Its a container of books.
Thanks in advance.

```<code>
//React imports
import React, { useState,useEffect} from 'react';
import { StyleSheet, Text, View , Image, Pressable, ScrollView, Modal, Alert, Dimensions , Platform} from 'react-native';
import { useNavigation } from '@react-navigation/native';
//Icon imports
import { FontAwesome } from '@expo/vector-icons';
//APIs imports
import axios from 'axios';
import { Buffer } from "buffer";
//My imports
import Header from './Header';
//.Env imports
import {URL} from '@env';

export default function BooksRented() {

 return (

  //Container
  <View style = {styles.container}>

    <Header />

        {/* ScrollView for Rent Books */}
        <ScrollView>

        <View style = {{width:'80%',height:'10%',backgroundColor:'black',alignItems:'center',justifyContent:'center',alignSelf:'center',marginTop:'3%',borderRadius:15,flexDirection:'row'}}>
          <FontAwesome name="book" size={24} color="white" />
          <Text style = {{color:'white',fontSize:22,marginLeft:'5%'}}>Rent Books</Text>
        </View>

        <View style = {styles.books}>
        {book2.map((item)=>{
          return (
            <View style = {styles.bookContainer} key = {item.id}>
              <Text style = {styles.itemTitle}>
              {item.title}
              </Text>

              {/* Here we are making a book image pressable and keep the book object to use it later as modal */}
              <Pressable style = {styles.itemImage} onPress={ () => { setBookShow(item); setModalBookVisible(!ModalBookVisible)}}>
              <Image
                style = {{width:'100%',height:'100%',borderRadius:15 , marginTop:'5%'}}
                source = {{uri :'data:image/png;base64,' + Buffer.from(item.image.data,'hex').toString('base64')}}
              />
              </Pressable>

            </View>
          )
        })}
        </View>
      </ScrollView>

    </View>
  );
}

//Components Style
const styles = StyleSheet.create({
  container:{
    backgroundColor:'white',
    height:'100%',
    width:'100%'
  },
  //Each element - book
  books:{
    flexDirection:'row',
    flexWrap:'wrap',
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'red',
    width: Dimensions.get('window').width * 1, ** <-------Thats my Component **
    height: Dimensions.get('window').height * 1 ** <-------Thats my Component **
  },
  bookContainer:{
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'black',
    borderRadius:15,
    margin:'3%',
    padding:'3%',
    width: Dimensions.get('window').width * 0.35,
    height: Dimensions.get('window').height * 0.30
  },
  itemTitle:{
    textAlign:'center',
    width:'80%',
    fontWeight:'bold',
    fontSize : 12,
    color:'white'
  },
  itemImage:{
    width:'90%',
    height:'80%',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:15,
  },
//Modal for Books
bookModal:{
  alignItems:'center',
  height:Platform.OS ==='ios' ? '70%' : '80%',
  width:'80%',
  backgroundColor:'black',
  marginTop:Platform.OS ==='ios' ? '40%' : '19%',
  marginLeft:'10%',
  borderRadius:25,
  borderWidth:1,
  elevation:15
},
//Modal Texts
bookShowTitleText:{
  textAlign:'center',
  fontWeight:'bold',
  color:'white',
  fontSize: 15
},
bookShowCategoryText:{
  textAlign:'center',
  color:'white',
  fontSize : 15
},
textInsideModal:{
  textAlign:'center',
  color:'white',
  fontSize : 14
},
bookShowDescribeText:{
  textAlign:'center',
  fontWeight:'bold',
  fontSize : 15
},
scrollViewForDescribeModal:{
  backgroundColor:'white',
  flexDirection:'column',
  padding:'5%'
},
describeText:{
  fontSize : 15
},
//Modal pressables
pressableInsideModal:{
  borderWidth:6,
  borderRadius:11,
  elevation:5,
  backgroundColor:'grey',
  width:'45%',
  height:Platform.OS ==='ios' ? '7%' : '9%',
  paddingTop:'2%',
  alignItems:'center'
},

});
</code>```

Body:
So im trying to do a responsive UI ,when i put width or height "100%" in my component its not working in my screen correctly ,but when i put Dimensions.get('window').width * 1 works perfect but i dont understand why.I have read some other questions too in the forum but i still dont get it .Thats not static data?

My component name is books at the near the start of CSS code. Its a container of books.
Thanks in advance.

//React imports
import React, { useState,useEffect} from 'react';
import { StyleSheet, Text, View , Image, Pressable, ScrollView, Modal, Alert, Dimensions , Platform} from 'react-native';
import { useNavigation } from '@react-navigation/native';
//Icon imports
import { FontAwesome } from '@expo/vector-icons';
//APIs imports
import axios from 'axios';
import { Buffer } from "buffer";
//My imports
import Header from './Header';
//.Env imports
import {URL} from '@env';

export default function BooksRented() {

 return (

  //Container
  <View style = {styles.container}>

        {/* ScrollView for Rent Books */}
        <ScrollView>

        <View style = {{width:'80%',height:'10%',backgroundColor:'black',alignItems:'center',justifyContent:'center',alignSelf:'center',marginTop:'3%',borderRadius:15,flexDirection:'row'}}>
          <FontAwesome name="book" size={24} color="white" />
          <Text style = {{color:'white',fontSize:22,marginLeft:'5%'}}>Rent Books</Text>
        </View>

        <View style = {styles.books}>
        {book2.map((item)=>{
          return (
            <View style = {styles.bookContainer} key = {item.id}>
              <Text style = {styles.itemTitle}>
              {item.title}
              </Text>

              {/* Here we are making a book image pressable and keep the book object to use it later as modal */}
              <Pressable style = {styles.itemImage} onPress={ () => { setBookShow(item); setModalBookVisible(!ModalBookVisible)}}>
              <Image
                style = {{width:'100%',height:'100%',borderRadius:15 , marginTop:'5%'}}
                source = {{uri :'data:image/png;base64,' + Buffer.from(item.image.data,'hex').toString('base64')}}
              />
              </Pressable>

            </View>
          )
        })}
        </View>
      </ScrollView>

    </View>
  );
}

//Components Style
const styles = StyleSheet.create({
  container:{
    backgroundColor:'white',
    height:'100%',
    width:'100%'
  },
  //Each element - book
  books:{
    flexDirection:'row',
    flexWrap:'wrap',
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'red',
    width: Dimensions.get('window').width * 1, ** <-------Thats my Component **
    height: Dimensions.get('window').height * 1 ** <-------Thats my Component **
  },
  bookContainer:{
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'black',
    borderRadius:15,
    margin:'3%',
    padding:'3%',
    width: Dimensions.get('window').width * 0.35,
    height: Dimensions.get('window').height * 0.30
  },
  itemTitle:{
    textAlign:'center',
    width:'80%',
    fontWeight:'bold',
    fontSize : 12,
    color:'white'
  },
  itemImage:{
    width:'90%',
    height:'80%',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:15,
  },
//Modal for Books
bookModal:{
  alignItems:'center',
  height:Platform.OS ==='ios' ? '70%' : '80%',
  width:'80%',
  backgroundColor:'black',
  marginTop:Platform.OS ==='ios' ? '40%' : '19%',
  marginLeft:'10%',
  borderRadius:25,
  borderWidth:1,
  elevation:15
},
//Modal Texts
bookShowTitleText:{
  textAlign:'center',
  fontWeight:'bold',
  color:'white',
  fontSize: 15
},
bookShowCategoryText:{
  textAlign:'center',
  color:'white',
  fontSize : 15
},
textInsideModal:{
  textAlign:'center',
  color:'white',
  fontSize : 14
},
bookShowDescribeText:{
  textAlign:'center',
  fontWeight:'bold',
  fontSize : 15
},
scrollViewForDescribeModal:{
  backgroundColor:'white',
  flexDirection:'column',
  padding:'5%'
},
describeText:{
  fontSize : 15
},
//Modal pressables
pressableInsideModal:{
  borderWidth:6,
  borderRadius:11,
  elevation:5,
  backgroundColor:'grey',
  width:'45%',
  height:Platform.OS ==='ios' ? '7%' : '9%',
  paddingTop:'2%',
  alignItems:'center'
},

});