问:
Typescript: Cannot use import statement outside a module
I have a .ts file in node js (latest version of node.js for 07.10.19) app with importing node-module without default export. I use this construction: import { Class } from 'abc'; When i run the code, i have this error: Cannot use import statement outside a module.

In the network i see many solutions for this problem (for .js), but it not helps to me, maybe because i have typescript file. Here's my code:

```<code>import { Class } from 'abc';
module.exports = { ...
    execute(a : Class ,args : Array<string>){ ...
</code>```

Here's my tsconfig.json:

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",

    "strict": true
  }
}
</code>```

答:
Update: Because this answer is getting significant views I have updated it to better show the available solutions for this problem in 2022.

The error means Node found an import statement in a file that it does not consider an ECMAScript (ES) module. Adding "type": "module" to package.json will tell Node you are using ES modules, but then you will need to tell the TypeScript compiler to emit this type of module by setting "module": "es2015" or higher (for example: "es2020") in tsconfig.json . If you want to emit CommonJS modules (require), set "module": "commonjs".

In case you don't want to set the module system at the project level, there are more fine-grained options. Files with the .mjs extension are always treated as ES modules, while files with .cjs are always treated as CommonJS modules. As of TypeScript 4.5 it is possible to use the .mts and .cts extensions as well and have the compiler emit .mjs or .cjs files, respectively.

The two systems are partially compatible. For example, it is possible to import a CommonJS module into an ES module with a default export:

```<code>// in an ES module
import thing from "./main.cjs";
</code>```

The other way around. an ES module may be imported into a CommonJS module with dynamic import (ES2020 features are needed for this to work):

```<code>// in a CommonJS module
const thing = await import("./main.mjs");
</code>```

Original answer (2020):

Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.

This however causes a problem with the current code because although you are using an ES6 import {} statement you are exporting using the commonJS module.exports = {} syntax, and Node’s ES module loader will have an issue with it. There are two ways to deal with it:

Keep the module.exports but tell Node to interpret this file as commonJS by giving it a .cjs extension.

Change the export statement to ES2015 syntax: export function execute(…)..

The first option could get a bit tricky because the compiler will output .js files and you’d have to change it to .cjs all the time (as far as I know). With the second option you should be able to run the file with Node (including the --experimental-modules flag for versions < 13.8).

If you absolutely need to use commonJS, perhaps it is better to install the type definitions for Node: @types/node and change the import to commonJS format: require('abc') and keep the rest of the settings as they are (though you can add "type": "commonjs" to package.json to be explicit).

Body:
I have a .ts file in node js (latest version of node.js for 07.10.19) app with importing node-module without default export. I use this construction: import { Class } from 'abc'; When i run the code, i have this error: Cannot use import statement outside a module.

In the network i see many solutions for this problem (for .js), but it not helps to me, maybe because i have typescript file. Here's my code:

import { Class } from 'abc';
module.exports = { ...
    execute(a : Class ,args : Array<string>){ ...

Here's my tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",

    "strict": true
  }
}

Body:
Update: Because this answer is getting significant views I have updated it to better show the available solutions for this problem in 2022.

The error means Node found an import statement in a file that it does not consider an ECMAScript (ES) module. Adding "type": "module" to package.json will tell Node you are using ES modules, but then you will need to tell the TypeScript compiler to emit this type of module by setting "module": "es2015" or higher (for example: "es2020") in tsconfig.json . If you want to emit CommonJS modules (require), set "module": "commonjs".

In case you don't want to set the module system at the project level, there are more fine-grained options. Files with the .mjs extension are always treated as ES modules, while files with .cjs are always treated as CommonJS modules. As of TypeScript 4.5 it is possible to use the .mts and .cts extensions as well and have the compiler emit .mjs or .cjs files, respectively.

The two systems are partially compatible. For example, it is possible to import a CommonJS module into an ES module with a default export:

// in an ES module
import thing from "./main.cjs";

The other way around. an ES module may be imported into a CommonJS module with dynamic import (ES2020 features are needed for this to work):

// in a CommonJS module
const thing = await import("./main.mjs");

Original answer (2020):

Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.

This however causes a problem with the current code because although you are using an ES6 import {} statement you are exporting using the commonJS module.exports = {} syntax, and Node’s ES module loader will have an issue with it. There are two ways to deal with it:

Keep the module.exports but tell Node to interpret this file as commonJS by giving it a .cjs extension.

Change the export statement to ES2015 syntax: export function execute(…)..

The first option could get a bit tricky because the compiler will output .js files and you’d have to change it to .cjs all the time (as far as I know). With the second option you should be able to run the file with Node (including the --experimental-modules flag for versions < 13.8).

If you absolutely need to use commonJS, perhaps it is better to install the type definitions for Node: @types/node and change the import to commonJS format: require('abc') and keep the rest of the settings as they are (though you can add "type": "commonjs" to package.json to be explicit).


来源: stackexchange

问:
strapi API: curl examples for searching
Can someone give me some simple curl examples for how to use the strapi API?

For example I can fetch items of a content type like this:

```<code>$ curl http://127.0.0.1:1337/products
$ curl http://127.0.0.1:1337/products/1
</code>```

But how can I search for specific fields? I saw in the docs that there is a way to query for other fields than ID, like e.g. name of products. But what's the right URL syntax?

答:
You can find all params here: https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#api-parameters</p>
```<code>curl http://127.0.0.1:1337/products?name=somename
</code>```

ContentLicense: CC BY-SA 4.0

Title: strapi API: curl examples for searching

Body:
Can someone give me some simple curl examples for how to use the strapi API?

For example I can fetch items of a content type like this:

$ curl http://127.0.0.1:1337/products
$ curl http://127.0.0.1:1337/products/1

But how can I search for specific fields? I saw in the docs that there is a way to query for other fields than ID, like e.g. name of products. But what's the right URL syntax?

Body:
You can find all params here: https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#api-parameters

curl http://127.0.0.1:1337/products?name=somename


问:
How to make time ago from json in flutter
Is it possible if I have json with the timestamp like this

```<code>{
"modified": "2018-11-14T16:25:21",
}

</code>```

and I want to make time ago in flutter. eg.5 minutes ago

答:
For Seconds:

```<code>yourDate.difference(DateTime.now()).inSeconds;
</code>```

For Minutes:

```<code>yourDate.difference(DateTime.now()).inMinutes;
</code>```

For Hours:

```<code>yourDate.difference(DateTime.now()).inHours;
</code>```

Body:
Is it possible if I have json with the timestamp like this

{
"modified": "2018-11-14T16:25:21",
}

and I want to make time ago in flutter. eg.5 minutes ago

Body:
For Seconds:

yourDate.difference(DateTime.now()).inSeconds;

For Minutes:

yourDate.difference(DateTime.now()).inMinutes;

For Hours:

yourDate.difference(DateTime.now()).inHours;


问:
how can I build Widgets using flutter?
View screen shot here

I need to build this kind of widget to my flutter application.The widget should be can bring across the screen. is its possible? Then How can I do that?
Thanks in advance!

答: Actually, Flutter can't create this type of widget (widget that you can add on your Home Screen) because Flutter uses his own custom rendering engine.</p>

Title: how can I build Widgets using flutter?


问:
Encoding problem using new line command in perl
The program works as long as I only print the special characters. But I want them to be separated and sorted. With the new line command the characters change into question marks. Can someone tell me why and how to solve this problem?</p>

```<code>#!/usr/bin/perl

while (<>) {
  while (/(.)/g) {
    if (ord($1) >= 128){
       print "$1\n";
    }
  }
}
</code>```

答:
When opening a non-ASCII file, you should tell Perl what encoding the file has. When printing those characters, again, you should specify how they should be encoded on output.

For example, to process UTF-8 encoded characters, prepend the following to your code:

```<code>use open IO => ':encoding(UTF-8)', ':std';
</code>```

See open for details.

Body:
The program works as long as I only print the special characters. But I want them to be separated and sorted. With the new line command the characters change into question marks. Can someone tell me why and how to solve this problem?

#!/usr/bin/perl

while (<>) {
  while (/(.)/g) {
    if (ord($1) >= 128){
       print "$1\n";
    }
  }
}

Body:
When opening a non-ASCII file, you should tell Perl what encoding the file has. When printing those characters, again, you should specify how they should be encoded on output.

For example, to process UTF-8 encoded characters, prepend the following to your code:

use open IO => ':encoding(UTF-8)', ':std';

See open for details.


问:
How to pass "environment" values to NGModule as configuration?
I've got an angular library that expose a module to whom I pass a config valued from environment:

```<code>import { environment } from '../environments/environment';

console.log(environment); // {locale: 'en'}

@NgModule({
    imports: [
        AngularCoreModule.forRoot({
            locale: environment.locale || 'KO'
        })
    ],
})
export class AppModule {
}
</code>```

When I try to access to the configuration from within the module, I get the fallback value instead of the right one. This happen ONLY with the ng build --prod code.

//...

```<code>someMethod() {
    console.log(this.config); // {locale: 'KO'}
}
</code>```

My angular.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "defaultProject": "app",
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "preserveSymlinks": true,
            "outputPath": "www",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ],
            "styles": [
              {
                "input": "src/theme/variables.scss"
              },
              {
                "input": "src/global.scss"
              }
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "ci": {
              "progress": false
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            },
            "ci": {
              "progress": false
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          },
          "configurations": {
            "ci": {
              "progress": false,
              "watch": false
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": ["**/node_modules/**"]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            },
            "ci": {
              "devServerTarget": "app:serve:ci"
            }
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        }
      }
    }
  },
  "cli": {
    "defaultCollection": "@ionic/angular-toolkit"
  },
  "schematics": {
    "@ionic/angular-toolkit:component": {
      "styleext": "scss"
    },
    "@ionic/angular-toolkit:page": {
      "styleext": "scss"
    }
  }
}
</code>```

Why this happens?

答:
Found the issue:
for some reason I cannot understand if my environment.ts file has imports like

```<code>import base from './base';

export const environment = {
...base
}
</code>```

the app.module.ts cannot read it correctly in production build, so I need to paste inside the environment.ts the base file content

Body:
I've got an angular library that expose a module to whom I pass a config valued from environment:

import { environment } from '../environments/environment';

console.log(environment); // {locale: 'en'}

@NgModule({
    imports: [
        AngularCoreModule.forRoot({
            locale: environment.locale || 'KO'
        })
    ],
})
export class AppModule {
}

When I try to access to the configuration from within the module, I get the fallback value instead of the right one. This happen ONLY with the ng build --prod code.

//...

someMethod() {
    console.log(this.config); // {locale: 'KO'}
}

My angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "defaultProject": "app",
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "preserveSymlinks": true,
            "outputPath": "www",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ],
            "styles": [
              {
                "input": "src/theme/variables.scss"
              },
              {
                "input": "src/global.scss"
              }
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "ci": {
              "progress": false
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            },
            "ci": {
              "progress": false
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          },
          "configurations": {
            "ci": {
              "progress": false,
              "watch": false
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": ["**/node_modules/**"]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            },
            "ci": {
              "devServerTarget": "app:serve:ci"
            }
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        }
      }
    }
  },
  "cli": {
    "defaultCollection": "@ionic/angular-toolkit"
  },
  "schematics": {
    "@ionic/angular-toolkit:component": {
      "styleext": "scss"
    },
    "@ionic/angular-toolkit:page": {
      "styleext": "scss"
    }
  }
}

Why this happens?

Body:
Found the issue:
for some reason I cannot understand if my environment.ts file has imports like

import base from './base';

export const environment = {
...base
}

the app.module.ts cannot read it correctly in production build, so I need to paste inside the environment.ts the base file content


问:
Separate Powershell Output in a Dropdown Menu
I am getting my Printer Information from the following Powershell Command:

```<code><?php
$Comment = Shell_Exec ('powershell.exe -Command "Get-Printer -ComputerName servername | select Comment | ConvertTo-Html | Format-Table"');
?>
</code>```

and trying to put them into a Dropdown Menu:

```<code><select id="comment">
  <option value="comment"><?php echo $Comment; ?></option>
</select>`
</code>```

But i can't find a way to separate the Output with one Value in each Box.

The Output / Data from the shell call looks like this:

```<code>Comment
-------
2483
2066                                                                                1737
</code>```

答:
If you want to create a select dropdown menu, you need to create several entries like this:

```<code><label for="printer">Choose a printer:</label>

<select id="printer" name="printer">
  <option value="printer-1">Printer 1</option>
  <option value="printer-2">Printer 2</option>
  <option value="printer-x">The last printer</option>
</select>
</code>```

But in any case, I would avoid your PHP calling some Powershell commands on each page load. This is very very slow and your page won't be reactive at all.

If you need this list to be updated then consider having a configuration file which is written with a cron task (scheduled task) from time to time. Then your  PHP code in the page should just load the array of printers by requiring this configuration file.

For example, you could generate the list of printers by saving it in JSON format that can easily be read by PHP.

The command would become:

powershell.exe -Command "Get-Printer -ComputerName yourprintserver | select Name,DriverName,PortName,Comment | ConvertTo-Json"
```

<p>Example of output:</p>

```[
    {
        "Name":  "PDF-cadwork",
        "DriverName":  "PDF-XChange 4.0 Lite",
        "PortName":  "PDF-XChange4",
        "Comment":  ""
    },
    {
        "Name":  "OKI C9800(PS)",
        "DriverName":  "OKI C9600(PS)",
        "PortName":  "IP_192.168.11.99",
        "Comment":  ""
    },
    {
        "Name":  "OKI C9800(PCL)",
        "DriverName":  "OKI C9800(PCL)",
        "PortName":  "IP_192.168.11.99",
        "Comment":  ""
    },
    {
        "Name":  "Microsoft XPS Document Writer",
        "DriverName":  "Microsoft XPS Document Writer v4",
        "PortName":  "PORTPROMPT:",
        "Comment":  ""
    },
    {
        "Name":  "HP LaserJet M570 PS",
        "DriverName":  "HP Universal Printing PS",
        "PortName":  "IP_192.168.11.96",
        "Comment":  ""
    },
    {
        "Name":  "HP Color LaserJet CM6030 MFP PCL6",
        "DriverName":  "HP Color LaserJet CM6030 MFP PCL6",
        "PortName":  "192.168.11.95",
        "Comment":  ""
    },
    {
        "Name":  "Canon iPF510",
        "DriverName":  "Canon iPF510",
        "PortName":  "IP_192.168.11.97",
        "Comment":  ""
    }
]
```

<p>As you see, <strong>I actually haven't got the Comment field filled</strong> but it would be your case.</p>

<p>Let's say this file is then saved to <code>printers.json</code> by your scheduled task. To do that, just redirect the result to your file with the <code>></code> operator:</p>

<pre class="lang-sh prettyprint-override"><code>powershell.exe -Command "Get-Printer -ComputerName yourprintserver | select Name,DriverName,PortName,Comment | ConvertTo-Json" > C:\path-to-php-site\config\printers.json
</code>```

We can then load it in PHP:

<?php
// Get the list of printers from the automatically updated JSON file.
// Caution: PowerShell creates the file in "UCS-2 LE BOM" format.
//          PHP wants to read UTF-8 so we'll have to convert it.

// Read the JSON created by the scheduled task running PowerShell.
$printers_json_ucs2_le_bom = file_get_contents('printers.json');

// Convert to UTF-8 encoding.
$printers_json_utf8_bom = mb_convert_encoding(
    $printers_json_ucs2_le_bom, // Source content.
    'UTF-8',                    // Destination encoding.
    'UCS-2LE'                   // Source encoding.
);

// Remove the BOM marker which is still there.
$printers_json_utf8 = preg_replace('/\x{FEFF}/u', '', $printers_json_utf8_bom);

// Decode the JSON to a PHP variable.
$printers = json_decode($printers_json_utf8);

/**
 * Get the HTML code to create a select drop down to choose a printer.
 *
 * @param array $printers The list of printers.
 * @param string $name The name of the field in the form.
 * @param string $id THe id of the fiedl in the form.
 * @param string $lable The label to display before the select drop down.
 *
 * @return string The HTML code to put in your form.
 */
function get_printers_select(array $printers, $name = 'printer', $id = 'printer', $label = 'Select your printer')
{
    $html = '';
    if (!empty($label)) {
        $html .= '' . htmlspecialchars($label) . "\n";
    }
    $html .= '<select id="' . $id . '" name="' . $name . "\">\n";
    foreach ($printers as $printer) {
        $html .= '  <option value="' . htmlentities($printer->Comment) . '">' .
                 htmlspecialchars($printer->Comment) . "</option>\n";
    }
    $html .= "</select>\n";
    return $html;
}

// Your HTML and <form> should come here...

print get_printers_select($printers);

```

<p>And this outputs this HTML if I replace <code>$printer->Comment</code> by <code>$printer->Name</code>:</p>

<pre class="lang-html prettyprint-override"><code><label for="printer">Select your printer</label>
<select id="printer" name="printer">
  <option value="PDF-cadwork">PDF-cadwork</option>
  <option value="OKI C9800(PS)">OKI C9800(PS)</option>
  <option value="OKI C9800(PCL)">OKI C9800(PCL)</option>
  <option value="Microsoft XPS Document Writer">Microsoft XPS Document Writer</option>
  <option value="HP LaserJet M570 PS">HP LaserJet M570 PS</option>
  <option value="HP Color LaserJet CM6030 MFP PCL6">HP Color LaserJet CM6030 MFP PCL6</option>
  <option value="Canon iPF510">Canon iPF510</option>
</select>
</code>```

Body:
I am getting my Printer Information from the following Powershell Command:

<?php
$Comment = Shell_Exec ('powershell.exe -Command "Get-Printer -ComputerName servername | select Comment | ConvertTo-Html | Format-Table"');
?>

and trying to put them into a Dropdown Menu:

<select id="comment">
  <option value="comment"><?php echo $Comment; ?></option>
</select>`

But i can't find a way to separate the Output with one Value in each Box.

The Output / Data from the shell call looks like this:

Comment
-------
2483
2066                                                                                1737

Body:
If you want to create a select dropdown menu, you need to create several entries like this:

<label for="printer">Choose a printer:</label>

<select id="printer" name="printer">
  <option value="printer-1">Printer 1</option>
  <option value="printer-2">Printer 2</option>
  <option value="printer-x">The last printer</option>
</select>

But in any case, I would avoid your PHP calling some Powershell commands on each page load. This is very very slow and your page won't be reactive at all.

If you need this list to be updated then consider having a configuration file which is written with a cron task (scheduled task) from time to time. Then your  PHP code in the page should just load the array of printers by requiring this configuration file.

For example, you could generate the list of printers by saving it in JSON format that can easily be read by PHP.

The command would become:

powershell.exe -Command "Get-Printer -ComputerName yourprintserver | select Name,DriverName,PortName,Comment | ConvertTo-Json"

Example of output:

[
    {
        "Name":  "PDF-cadwork",
        "DriverName":  "PDF-XChange 4.0 Lite",
        "PortName":  "PDF-XChange4",
        "Comment":  ""
    },
    {
        "Name":  "OKI C9800(PS)",
        "DriverName":  "OKI C9600(PS)",
        "PortName":  "IP_192.168.11.99",
        "Comment":  ""
    },
    {
        "Name":  "OKI C9800(PCL)",
        "DriverName":  "OKI C9800(PCL)",
        "PortName":  "IP_192.168.11.99",
        "Comment":  ""
    },
    {
        "Name":  "Microsoft XPS Document Writer",
        "DriverName":  "Microsoft XPS Document Writer v4",
        "PortName":  "PORTPROMPT:",
        "Comment":  ""
    },
    {
        "Name":  "HP LaserJet M570 PS",
        "DriverName":  "HP Universal Printing PS",
        "PortName":  "IP_192.168.11.96",
        "Comment":  ""
    },
    {
        "Name":  "HP Color LaserJet CM6030 MFP PCL6",
        "DriverName":  "HP Color LaserJet CM6030 MFP PCL6",
        "PortName":  "192.168.11.95",
        "Comment":  ""
    },
    {
        "Name":  "Canon iPF510",
        "DriverName":  "Canon iPF510",
        "PortName":  "IP_192.168.11.97",
        "Comment":  ""
    }
]

As you see, I actually haven't got the Comment field filled but it would be your case.

Let's say this file is then saved to printers.json by your scheduled task. To do that, just redirect the result to your file with the > operator:

powershell.exe -Command "Get-Printer -ComputerName yourprintserver | select Name,DriverName,PortName,Comment | ConvertTo-Json" > C:\path-to-php-site\config\printers.json

We can then load it in PHP:

<?php
// Get the list of printers from the automatically updated JSON file.
// Caution: PowerShell creates the file in "UCS-2 LE BOM" format.
//          PHP wants to read UTF-8 so we'll have to convert it.

// Read the JSON created by the scheduled task running PowerShell.
$printers_json_ucs2_le_bom = file_get_contents('printers.json');

// Convert to UTF-8 encoding.
$printers_json_utf8_bom = mb_convert_encoding(
    $printers_json_ucs2_le_bom, // Source content.
    'UTF-8',                    // Destination encoding.
    'UCS-2LE'                   // Source encoding.
);

// Remove the BOM marker which is still there.
$printers_json_utf8 = preg_replace('/\x{FEFF}/u', '', $printers_json_utf8_bom);

// Decode the JSON to a PHP variable.
$printers = json_decode($printers_json_utf8);

/**
 * Get the HTML code to create a select drop down to choose a printer.
 *
 * @param array $printers The list of printers.
 * @param string $name The name of the field in the form.
 * @param string $id THe id of the fiedl in the form.
 * @param string $lable The label to display before the select drop down.
 *
 * @return string The HTML code to put in your form.
 */
function get_printers_select(array $printers, $name = 'printer', $id = 'printer', $label = 'Select your printer')
{
    $html = '';
    if (!empty($label)) {
        $html .= '<label for="' . $id . '">' . htmlspecialchars($label) . "</label>\n";
    }
    $html .= '<select id="' . $id . '" name="' . $name . "\">\n";
    foreach ($printers as $printer) {
        $html .= '  <option value="' . htmlentities($printer->Comment) . '">' .
                 htmlspecialchars($printer->Comment) . "</option>\n";
    }
    $html .= "</select>\n";
    return $html;
}

// Your HTML and <form> should come here...

print get_printers_select($printers);

And this outputs this HTML if I replace $printer->Comment by $printer->Name:

<label for="printer">Select your printer</label>
<select id="printer" name="printer">
  <option value="PDF-cadwork">PDF-cadwork</option>
  <option value="OKI C9800(PS)">OKI C9800(PS)</option>
  <option value="OKI C9800(PCL)">OKI C9800(PCL)</option>
  <option value="Microsoft XPS Document Writer">Microsoft XPS Document Writer</option>
  <option value="HP LaserJet M570 PS">HP LaserJet M570 PS</option>
  <option value="HP Color LaserJet CM6030 MFP PCL6">HP Color LaserJet CM6030 MFP PCL6</option>
  <option value="Canon iPF510">Canon iPF510</option>
</select>


问:
Add a new lag column, after ordering?
enter image description hereI am trying to produce a lag column after ordering, and am not sure how to do it

```<code>SELECT
     Date
      ,Vehicle
      ,OdoReadingMiles
  FROM [Fleet].[DwhTriscanChargeouts]
  order by convert(datetime, date, 103), Vehicle ASC
  LAG (OdoReadingMiles,1) Over (ORDER BY Vehicle) AS New
</code>```

I want to be able to sort the dataset by date order, before using the Lag function. I have tried to put the Lag function before, but that doesnt seem to work?

答:
I think you want partition by:

```<code>SELECT Date, Vehicle, OdoReadingMiles,
       LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY date) AS prev_OdoReadingMiles
FROM [Fleet].[DwhTriscanChargeouts];
</code>```

Title: Add a new lag column, after ordering?

Body:
enter image description hereI am trying to produce a lag column after ordering, and am not sure how to do it

SELECT
     Date
      ,Vehicle
      ,OdoReadingMiles
  FROM [Fleet].[DwhTriscanChargeouts]
  order by convert(datetime, date, 103), Vehicle ASC
  LAG (OdoReadingMiles,1) Over (ORDER BY Vehicle) AS New

I want to be able to sort the dataset by date order, before using the Lag function. I have tried to put the Lag function before, but that doesnt seem to work?

Body:
I think you want partition by:

SELECT Date, Vehicle, OdoReadingMiles,
       LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY date) AS prev_OdoReadingMiles
FROM [Fleet].[DwhTriscanChargeouts];


问:
Mongo Write Client connection
What does the MongoDB_ActiveClientsWriting_ metric in mongostat refer to?

If I am performing multiple writes from an application on the same connection  - does it get audited as a single Active Client?

In that case - does a connection indicate a thread - a single funnel of write?

Or does Mongo have inherent worker threads to fork off parallel writes on a connection.

If so,what is the metric/configuration that flags the active threads writing at a time.

We are using Mongo 4.x.x

答:
It is stats from the locker - how many active connections keep write lock at the time of reporting.
https://docs.mongodb.com/manual/reference/command/serverStatus/#serverstatus.globalLock.activeClients reads:

globalLock.activeClients.total

The total number of internal client connections to the database including system threads as well as queued readers and writers. This metric will be higher than the total of activeClients.readers and activeClients.writers due to the inclusion of system threads.

globalLock.activeClients.readers

The number of the active client connections performing read operations.

globalLock.activeClients.writers

The number of active client connections performing write operations.

The metric itself is calculated in https://github.com/mongodb/mongo/blob/3a508dcd9755cc5012288068ce88afb9117ac8b8/src/mongo/db/stats/lock_server_status_section.cpp#L55

Title: Mongo Write Client connection


问:
Using generic lambda of header file in implementation file
I have this type in the header MyType.hpp:

```<code>struct MyType
{
    template<typename T>
    void operator(T t)
    {
        auto lamdba = [t](auto i){ t.someCall(i); };
        someMethod(lamdba);
    }

    template<typename L>
    void someMethod(L);
};
</code>```

So, someMethod gets called with a generic lambda which accepts a generic parameter.
Is it somehow possible to provide an implementation in MyType.cpp for someMethod?
This does not work:

```<code>template<typename L>
void MyType::someMethod(L lambda)
{
    lambda(42);
    lambda("42");
    // etc...
}
</code>```

As partial specialization is not allowed(only full specialization  for function templates), is there any other way to "pass" the lambda of the header file to the implementation file MyType.cpp?
If passing is not possible, maybe there exists a way of dynamically storing this lambda in MyType.hpp and access it in MyType.cpp?

答:
Every lambda has its own type. You will not be able to write down the type in your source code anyway.

As the translation unit which has the definition of your template will never see the lambda type, the template will never be instantiated. And you will not be able to get the type of a lambda to make it a specialization nor to have it for a manual instantiation.

As this the answer is: You can't use a lambda closure as parameter for a template specialized or manually instantiated if the template is visible only in its own translation unit.

Body:
I have this type in the header MyType.hpp:

struct MyType
{
    template<typename T>
    void operator(T t)
    {
        auto lamdba = [t](auto i){ t.someCall(i); };
        someMethod(lamdba);
    }

    template<typename L>
    void someMethod(L);
};

So, someMethod gets called with a generic lambda which accepts a generic parameter.
Is it somehow possible to provide an implementation in MyType.cpp for someMethod?
This does not work:

template<typename L>
void MyType::someMethod(L lambda)
{
    lambda(42);
    lambda("42");
    // etc...
}

As partial specialization is not allowed(only full specialization  for function templates), is there any other way to "pass" the lambda of the header file to the implementation file MyType.cpp?
If passing is not possible, maybe there exists a way of dynamically storing this lambda in MyType.hpp and access it in MyType.cpp?


答:
```<code>template<typename L>
void MyType::someMethod(L lambda)
{
    lambda(42);
    lambda("42");
    // etc...
}
</code>```

Will not work. Templates (and lambda's) must be completely defined when instantiated. You cannot have a generic template definitions in .cpp - only full specializations can be implemented in .cpp (informally speaking). There are multiple ways to work around this. Brute force method would be to add in specializations for every type (perhaps calling a common template that only lives in the .cpp). Another approach could maybe be to use some kind of abstract factory design (returning interface based on the dispatched type) - but there is too little information here wrether that is a feasible solution.

Title: Using generic lambda of header file in implementation file

Body:
template<typename L>
void MyType::someMethod(L lambda)
{
    lambda(42);
    lambda("42");
    // etc...
}

Will not work. Templates (and lambda's) must be completely defined when instantiated. You cannot have a generic template definitions in .cpp - only full specializations can be implemented in .cpp (informally speaking). There are multiple ways to work around this. Brute force method would be to add in specializations for every type (perhaps calling a common template that only lives in the .cpp). Another approach could maybe be to use some kind of abstract factory design (returning interface based on the dispatched type) - but there is too little information here wrether that is a feasible solution.


问:
Why doesn't my JS update my data-theme back?
I want to have a button inside my navbar (ul li) that can toggle between theme=light and theme=dark. However, only activating dark mode works.

Code:

I created a button

, with a JS function

function darkMode () {
    var isOn = false;
    if(Boolean(isOn) === false) {
        document.documentElement.setAttribute('data-theme', 'dark');
        var isOn = true;
    }
    else if(Boolean(isOn) === true) {
        document.documentElement.setAttribute('data-theme', 'light');
        var isOn = false;
    }
}
```

<p>and my css looks like this:</p>

<pre class="lang-css prettyprint-override"><code>:root, [data-theme="light"] {
  --bg-color: #ffffff;
  --bg-color-inv: #000000;
  --outline-color: #000000;
  --text-primary: #000000;
  --text-primary-inv: #ffffff;
  --text-secondary: #a4a4a4;
  --text-secondary-hover: #000000;
  --chivo: 'Chivo', sans-serif;
}

[data-theme="dark"] {
  --bg-color: #121212;
  --bg-color-inv: #ffffff;
  --outline-color: #ffffff;
  --text-primary: #ffffff;
  --text-primary-inv: #000000;
  --text-secondary: #5b5b5b;
  --text-secondary-hover: #ffffff;
}
</code>```

答:
1. You start the function by setting the isOn to false. so Boolean(isOn) === false alwaeys return true. you should init the isOn variable outside the function

2 Why you convert the isOn to boolean? it's already boolean type..

3 You not really need else if.. if it is not false it is true..

4. as mentioned in the comment below, not need reinitiate the isOn inside the if else

```<code>var isOn = false;

function darkMode () {
    if(!isOn) {
        document.documentElement.setAttribute('data-theme', 'dark');
        isOn = true;
    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        isOn = false;
    }
}
</code>```

in even more elegant way, you can do:

```<code>var isOn = false;

function darkMode () {

    document.documentElement.setAttribute('data-theme', ['dark', 'light'][+isOn]);
    isOn = !isOn;

}
</code>```

explanation

+isOn convert it to number, so true become 1 and false become 0.
Then you use this number as index to choose dark or light accordingly.

isOn=!isOn flip the current value of isOn - true become false and false become true

Body:
I want to have a button inside my navbar (ul li) that can toggle between theme=light and theme=dark. However, only activating dark mode works.

Code:

I created a button

, with a JS function

function darkMode () {
    var isOn = false;
    if(Boolean(isOn) === false) {
        document.documentElement.setAttribute('data-theme', 'dark');
        var isOn = true;
    }
    else if(Boolean(isOn) === true) {
        document.documentElement.setAttribute('data-theme', 'light');
        var isOn = false;
    }
}

and my css looks like this:

:root, [data-theme="light"] {
  --bg-color: #ffffff;
  --bg-color-inv: #000000;
  --outline-color: #000000;
  --text-primary: #000000;
  --text-primary-inv: #ffffff;
  --text-secondary: #a4a4a4;
  --text-secondary-hover: #000000;
  --chivo: 'Chivo', sans-serif;
}

[data-theme="dark"] {
  --bg-color: #121212;
  --bg-color-inv: #ffffff;
  --outline-color: #ffffff;
  --text-primary: #ffffff;
  --text-primary-inv: #000000;
  --text-secondary: #5b5b5b;
  --text-secondary-hover: #ffffff;
}

Body:
1. You start the function by setting the isOn to false. so Boolean(isOn) === false alwaeys return true. you should init the isOn variable outside the function

2 Why you convert the isOn to boolean? it's already boolean type..

3 You not really need else if.. if it is not false it is true..

4. as mentioned in the comment below, not need reinitiate the isOn inside the if else

var isOn = false;

function darkMode () {
    if(!isOn) {
        document.documentElement.setAttribute('data-theme', 'dark');
        isOn = true;
    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        isOn = false;
    }
}

in even more elegant way, you can do:

var isOn = false;

function darkMode () {

    document.documentElement.setAttribute('data-theme', ['dark', 'light'][+isOn]);
    isOn = !isOn;

}

explanation

+isOn convert it to number, so true become 1 and false become 0.
Then you use this number as index to choose dark or light accordingly.

isOn=!isOn flip the current value of isOn - true become false and false become true


问:
How can I merge 2 dictionaries into one array?
My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?

I just filter the response data from the server like this:

```<code>        var dataBanDau: [SDFilterModel] = []
        var quickData: [SDFilterModel] = []

        let filters: [SDFilterModel] = data

        self.filterEntries = filters

        //let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
//            self.filterEntriesStoreConstant = nsarray as! Array

        self.dataBanDau = filters

        for i in 0..<self.dataBanDau.count {
            if self.dataBanDau[i].search_key.count == 0 {
                self.quickData.append(self.dataBanDau[i])
            }
        }

        self.quickData = self.quickData.filter {
            $0.type != "range"
        }

        DispatchQueue.main.async {
            //Note: Reload TableView
            self.quickFilterCollection.reloadData()
            completed(true)
        }
    }
</code>```

the class SDFilterModel:

```<code>class SDFilterModel: DSBaseModel {
    var name = String()
    var type = String()
    var is_expanded = Int()
    var search_key = String()
    var filterEntries : [SDFilterModel]?

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = SDFilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);
        value = self.valueParse()

        name = dict.getString(forKey: "name")
        type = dict.getString(forKey: "type")
        search_key = dict.getString(forKey: "search_key")
        is_expanded = dict.getInt(forKey: "is_expanded")!
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var value: [AttributeValueModel] = [];

    func valueParse()-> [AttributeValueModel] {
        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

//            if type == .Range  && item.option_id == "0" {
//                item.setRangeOptionID(aValue: item.option_name!)
//            }
//
            output.append(item);
        }

        return output;
    }
</code>```

答:
Let be Assume you have let myArray = [1,2,3,4,5,6,7,8]

Now you wanted to square of each and every element in the array,

With for loop you do like this

```<code>for item in myArray {
    print(item * item)
}
</code>```

Now assume item = $0

With for map you jus do

```<code>myArray.map({ $0 * $0 })
</code>```

Both will gave same output.

map : Use to do same operation on every element of array.

flatmap : It is used to flattern the array of array.

```<code>let myArr = [[1,2,3],[4,5,6,7]]
</code>```

and you want o/p as [1,2,3,4,5,6,7]

So can get above output with myArr.flatMap({$0})

Now back to your question.

```<code>let reqArray = myModel.data.map({ $0.value }).flatMap({ $0 })
</code>```

First, map gaves you array-of-array of key value but you need a single array, so for that you need to use flatmap.

You can take ref : https://medium.com/@Dougly/higher-order-functions-in-swift-sorted-map-filter-reduce-dff60b5b6adf

Body:
My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?

I just filter the response data from the server like this:

        var dataBanDau: [SDFilterModel] = []
        var quickData: [SDFilterModel] = []

        let filters: [SDFilterModel] = data

        self.filterEntries = filters

        //let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
//            self.filterEntriesStoreConstant = nsarray as! Array

        self.dataBanDau = filters

        for i in 0..<self.dataBanDau.count {
            if self.dataBanDau[i].search_key.count == 0 {
                self.quickData.append(self.dataBanDau[i])
            }
        }

        self.quickData = self.quickData.filter {
            $0.type != "range"
        }

        DispatchQueue.main.async {
            //Note: Reload TableView
            self.quickFilterCollection.reloadData()
            completed(true)
        }
    }

the class SDFilterModel:

class SDFilterModel: DSBaseModel {
    var name = String()
    var type = String()
    var is_expanded = Int()
    var search_key = String()
    var filterEntries : [SDFilterModel]?

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = SDFilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);
        value = self.valueParse()

        name = dict.getString(forKey: "name")
        type = dict.getString(forKey: "type")
        search_key = dict.getString(forKey: "search_key")
        is_expanded = dict.getInt(forKey: "is_expanded")!
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var value: [AttributeValueModel] = [];

    func valueParse()-> [AttributeValueModel] {
        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

//            if type == .Range  && item.option_id == "0" {
//                item.setRangeOptionID(aValue: item.option_name!)
//            }
//
            output.append(item);
        }

        return output;
    }

Body:
Let be Assume you have let myArray = [1,2,3,4,5,6,7,8]

Now you wanted to square of each and every element in the array,

With for loop you do like this

for item in myArray {
    print(item * item)
}

Now assume item = $0

With for map you jus do

myArray.map({ $0 * $0 })

Both will gave same output.

map : Use to do same operation on every element of array.

flatmap : It is used to flattern the array of array.

let myArr = [[1,2,3],[4,5,6,7]]

and you want o/p as [1,2,3,4,5,6,7]

So can get above output with myArr.flatMap({$0})

Now back to your question.

let reqArray = myModel.data.map({ $0.value }).flatMap({ $0 })

First, map gaves you array-of-array of key value but you need a single array, so for that you need to use flatmap.

You can take ref : https://medium.com/@Dougly/higher-order-functions-in-swift-sorted-map-filter-reduce-dff60b5b6adf


问:
No signing certificate "iOS Distribution" found
I am trying to sign an app with my client's certificates. I have received the following file from the client

I tried installing the ios_distribution certificate and the key (.p12). Also I have installed the provisioning profile. Now when I try to sign the app with the provisioning profile, it does show up in the drop down but I get the following error:-

```<code>No "iOS Distribution" signing certificate matching team ID "7S977Lxxx" with a private key was found
</code>```

How can I solve this issue? Any help is appreciated.

答: Double click and install the production certificate in your key chain. This might resolve the issue.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to sign an app with my client's certificates. I have received the following file from the client

I tried installing the ios_distribution certificate and the key (.p12). Also I have installed the provisioning profile. Now when I try to sign the app with the provisioning profile, it does show up in the drop down but I get the following error:-

No "iOS Distribution" signing certificate matching team ID "7S977Lxxx" with a private key was found

How can I solve this issue? Any help is appreciated.


问:
Using Marklogic 8 Query Console Javascript on Windows 7
I am just starting to work with Marklogic and I am running simple commands like xdmp.document.load to ingest a json file

```<code>declareUpdate();
xdmp.documentLoad("C:\Users\Documents\SemanticData\Recipies\Tofu-Soup.json",
    {
      "uri" : "/documents/tofu-soup.json",
      "permissions" : xdmp.defaultPermissions(),
      "collections" : ["soup", "vegetarian"],
      "encoding" : 'UTF-8'
    })
</code>```

I receive the following error where the path name has had all the "\" directory separators removed.

[javascript] SVC-FILOPN:
  xdmp.documentLoad("C:UsersDocumentsSemanticDataRecipiesTofu-Soup.json",
  {uri:"/documents/tofu-soup.json", permissions:[], collections:["soup",
  "vegetarian"], ...}) -- File open error: open
  'C:UsersDocumentsSemanticDataRecipiesTofu-Soup.json': No such file or
  directory

I cannot find anything in the functions guide to illuminate me.

Any ideas

答:
You can run command in following way. </p>

```<code>declareUpdate();
xdmp.documentLoad("C:\\Users\\Documents\\SemanticData\\Recipies\\Tofu-Soup.json",
    {
      "uri" : "/documents/tofu-soup.json",
      "permissions" : xdmp.defaultPermissions(),
      "collections" : ["soup", "vegetarian"],
      "encoding" : 'UTF-8'
    })
</code>```

Body:
I am just starting to work with Marklogic and I am running simple commands like xdmp.document.load to ingest a json file

declareUpdate();
xdmp.documentLoad("C:\Users\Documents\SemanticData\Recipies\Tofu-Soup.json",
    {
      "uri" : "/documents/tofu-soup.json",
      "permissions" : xdmp.defaultPermissions(),
      "collections" : ["soup", "vegetarian"],
      "encoding" : 'UTF-8'
    })

I receive the following error where the path name has had all the "\" directory separators removed.

[javascript] SVC-FILOPN:
  xdmp.documentLoad("C:UsersDocumentsSemanticDataRecipiesTofu-Soup.json",
  {uri:"/documents/tofu-soup.json", permissions:[], collections:["soup",
  "vegetarian"], ...}) -- File open error: open
  'C:UsersDocumentsSemanticDataRecipiesTofu-Soup.json': No such file or
  directory

I cannot find anything in the functions guide to illuminate me.

Any ideas

Body:
You can run command in following way.

declareUpdate();
xdmp.documentLoad("C:\\Users\\Documents\\SemanticData\\Recipies\\Tofu-Soup.json",
    {
      "uri" : "/documents/tofu-soup.json",
      "permissions" : xdmp.defaultPermissions(),
      "collections" : ["soup", "vegetarian"],
      "encoding" : 'UTF-8'
    })


问:
Pull nested JSON data using foreach loop in php
I want to pull data from below JSON format using PHP (foreach loop).

User detail is correspondence to house detail and house detail correspondence to individual meter reading.

I want to show Username, Device_No and all meter_detail field. Please help me out.

```<code>{
    "id": 7,
    "Username": "user",
    "Housename": "Leela",
    "Houses_list": [{
            "id": 1,
            "Device_No": 1111,
            "meter_detail": [{
                    "id": 1,
                    "flow": 12,
                    "date": "2020-02-13T12:05:14.709Z",
                    "opening": 5,
                    "volume": 1234
                },
                {
                    "id": 2,
                    "flow": 32,
                    "date": "2020-02-13T12:05:26.821Z",
                    "opening": 2,
                    "volume": 1235
                }
            ]
        },
        {
            "id": 2,
            "Device_No": 231,
            "meter_detail": [{
                "id": 3,
                "flow": 78,
                "date": "2020-02-13T12:05:41.331Z",
                "opening": 5,
                "volume": 7854
            }]
        }
    ]
}
</code>```

答:
You need to convert the JSON to an array by using json_decode(). Then a couple of foreach loops would do work for you:

```<code><?php
    $json = '{
        "id": 7,
        "Username": "user",
        "Housename": "Leela",
        "Houses_list": [{
                "id": 1,
                "Device_No": 1111,
                "meter_detail": [{
                        "id": 1,
                        "flow": 12,
                        "date": "2020-02-13T12:05:14.709Z",
                        "opening": 5,
                        "volume": 1234
                    },
                    {
                        "id": 2,
                        "flow": 32,
                        "date": "2020-02-13T12:05:26.821Z",
                        "opening": 2,
                        "volume": 1235
                    }
                ]
            },
            {
                "id": 2,
                "Device_No": 231,
                "meter_detail": [{
                    "id": 3,
                    "flow": 78,
                    "date": "2020-02-13T12:05:41.331Z",
                    "opening": 5,
                    "volume": 7854
                }]
            }
        ]
    }';

    $input = json_decode($json, true);

    echo 'Username: '.$input['Username'].'<br>';
    foreach ($input['Houses_list'] as $device){
        echo '<br>Device No: '.$device['Device_No'].'<br>';
        foreach ($device['meter_detail'] as $metrics){
            echo '<table style="border: 1px solid black">';
            foreach ($metrics as $key => $metric){
                echo '<tr><td>'.$key.'</td><td>'.$metric.'</td></tr>';
            }
            echo '</table>';
        }
    }
?>
</code>```

Output:

Body:
I want to pull data from below JSON format using PHP (foreach loop).

User detail is correspondence to house detail and house detail correspondence to individual meter reading.

I want to show Username, Device_No and all meter_detail field. Please help me out.

{
    "id": 7,
    "Username": "user",
    "Housename": "Leela",
    "Houses_list": [{
            "id": 1,
            "Device_No": 1111,
            "meter_detail": [{
                    "id": 1,
                    "flow": 12,
                    "date": "2020-02-13T12:05:14.709Z",
                    "opening": 5,
                    "volume": 1234
                },
                {
                    "id": 2,
                    "flow": 32,
                    "date": "2020-02-13T12:05:26.821Z",
                    "opening": 2,
                    "volume": 1235
                }
            ]
        },
        {
            "id": 2,
            "Device_No": 231,
            "meter_detail": [{
                "id": 3,
                "flow": 78,
                "date": "2020-02-13T12:05:41.331Z",
                "opening": 5,
                "volume": 7854
            }]
        }
    ]
}

Body:
You need to convert the JSON to an array by using json_decode(). Then a couple of foreach loops would do work for you:

<?php
    $json = '{
        "id": 7,
        "Username": "user",
        "Housename": "Leela",
        "Houses_list": [{
                "id": 1,
                "Device_No": 1111,
                "meter_detail": [{
                        "id": 1,
                        "flow": 12,
                        "date": "2020-02-13T12:05:14.709Z",
                        "opening": 5,
                        "volume": 1234
                    },
                    {
                        "id": 2,
                        "flow": 32,
                        "date": "2020-02-13T12:05:26.821Z",
                        "opening": 2,
                        "volume": 1235
                    }
                ]
            },
            {
                "id": 2,
                "Device_No": 231,
                "meter_detail": [{
                    "id": 3,
                    "flow": 78,
                    "date": "2020-02-13T12:05:41.331Z",
                    "opening": 5,
                    "volume": 7854
                }]
            }
        ]
    }';

    $input = json_decode($json, true);

    echo 'Username: '.$input['Username'].'<br>';
    foreach ($input['Houses_list'] as $device){
        echo '<br>Device No: '.$device['Device_No'].'<br>';
        foreach ($device['meter_detail'] as $metrics){
            echo '<table style="border: 1px solid black">';
            foreach ($metrics as $key => $metric){
                echo '<tr><td>'.$key.'</td><td>'.$metric.'</td></tr>';
            }
            echo '</table>';
        }
    }
?>

Output:


问:
multiple image combination for featured block content
I'm trying to make solid markup and style for following XD layout

I added bootstrap for the full project but I'm confused about how I write markup and style for this layout with keep in mind responsiveness!

.hb-block-content-part {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url("../images/bg-two.png");
  background-size: cover;
  background-position: center center;
}

.hb-block-content-part::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 100%, rgba(0, 0, 0, 0) 100%);
}

.left-image {
  position: relative;
}

.left-image .l-main-image {
  float: right;
  position: relative;
  margin-left: 30%;
  margin-top: 10%;
  z-index: 2;
}

.left-image .l-overlay-image {
  position: absolute;
  left: -20%;
  top: 20%;
  z-index: 3;
}

.left-image .l-yellow-image {
  position: absolute;
  left: 10%;
  top: 0;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<div class="hb-block-content-part">
  <div class="container-fluid px-10-percent">
    <div class="hb-block-content">
      <div class="left-image">
        <div class="l-main-image">
          <img class="img-fluid" src="https://i.imgur.com/JQl8Uyb.jpg" alt="">
        </div>
        <div class="l-overlay-image">
          <img class="img-fluid" src="https://i.imgur.com/gBJ6kwB.jpg" alt="">
        </div>
        <div class="l-yellow-image">
          <img class="img-fluid" src="https://i.imgur.com/rfk6tzn.jpg" alt="">
        </div>
      </div>
      <div class="right-content">

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

答:
Can you provide the mobile version of this design?

Bootstrap 4 has classes for positions and grids, make sure you check the documentation here:  https://getbootstrap.com/docs/4.4/layout/overview/

You should work with flexbox or grid for a better result with responsive layouts.

See below links about:

Grid:

https://css-tricks.com/snippets/css/complete-guide-grid/

Flexbox:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
I'm trying to make solid markup and style for following XD layout

I added bootstrap for the full project but I'm confused about how I write markup and style for this layout with keep in mind responsiveness!

.hb-block-content-part {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url("../images/bg-two.png");
  background-size: cover;
  background-position: center center;
}

.hb-block-content-part::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 100%, rgba(0, 0, 0, 0) 100%);
}

.left-image {
  position: relative;
}

.left-image .l-main-image {
  float: right;
  position: relative;
  margin-left: 30%;
  margin-top: 10%;
  z-index: 2;
}

.left-image .l-overlay-image {
  position: absolute;
  left: -20%;
  top: 20%;
  z-index: 3;
}

.left-image .l-yellow-image {
  position: absolute;
  left: 10%;
  top: 0;
  z-index: 1;
}

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


问:
Printing hollow square with array
I'm trying to print a hollow square. I currently have the top, bottom, and left borders drawn but for some reason cannot get the right side to draw in the correct place. I'm  sure its a simple fix but I'm new to this so sorry for noobness.

```<code>int main()
{
    const int boardX = 10;
    const int boardY = 10;
    char gameBoard[boardX][boardY];

    for (int i = 0; i != boardX; i++)
    {
        for (int k = 0; k != boardY; k++)
        {
            if (i == 0 || i == 9 || k == 0 || k == 9)
            {
                gameBoard[i][k] = '*';
                cout << gameBoard[i][k];
            }

        }
        cout << "\n";
    }

    system("pause");
    return 0;
}
</code>```

答:
You forgot to print spaces to make the square hollow:

```<code>int main()
{
    const int boardX = 10;
    const int boardY = 10;
    char gameBoard[boardX][boardY];

    for (int i = 0; i != boardX; i++)
    {
        for (int k = 0; k != boardY; k++)
        {
            if (i == 0 || i == 9 || k == 0 || k == 9)
            {
                gameBoard[i][k] = '*';
                cout << gameBoard[i][k];
            }
            else
            {
                gameBoard[i][k] = ' ';
                cout << gameBoard[i][k];
            }

        }
        cout << "\n";
    }

    return 0;
}
</code>```

Note: I followed your style to make the changed part stand out, but normally you would separate the construction of the board and printing it to the screen into separate code blocks/functions.

Title: Printing hollow square with array

Body:
I'm trying to print a hollow square. I currently have the top, bottom, and left borders drawn but for some reason cannot get the right side to draw in the correct place. I'm  sure its a simple fix but I'm new to this so sorry for noobness.

int main()
{
    const int boardX = 10;
    const int boardY = 10;
    char gameBoard[boardX][boardY];

    for (int i = 0; i != boardX; i++)
    {
        for (int k = 0; k != boardY; k++)
        {
            if (i == 0 || i == 9 || k == 0 || k == 9)
            {
                gameBoard[i][k] = '*';
                cout << gameBoard[i][k];
            }

        }
        cout << "\n";
    }

    system("pause");
    return 0;
}

Body:
You forgot to print spaces to make the square hollow:

int main()
{
    const int boardX = 10;
    const int boardY = 10;
    char gameBoard[boardX][boardY];

    for (int i = 0; i != boardX; i++)
    {
        for (int k = 0; k != boardY; k++)
        {
            if (i == 0 || i == 9 || k == 0 || k == 9)
            {
                gameBoard[i][k] = '*';
                cout << gameBoard[i][k];
            }
            else
            {
                gameBoard[i][k] = ' ';
                cout << gameBoard[i][k];
            }

        }
        cout << "\n";
    }

    return 0;
}

Note: I followed your style to make the changed part stand out, but normally you would separate the construction of the board and printing it to the screen into separate code blocks/functions.


问:
How to delete a directory in hadoop which has the '[' character in its name
I accidentally uploaded a file to the "/hadoo[-workshop" path and I am trying to delete it.

I am using the hadoop fs -rmr <path> Hadoop 0.20.2 .
I have tried every permutation of putting the file path in single quotes ('), double quotes ("), and escaping the "[" character with a backslash (), but every time i get an error saying

rmr: Illegal file pattern: Expecting set closure character or end of range, or } for glob hadoo[-workshop at 15

答:
I managed to delete it by using a wildcard (*) in the command.

hadoop fs -rmr /hadoo*

I guess "deleting everything that start with the string before faulty character" is good enough.

NOTE: If you use this and you have other directories with a similar name don't use -skipTrash to be able to recover the other directories


问:
Can I override the color of a control when Visual Styles are enabled?
I have an application in C++ Builder 2010 that has Visual Styles/Runtime Themes enabled to use the runtime look for buttons and tabs.  However, I have a set of checkboxes (TCheckBox) for which I would like to override the runtime style, if possible.

My checkboxes are used to toggle some graphical overlays for various colors.  When I have runtime themes disabled, I can set the background of the checkbox to show which color it will enable, like so:

Is there a way I can achieve this same effect when runtime themes are enabled?

Thanks to stukelly, I can selectively disable visual styles for individual controls, but I seem unable to modify the color or other styling of that control after I call SetWindowTheme as below:

```<code>SetWindowTheme(CheckBox1->Handle, L" ", "");
</code>```

答:
You could try disabling the theme for each checkbox using the SetWindowTheme function.

```<code>  SetWindowTheme(CheckBox1->Handle, NULL, "");
</code>```

I'm not sure if the second parameter needs to be NULL or L" " as the documentation mentions.

```<code>  SetWindowTheme(CheckBox1->Handle, L" ", "");
</code>```

I used the following references to answer this question.

http://www.delphigroups.info/3/7/54654.html

borland.public.delphi.ide.general

Body:
I have an application in C++ Builder 2010 that has Visual Styles/Runtime Themes enabled to use the runtime look for buttons and tabs.  However, I have a set of checkboxes (TCheckBox) for which I would like to override the runtime style, if possible.

My checkboxes are used to toggle some graphical overlays for various colors.  When I have runtime themes disabled, I can set the background of the checkbox to show which color it will enable, like so:

Is there a way I can achieve this same effect when runtime themes are enabled?

Thanks to stukelly, I can selectively disable visual styles for individual controls, but I seem unable to modify the color or other styling of that control after I call SetWindowTheme as below:

SetWindowTheme(CheckBox1->Handle, L" ", "");

Body:
You could try disabling the theme for each checkbox using the SetWindowTheme function.

  SetWindowTheme(CheckBox1->Handle, NULL, "");

I'm not sure if the second parameter needs to be NULL or L" " as the documentation mentions.

  SetWindowTheme(CheckBox1->Handle, L" ", "");

I used the following references to answer this question.

http://www.delphigroups.info/3/7/54654.html

borland.public.delphi.ide.general


问:
How do I open a URL from C++?
how can I open a URL from my C++ program?

In ruby you can do

```<code>%x(open https://google.com)
</code>```

What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)

Here's my code:

```<code>#include <stdio.h>
#include <string.h>
#include <fstream>

int main (int argc, char *argv[])
{
    char url[1000] = "https://www.google.com";

    std::fstream fs;
    fs.open(url);
    fs.close();

    return 0;
}
</code>```

答:
I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>

For those of you that are using Windows, as I am, you can use the following:

```<code>std::string op = std::string("start ").append(url);
system(op.c_str());
</code>```

Title: How do I open a URL from C++?

Body:
how can I open a URL from my C++ program?

In ruby you can do

%x(open https://google.com)

What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)

Here's my code:

#include <stdio.h>
#include <string.h>
#include <fstream>

int main (int argc, char *argv[])
{
    char url[1000] = "https://www.google.com";

    std::fstream fs;
    fs.open(url);
    fs.close();

    return 0;
}

Body:
I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>

For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());


问:
How can I change app colors programmatically?
I want change to my primary colors at runtime. I can change it with custom themes and colors. But I want to change my color from service result not static styles code. Is there any way to change colors.xml programmatically.

I find a solution but that's deprecated now: https://stackoverflow.com/a/34178187/6155031

答:
Create one Singleton class that defines all the colors that you want
to change in your app.

Set its properties on app load from JSON file
obtained from the cloud.

In your app, wherever you are using color codes, don't set those values in xml. Set color values in your Java/Kotlin code.

I assume you are aware of findViewbyId. :-)


问:
How to construct a dynamic tree level by level in python?
I want to construct a dynamic tree. The initial state of the tree only has a root node, then, I hope it can add nodes level by level. These added nodes are fetched according to some additional functions. I have found some similary questions in Stack Overflow, such as How do I build a tree dynamically in Python How do I build a tree dynamically in Python,  but the answers don't satisfy my need and the originer.

答:
From the answer of the question

```<code>import collections
from functools import reduce

def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)

tree = lambda: collections.defaultdict(tree)
root = tree()

add_element(root,["top"],{}) #Make a level
add_element(root,["top","level1"],{}) # Make another level
add_element(root,["top","level1","val"],2) #Data
print(root)
</code>```

As I mentioned, it does do what you want it to do.

Body:
From the answer of the question

import collections
from functools import reduce

def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)

tree = lambda: collections.defaultdict(tree)
root = tree()

add_element(root,["top"],{}) #Make a level
add_element(root,["top","level1"],{}) # Make another level
add_element(root,["top","level1","val"],2) #Data
print(root)

As I mentioned, it does do what you want it to do.


问:
decrease height and row spacing in vuetify form
I am trying to make a form using vuetify which is basically, replicating this form.

I have tried to use vuetify grid and columns after a lot of tries I have got to this

I want to decrease the height of inputs as well as the spacing between rows.

Live code snippet https://codepen.io/ijunaid8088/pen/xxGZzGv

答:
Best possible solution without changing default library styles

              Add IP Camera

```<code>    <v-col cols="12" md="4">
      <v-text-field
        v-model="lastname"
        :rules="nameRules"
        label="Last name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        label="E-mail"
        required
      ></v-text-field>
    </v-col>
  </v-row>
  <v-row>
    <v-col cols="12" md="4">
      <v-text-field
        v-model="firstname"
        :rules="nameRules"
        label="First name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="lastname"
        :rules="nameRules"
        label="Last name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        label="E-mail"
        required
      ></v-text-field>
    </v-col>
  </v-row>
</v-container>
      </v-col>
      <v-col cols="4">4</v-col>
    </v-row>
  </v-container>
</template>
  </v-app>
</div>
//CSS
    .v-text-field {
        margin: 0;
        padding: 0;
    }
</code>```

Body:
Best possible solution without changing default library styles

              Add IP Camera

    <v-col cols="12" md="4">
      <v-text-field
        v-model="lastname"
        :rules="nameRules"
        label="Last name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        label="E-mail"
        required
      ></v-text-field>
    </v-col>
  </v-row>
  <v-row>
    <v-col cols="12" md="4">
      <v-text-field
        v-model="firstname"
        :rules="nameRules"
        label="First name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="lastname"
        :rules="nameRules"
        label="Last name"
        required
      ></v-text-field>
    </v-col>

    <v-col cols="12" md="4">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        label="E-mail"
        required
      ></v-text-field>
    </v-col>
  </v-row>
</v-container>
      </v-col>
      <v-col cols="4">4</v-col>
    </v-row>
  </v-container>
</template>
  </v-app>
</div>
//CSS
    .v-text-field {
        margin: 0;
        padding: 0;
    }


问:
How do I test that Asp.Net MVC Views are rendered without exceptions?
I have come up with a small issue in my application.

I changed the namespace of my main application to be from MyApp.Models to MyApp.ViewModels so that the namespaces were less confusing overall (since that namespace only has view models and no business models).  I changed all the references I could find, including in my views, and I re-ran all my unit tests and went through the application, and all seemed fine.

A few days later I got a report that the registration page had an error when it was brought up.  After looking it turns out I forgot to fix the namespace on the registration page, and thus it was failing to compile the view.

This worries me.  The whole point of unit testing, and one of the biggest lures of Asp.Net MVC, is to be able to have confidence in your application by having everything tested individually automatically so that you know immediately when your modification breaks parts of the system.  Views right now seem like a major hole in this.

To be clear, I am aware you are able to turn on pre-compiling a views.  However, I do not like this option as it's not a good idea to have this on all the time (as it makes compiling a new build very, very slow), and having a separate configuration scheme for this means it's up to the user to remember to attempt to compile with that configuration scheme to check for view compile errors.

This also completely bypasses checking for runtime errors that may occur.  For example, lets say you change the viewmodel that a strongly-typed view is expecting.  You would then update the unit test to make sure that the Controller.Action() is returning a view result with the correct view model type, but that does nothing to make sure that the actual view was updated correctly for the new view, and yet this scenario will cause a run-time exception.  This is an easy scenario to occur, especially since if the differences in the two view models are only seen in partials used within the view.

Other examples of code that can cause runtime exceptions in views are incorrect loops (possibly caused by changes in a view model), code that checks a user's role (so buttons are only shown for users with credentials), incorrect casts (e.g. for converting a collection into a select list), incorrect code to sort a collection (how a collection is sorted in the display can construed as a view concern, not a controller or view model concern), if strings used for locations of files don't work correctly (T4MVC doesn't integrate well with some things, such as Telerik's script registration system) etc...

The way I see it, there are many things that can cause an exception to occur in the process of rendering a view, and I can't seem to find any way to create unit or integration tests to determine when these occur.  I would feel more comfortable if I did not have to check every page to make sure I missed a compile time or runtime error for something that a standard unit test should be able to catch.

What options do I have to do this?

I would prefer to stay away from WaTiN and other GUI testing tools, as for this I am not interested in the actual display of the page, I only want to know if the view renders or if an exception occurs and do not need the overhead of Watin running an IE instance for each test (I also think this will cause issues if I go with continuous integration at a later point).

答: mspec mvc extensions</p>

Body: mspec mvc extensions


问:
After update from Angular 8 to Angular 9, 'ng generate component' generates a .css file instead of .scss
In my project I had set up SCSS as the style. Now after the update from Angular 8 to 9, when I use the CLI to generate a new component, a CSS file is generated where I expect an SCSS file to be generated.</p>

答:
To fix it, open angular.json and search for styleext (it's in the schematics section). Rename styleext to style.

Explanation: This name has changed from styleext in version 8 to style in version 9 of Angular. However the ng update command did not take account of this. They have fixed it in the meantime so future ng updates will work properly:

https://github.com/angular/angular-cli/issues/16949


问:
How to merge columns in temporary table while inserting data from a SubQuery in SQL?
I have a temp table #TestData as below where data is inserted using sub-query

```<code>Id      Amount         Ccy    Description
2012    2373350.000    INR    test1
2012    2321030.000    INR    test12
2014    2350.000       INR    test4
2014    30.000         USD    test5
2014    130.000        USD    test6
</code>```

code updated : using stuff and group by to concatenate strings hoever getting error invalid object Tmpta

```<code>      INSERT  INTO #TestData

       -- SELECT  Tmpta.Id,Tmpta.Amount,Tmpta.Ccy,tmpta.Description
     SELECT  Tmpta.Id ,
                    STUFF(( SELECT  ',' + CAST(B.[Amount] AS VARCHAR(20))
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[Amount]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Amount ,
                    STUFF(( SELECT  ',' + B.[cur]
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[cur]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Ccy ,
                    STUFF(( SELECT  ',' + B.[Description]
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[Description]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Description
         FROM    ( SELECT SubQuery
                  ) Tmpta

         WHERE   tmpta.Id in (2012,2014)
         group by Tmpta.id
</code>```

I want to merge data as below :

```<code>Id      Amount                         Ccy          Description
2012    2373350.000,2321030.000        INR,INR      test1,test12
2014    2350.000,30.000,130.000        INR,USD,USD  test4,test5,test6
</code>```

any idea how we can achieve this?

Please help.
Thanks!

答:
try below query</p>

```<code>    SELECT
    ID,  string_agg(Amount,',') As Amount, string_agg(ccy,',') as CCY, string_agg(description, ',')
FROM
    <table name>
GROUP BY
    ID;
</code>```

Body:
I have a temp table #TestData as below where data is inserted using sub-query

Id      Amount         Ccy    Description
2012    2373350.000    INR    test1
2012    2321030.000    INR    test12
2014    2350.000       INR    test4
2014    30.000         USD    test5
2014    130.000        USD    test6

code updated : using stuff and group by to concatenate strings hoever getting error invalid object Tmpta

      INSERT  INTO #TestData

       -- SELECT  Tmpta.Id,Tmpta.Amount,Tmpta.Ccy,tmpta.Description
     SELECT  Tmpta.Id ,
                    STUFF(( SELECT  ',' + CAST(B.[Amount] AS VARCHAR(20))
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[Amount]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Amount ,
                    STUFF(( SELECT  ',' + B.[cur]
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[cur]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Ccy ,
                    STUFF(( SELECT  ',' + B.[Description]
                            FROM    Tmpta B
                            WHERE   B.id = Tmpta.id
                            ORDER BY B.[Description]
                          FOR
                            XML PATH('')
                          ), 1, 1, '') AS Description
         FROM    ( SELECT SubQuery
                  ) Tmpta

         WHERE   tmpta.Id in (2012,2014)
         group by Tmpta.id

I want to merge data as below :

Id      Amount                         Ccy          Description
2012    2373350.000,2321030.000        INR,INR      test1,test12
2014    2350.000,30.000,130.000        INR,USD,USD  test4,test5,test6

any idea how we can achieve this?

Please help.
Thanks!

Body:
try below query

    SELECT
    ID,  string_agg(Amount,',') As Amount, string_agg(ccy,',') as CCY, string_agg(description, ',')
FROM
    <table name>
GROUP BY
    ID;


问:
How to compute de Bruijn sequences for non-power-of-two-sized alphabets?
I'm trying to compute de Bruijn sequences for alphabets which have a number of characters which is not a power of two.

For alphabets with a 2^k characters, calculating de Bruijn sequences is easy: There are several simple rules, such as "Prefer Ones" and "Prefer Opposites" which work for generating B(2,n). B(2^k,n) is exactly the same as B(2,kn), if you read the 1s and 0s as binary codes for the actual characters in your alphabet. E.g., you can interpret B(2,8n) as being over n-length sequences of bytes.

Prefer Ones is quite simple: Write n zeros. Then, always write a one unless it would cause the repetition of an n-length string; otherwise, write a zero.

Presently, I don't see how to generalize such rules to non-power-of-two-sized alphabets.

There's a general method for calculating de Bruijn sequences via graphs: Let each n-length sequence generated by your alphabet be a node; put an edge from A to B iff the rightmost n-1 characters of A are the same as the leftmost n-1 characters of B. Label each edge with the last character of the string in the head vertex. Any Eulerian path through this graph will generate a de Bruijn sequence, and the peculiar construction we used guarantees that there will be at least one such path. We can use Fleury's Algorithm to (nondeterministically) construct an Eulerian path:

Choose a vertex.

Leave that vertex via some edge and delete that edge, only choosing edges whose deletion would disconnect the vertex from the graph if there is no alternative.

Append to your string the label of the edge you just deleted.

Goto 2 until all edges are gone.

The resulting string will be a de Bruijn sequence.

This algorithm is somewhat more complex to implement than Prefer Ones. The simplicity of Prefer Ones is that one needs only to consult the output already generated to determine what to do. Is there a straightforward way to generalize Prefer Ones (or, possibly Prefer Opposites) to alphabets of non-power-of-two sizes?

答:
Based on @stefan-gruenwald's code, which lacks a simply categorizable set of words. Although I'm not capable (yet) to emend it, I wrote some lines for finding the error, which seems to be

import itertools

def debruijn (k, n) :
    v =  [ 0 for _ in range (n) ]
    l = 1
    r =  []
    while True :
        if n % l == 0 :
            r.extend (v [0:l])
        for i in range (l, n) :
            v [i] = v [i-l]
        l = n
        while l > 0 and v [l-1] >= k-1 :
            l -= 1
        if l == 0 :
            break
        v [l-1] += 1
    return r

K = int (input ( 'k ' ) )
N = int (input ( 'n ' ) )

for k in range (K) :                                # length of alphabet
    for n in range (N) :                            # length of word(s)
        List = debruijn (k, n)
        l = ''
        for L in List :
            l += str (L)
        L = itertools.product (range (k), repeat = n)
        print ( 'alphabet k', k, '\tword n', n, str ('|' + l + '|') )
        for a in L :
            searchstr = ''
            for A in a :
                searchstr += str (A)
            if not searchstr in l :
                print ( searchstr, end = ' ' )
        print ()
```

<p>Also saveable in a file:</p>

<pre class="lang-py prettyprint-override"><code>import itertools

def debruijn (k, n) :
    v =  [ 0 for _ in range (n) ]
    l = 1
    r =  []
    while True :
        if n % l == 0 :
            r.extend (v [0:l])
        for i in range (l, n) :
            v [i] = v [i-l]
        l = n
        while l > 0 and v [l-1] >= k-1 :
            l -= 1
        if l == 0 :
            break
        v [l-1] += 1
    return r

K = int (input ( 'k ' ) )
N = int (input ( 'n ' ) )

for k in range (K) :                                # length of alphabet
    for n in range (N) :                            # length of word(s)
        List = debruijn (k, n)
        l = ''
        for L in List :
            l += str (L)
        L = itertools.product (range (k), repeat = n)
        with open (str (k) + '-' + str (n), 'w') as f :
            f.write ( 'alphabet length ' + str (k) + '\tword length ' + str (n) + '\n' + l + '\nnot in:\n' )
            for a in L :
                searchstr = ''
                for A in a :
                    searchstr += str (A)
                if not searchstr in l :
                    f.write ( searchstr + ' ' )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Based on @stefan-gruenwald's code, which lacks a simply categorizable set of words. Although I'm not capable (yet) to emend it, I wrote some lines for finding the error, which seems to be

import itertools

def debruijn (k, n) :
    v =  [ 0 for _ in range (n) ]
    l = 1
    r =  []
    while True :
        if n % l == 0 :
            r.extend (v [0:l])
        for i in range (l, n) :
            v [i] = v [i-l]
        l = n
        while l > 0 and v [l-1] >= k-1 :
            l -= 1
        if l == 0 :
            break
        v [l-1] += 1
    return r

K = int (input ( 'k ' ) )
N = int (input ( 'n ' ) )

for k in range (K) :                                # length of alphabet
    for n in range (N) :                            # length of word(s)
        List = debruijn (k, n)
        l = ''
        for L in List :
            l += str (L)
        L = itertools.product (range (k), repeat = n)
        print ( 'alphabet k', k, '\tword n', n, str ('|' + l + '|') )
        for a in L :
            searchstr = ''
            for A in a :
                searchstr += str (A)
            if not searchstr in l :
                print ( searchstr, end = ' ' )
        print ()

Also saveable in a file:

import itertools

def debruijn (k, n) :
    v =  [ 0 for _ in range (n) ]
    l = 1
    r =  []
    while True :
        if n % l == 0 :
            r.extend (v [0:l])
        for i in range (l, n) :
            v [i] = v [i-l]
        l = n
        while l > 0 and v [l-1] >= k-1 :
            l -= 1
        if l == 0 :
            break
        v [l-1] += 1
    return r

K = int (input ( 'k ' ) )
N = int (input ( 'n ' ) )

for k in range (K) :                                # length of alphabet
    for n in range (N) :                            # length of word(s)
        List = debruijn (k, n)
        l = ''
        for L in List :
            l += str (L)
        L = itertools.product (range (k), repeat = n)
        with open (str (k) + '-' + str (n), 'w') as f :
            f.write ( 'alphabet length ' + str (k) + '\tword length ' + str (n) + '\n' + l + '\nnot in:\n' )
            for a in L :
                searchstr = ''
                for A in a :
                    searchstr += str (A)
                if not searchstr in l :
                    f.write ( searchstr + ' ' )


问:
Vuepress custom theme and postcss
I made a custom vuepress theme and published it on npm.
Then I import it in a vuepress project, and the theme shows up.

The problem: the postcss plugins required by the theme are not processed.

The postcss plugins are in the dependencies of the theme's package.json and in the theme's index.js:

module.exports = {
    postcss: {
      plugins: [
        require('postcss-normalize'),
        require('postcss-preset-env')({
          stage: 0
        })
      ]
    }
  }
```

It does not work.

What is the correct way to register the postcss plugins in the vuepress theme?

Thank you

答: according to this issue, it looks like a bug</p>

Title: Vuepress custom theme and postcss

Body:
I made a custom vuepress theme and published it on npm.
Then I import it in a vuepress project, and the theme shows up.

The problem: the postcss plugins required by the theme are not processed.

The postcss plugins are in the dependencies of the theme's package.json and in the theme's index.js:

module.exports = {
    postcss: {
      plugins: [
        require('postcss-normalize'),
        require('postcss-preset-env')({
          stage: 0
        })
      ]
    }
  }

It does not work.

What is the correct way to register the postcss plugins in the vuepress theme?

Thank you


问:
Create a firewall rule using powershell
I am trying to create a firewall rule for java in powershell. The problem is that even if I create exactly the same rule as windows creates automatically, it simply ignores it (I create the rule, then I start our custom company application - just normally from desktop - which uses java and then the firewall window asking about allowing or blocking traffic appears - I mean the Windows Security Alert window, which appears when you run an application for the first time). Is it somehow possible? I just want to automatically allow java through firewall in my script without the need of user interaction.
This is the command I'm using: </p>

```<code>New-NetFirewallRule -DisplayName "Java(TM) Platform SE binary" -Direction Inbound -Program "C:\program files (x86)\common files\oracle\java\javapath_target_49433390\java.exe" -Action Allow
</code>```

答:
I've got the same trouble using netsh.exe when I forgot enable=yes

```<code>netsh advfirewall firewall add rule name="app name" dir=in action=allow program="Full path of .exe" enable=yes
</code>```

So can you try to add -Enabled True to your command line.

Title: Create a firewall rule using powershell

Body:
I am trying to create a firewall rule for java in powershell. The problem is that even if I create exactly the same rule as windows creates automatically, it simply ignores it (I create the rule, then I start our custom company application - just normally from desktop - which uses java and then the firewall window asking about allowing or blocking traffic appears - I mean the Windows Security Alert window, which appears when you run an application for the first time). Is it somehow possible? I just want to automatically allow java through firewall in my script without the need of user interaction.
This is the command I'm using:

New-NetFirewallRule -DisplayName "Java(TM) Platform SE binary" -Direction Inbound -Program "C:\program files (x86)\common files\oracle\java\javapath_target_49433390\java.exe" -Action Allow

Body:
I've got the same trouble using netsh.exe when I forgot enable=yes

netsh advfirewall firewall add rule name="app name" dir=in action=allow program="Full path of .exe" enable=yes

So can you try to add -Enabled True to your command line.