问:
HTML webpack plugin not injecting script to template
When trying to build the project, two HTML files get created i.e (dist/test.html and dist/src/index.html)

dist/test.html

```<code>/dist/src/index.html?88827167<script type="text/javascript"
  src="/assets/vendors.chunk.js"></script>
<script type="text/javascript" src="/assets/client.js"></script>
</code>```

dist/src/index.html

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta http-equiv="cache-control" content="max-age=0" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
  <meta http-equiv="pragma" content="no-cache" />
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>

<body>
  <div id="app"></div>

</body>

</html>

</code>```

webpack.config.js

```<code>
import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import WebpackAssetsManifest from 'webpack-assets-manifest';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import WriteFilePlugin from 'write-file-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import overrideRules from './lib/overrideRules';
import pkg from '../package.json';

const ROOT_DIR = path.resolve(__dirname, '..');
const resolvePath = (...args) => path.resolve(ROOT_DIR, ...args);
const SRC_DIR = resolvePath('src');
const BUILD_DIR = resolvePath('build');

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
  process.argv.includes('--analyze') || process.argv.includes('--analyse');

const reScript = /\.(js|jsx|mjs)$/;
const reStyle = /\.(css|less|styl|scss|sass|sss)$/;
const reImage = /\.(bmp|gif|jpg|jpeg|png|svg)$/;
const staticAssetName = isDebug
  ? '[path][name].[ext]?[hash:8]'
  : '[hash:8].[ext]';

// CSS Nano options http://cssnano.co/
const minimizeCssOptions = {
  discardComments: { removeAll: true },
};

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: ROOT_DIR,

  mode: isDebug ? 'development' : 'production',

  output: {
    path: resolvePath(BUILD_DIR, 'public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug
      ? '[name].chunk.js'
      : '[name].[chunkhash:8].chunk.js',
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: [SRC_DIR, resolvePath('tools')],
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          configFile: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: pkg.browserslist,
                },
                forceAllTransforms: !isDebug, // for UglifyJS
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-flow
            '@babel/preset-flow',
            // JSX
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            ['@babel/preset-react', { development: isDebug }],
          ],
          plugins: [
            // Experimental ECMAScript proposals
            '@babel/plugin-proposal-class-properties',
            '@babel/plugin-syntax-dynamic-import',
            // Treat React JSX elements as value types and hoist them to the highest scope
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
            ...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
            // Replaces the React.createElement function with one that is more optimized for production
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
            ...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
            // Remove unnecessary React propTypes from the production build
            // https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
            ...(isDebug ? [] : ['transform-react-remove-prop-types']),
          ],
        },
      },

      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: SRC_DIR,
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: SRC_DIR,
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug
                ? '[name]-[local]-[hash:base64:5]'
                : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Apply PostCSS plugins including autoprefixer
          {
            loader: 'postcss-loader',
            options: {
              config: {
                path: './tools/postcss.config.js',
              },
            },
          },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.(scss|sass)$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: resolvePath(
                'node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['@babel/polyfill', './src/client.js'],
  },

  plugins: [
    // Forces webpack-dev-server program to write bundle files to the file system.
    new WriteFilePlugin(),
    new HtmlWebpackPlugin({
      inject: 'body',
      template: './src/index.html',
      filename: 'test.html',
      minify: false,
      title: 'React Kit',
    }),
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/webdeveric/webpack-assets-manifest#options
    new WebpackAssetsManifest({
      output: `${BUILD_DIR}/asset-manifest.json`,
      publicPath: true,
      writeToDisk: true,
      customize: ({ key, value }) => {
        // You can prevent adding items to the manifest by returning false.
        if (key.toLowerCase().endsWith('.map')) return false;
        return { key, value };
      },
      done: (manifest, stats) => {
        // Write chunk-manifest.json.json
        const chunkFileName = `${BUILD_DIR}/chunk-manifest.json`;
        try {
          const fileFilter = file => !file.endsWith('.map');
          const addPath = file => manifest.getPublicPath(file);
          const chunkFiles = stats.compilation.chunkGroups.reduce((acc, c) => {
            acc[c.name] = [
              ...(acc[c.name] || []),
              ...c.chunks.reduce(
                (files, cc) => [
                  ...files,
                  ...cc.files.filter(fileFilter).map(addPath),
                ],
                [],
              ),
            ];
            return acc;
          }, Object.create(null));
          fs.writeFileSync(chunkFileName, JSON.stringify(chunkFiles, null, 2));
        } catch (err) {
          console.error(`ERROR: Cannot write ${chunkFileName}: `, err);
          if (!isDebug) process.exit(1);
        }
      },
    }),

    ...(isDebug
      ? []
      : [
          // Webpack Bundle Analyzer
          // https://github.com/th0r/webpack-bundle-analyzer
          ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
        ]),
  ],

  // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        },
      },
    },
  },

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['@babel/polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: BUILD_DIR,
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(preset =>
              preset[0] !== '@babel/preset-env'
                ? preset
                : [
                    '@babel/preset-env',
                    {
                      targets: {
                        node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                      },
                      modules: false,
                      useBuiltIns: false,
                      debug: false,
                    },
                  ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            emitFile: false,
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './chunk-manifest.json',
    './asset-manifest.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

export default [clientConfig, serverConfig];

</code>```

Question- Why there are two HTML files, with one having a reference to another one getting created?

html-webpack-plugin: ^3.2.0

答:
install html loader : npm i html-loader

then in your webpack file:

```<code>{
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { attrs: ["img:src", "link:href"] }
          }
        ]
      },
</code>```

documentation for other options

then for each html file you need to call HTML plugin:

```<code>const HTMLWebpackPlugin = require("html-webpack-plugin");

plugins: [

    new HTMLWebpackPlugin({ template: "./src/index1.html" }),
    new HTMLWebpackPlugin({ template: "./src/index2.html" }),

  ]

 //template is relative path for your html files.

};
</code>```

Note : If you have plugins that make use of it, html-webpack-plugin should be ordered first before any of the integrated plugins.

Body:
When trying to build the project, two HTML files get created i.e (dist/test.html and dist/src/index.html)

dist/test.html

/dist/src/index.html?88827167

dist/src/index.html

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta http-equiv="cache-control" content="max-age=0" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
  <meta http-equiv="pragma" content="no-cache" />
  <title><%= htmlWebpackPlugin.options.title %></title>

webpack.config.js

import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import WebpackAssetsManifest from 'webpack-assets-manifest';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import WriteFilePlugin from 'write-file-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import overrideRules from './lib/overrideRules';
import pkg from '../package.json';

const ROOT_DIR = path.resolve(__dirname, '..');
const resolvePath = (...args) => path.resolve(ROOT_DIR, ...args);
const SRC_DIR = resolvePath('src');
const BUILD_DIR = resolvePath('build');

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
  process.argv.includes('--analyze') || process.argv.includes('--analyse');

const reScript = /\.(js|jsx|mjs)$/;
const reStyle = /\.(css|less|styl|scss|sass|sss)$/;
const reImage = /\.(bmp|gif|jpg|jpeg|png|svg)$/;
const staticAssetName = isDebug
  ? '[path][name].[ext]?[hash:8]'
  : '[hash:8].[ext]';

// CSS Nano options http://cssnano.co/
const minimizeCssOptions = {
  discardComments: { removeAll: true },
};

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: ROOT_DIR,

  mode: isDebug ? 'development' : 'production',

  output: {
    path: resolvePath(BUILD_DIR, 'public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug
      ? '[name].chunk.js'
      : '[name].[chunkhash:8].chunk.js',
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: [SRC_DIR, resolvePath('tools')],
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          configFile: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: pkg.browserslist,
                },
                forceAllTransforms: !isDebug, // for UglifyJS
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-flow
            '@babel/preset-flow',
            // JSX
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            ['@babel/preset-react', { development: isDebug }],
          ],
          plugins: [
            // Experimental ECMAScript proposals
            '@babel/plugin-proposal-class-properties',
            '@babel/plugin-syntax-dynamic-import',
            // Treat React JSX elements as value types and hoist them to the highest scope
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
            ...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
            // Replaces the React.createElement function with one that is more optimized for production
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
            ...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
            // Remove unnecessary React propTypes from the production build
            // https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
            ...(isDebug ? [] : ['transform-react-remove-prop-types']),
          ],
        },
      },

      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: SRC_DIR,
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: SRC_DIR,
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug
                ? '[name]-[local]-[hash:base64:5]'
                : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Apply PostCSS plugins including autoprefixer
          {
            loader: 'postcss-loader',
            options: {
              config: {
                path: './tools/postcss.config.js',
              },
            },
          },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.(scss|sass)$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: resolvePath(
                'node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['@babel/polyfill', './src/client.js'],
  },

  plugins: [
    // Forces webpack-dev-server program to write bundle files to the file system.
    new WriteFilePlugin(),
    new HtmlWebpackPlugin({
      inject: 'body',
      template: './src/index.html',
      filename: 'test.html',
      minify: false,
      title: 'React Kit',
    }),
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/webdeveric/webpack-assets-manifest#options
    new WebpackAssetsManifest({
      output: `${BUILD_DIR}/asset-manifest.json`,
      publicPath: true,
      writeToDisk: true,
      customize: ({ key, value }) => {
        // You can prevent adding items to the manifest by returning false.
        if (key.toLowerCase().endsWith('.map')) return false;
        return { key, value };
      },
      done: (manifest, stats) => {
        // Write chunk-manifest.json.json
        const chunkFileName = `${BUILD_DIR}/chunk-manifest.json`;
        try {
          const fileFilter = file => !file.endsWith('.map');
          const addPath = file => manifest.getPublicPath(file);
          const chunkFiles = stats.compilation.chunkGroups.reduce((acc, c) => {
            acc[c.name] = [
              ...(acc[c.name] || []),
              ...c.chunks.reduce(
                (files, cc) => [
                  ...files,
                  ...cc.files.filter(fileFilter).map(addPath),
                ],
                [],
              ),
            ];
            return acc;
          }, Object.create(null));
          fs.writeFileSync(chunkFileName, JSON.stringify(chunkFiles, null, 2));
        } catch (err) {
          console.error(`ERROR: Cannot write ${chunkFileName}: `, err);
          if (!isDebug) process.exit(1);
        }
      },
    }),

    ...(isDebug
      ? []
      : [
          // Webpack Bundle Analyzer
          // https://github.com/th0r/webpack-bundle-analyzer
          ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
        ]),
  ],

  // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        },
      },
    },
  },

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['@babel/polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: BUILD_DIR,
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(preset =>
              preset[0] !== '@babel/preset-env'
                ? preset
                : [
                    '@babel/preset-env',
                    {
                      targets: {
                        node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                      },
                      modules: false,
                      useBuiltIns: false,
                      debug: false,
                    },
                  ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            emitFile: false,
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './chunk-manifest.json',
    './asset-manifest.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

export default [clientConfig, serverConfig];

Question- Why there are two HTML files, with one having a reference to another one getting created?

html-webpack-plugin: ^3.2.0

Body:
install html loader : npm i html-loader

then in your webpack file:

{
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { attrs: ["img:src", "link:href"] }
          }
        ]
      },

documentation for other options

then for each html file you need to call HTML plugin:

const HTMLWebpackPlugin = require("html-webpack-plugin");

plugins: [

    new HTMLWebpackPlugin({ template: "./src/index1.html" }),
    new HTMLWebpackPlugin({ template: "./src/index2.html" }),

  ]

 //template is relative path for your html files.

};

Note : If you have plugins that make use of it, html-webpack-plugin should be ordered first before any of the integrated plugins.


来源: stackexchange

问:
R, Python, rpy2 and drc package in Docker
I'm trying to build a docker image to execute a python proces which calls (with rpy2) the package drc from R.

I'm using a amazonlinux docker image and to use drc I have de following lines to install it via conda:

```<code>RUN conda install -c r rpy2=2.9.4 --yes
RUN conda install -c conda-forge r-drc=3.0_1 --yes
</code>```

With the image build I enter into a running container with:

```<code>docker run -it --entrypoint bash mydockerName
</code>```

And when I enter to R via R it throws me the next error:

```<code>Error: package or namespace load failed for 'utils':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
Error: package or namespace load failed for 'stats':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
During startup - Warning messages:
1: package 'utils' in options("defaultPackages") was not found
2: package 'stats' in options("defaultPackages") was not found
</code>```

I've been googling the last days and I'm out of possible solutions...

Many thanks!

Xevi

答: I fixed a similar problem in a different container type by installing 'which'. This package is often omitted from linux enviroments because there are "better" alternatives. However, R package writers often still depend on 'which'. So figure out how to install this in your container and it may fix the issue.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a docker image to execute a python proces which calls (with rpy2) the package drc from R.

I'm using a amazonlinux docker image and to use drc I have de following lines to install it via conda:

RUN conda install -c r rpy2=2.9.4 --yes
RUN conda install -c conda-forge r-drc=3.0_1 --yes

With the image build I enter into a running container with:

docker run -it --entrypoint bash mydockerName

And when I enter to R via R it throws me the next error:

Error: package or namespace load failed for 'utils':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
Error: package or namespace load failed for 'stats':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
During startup - Warning messages:
1: package 'utils' in options("defaultPackages") was not found
2: package 'stats' in options("defaultPackages") was not found

I've been googling the last days and I'm out of possible solutions...

Many thanks!

Xevi


问:
How to show markers in Google map, latitude and lng obtained from XML URL after parsing
I had done sax XML parsing and now I want to display that lat and lng on map using marker. I am able to display one static marker. I mean I pass lat and lng value to geo point, but how to display all points which is obtained from XML parsing?

This question is very important to me but I am unable to do it during the last two days. I am new in Android and Java, so please help me.

```<code>public class XMLparsingExample extends MapActivity {
    String name;
    private String array_latitude[];
    private String array_longitude[];
    SitesList sitesList = null;
    private MapController mapController;
    private MapView mapView;
    private LocationManager locationManager;
    String value1;
    String value2;
    GeoPoint p;

    class MapOverlay extends com.google.android.maps.Overlay {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);
            // ---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);
            // ---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
            return true;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            /** Send URL to parse XML Tags */
            URL sourceUrl = new URL("http://site4demo.com/artealdiaonline/output.php?lat=-34.6394879&lng=-58.3617837kkj");
            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        /** Get result from MyXMLHandler SitlesList Object */
        sitesList = MyXMLHandler.sitesList;
        ArrayList<Integer> Latitude = new ArrayList<Integer>();
        ArrayList<Integer> Longtitude = new ArrayList<Integer>();
        RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        // mapView.setStreetView(true);
        mapView.setSatellite(true);
        mapController = mapView.getController();
        mapController.setZoom(14);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
        /*
         * how to pass here latitude and longitude getting after xml parsing for
         * displaying all lat and long in map
         */
        p = new GeoPoint((int) (32.864 * 1E6), (int) (-117.2353 * 1E6));
        mapController.animateTo(p);
        mapController.setZoom(17);
        // ---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);
        mapView.invalidate();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    public class GeoUpdateHandler implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude() * 1E6);
            int lng = (int) (location.getLongitude() * 1E6);
            GeoPoint point = new GeoPoint(lat, lng);
            mapController.animateTo(point); // mapController.setCenter(point);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
}
</code>```

siteslist.java:

```<code>public class SitesList {
    /** Variables */
    private ArrayList<String> Latitude = new ArrayList<String>();
    private ArrayList<String> Longitude = new ArrayList<String>();

    /**
     * In Setter method default it will return arraylist change that to add
     */
    public ArrayList<String> getLatitude() {
        return Latitude;
    }

    public void setLatitude(String latitude) {
        this.Latitude.add(latitude);
    }

    public ArrayList<String> getLongitude() {
        return Longitude;
    }

    public void setLongitude(String longitude) {
        this.Longitude.add(longitude);
    }
}
</code>```

答:
hope I don't missunderstand you, but you can add as many overlays as you want with

.getoverlays().add(geopoint);

edit:

```<code>public static ArrayList<MapRouteOverlay> postadded_overlays;
</code>```

...

```<code>String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude   lngLat[2]=height
                // src
                GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
                //mMapView01.getOverlays().add(overlayitem);
                GeoPoint gp1;
                GeoPoint gp2 = startGP;
                for(int i1=1;i1<pairs.length;i1++) {
                    lngLat = pairs[i1].split(",");
                    gp1 = gp2;
                    gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
                        postadded_overlays.add(new MapRouteOverlay(gp1,gp2,2,color));

                }`
</code>```

...

```<code>        mapOverlays.addAll(postadded_overlays);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I had done sax XML parsing and now I want to display that lat and lng on map using marker. I am able to display one static marker. I mean I pass lat and lng value to geo point, but how to display all points which is obtained from XML parsing?

This question is very important to me but I am unable to do it during the last two days. I am new in Android and Java, so please help me.

public class XMLparsingExample extends MapActivity {
    String name;
    private String array_latitude[];
    private String array_longitude[];
    SitesList sitesList = null;
    private MapController mapController;
    private MapView mapView;
    private LocationManager locationManager;
    String value1;
    String value2;
    GeoPoint p;

    class MapOverlay extends com.google.android.maps.Overlay {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);
            // ---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);
            // ---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
            return true;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            /** Send URL to parse XML Tags */
            URL sourceUrl = new URL("http://site4demo.com/artealdiaonline/output.php?lat=-34.6394879&lng=-58.3617837kkj");
            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        /** Get result from MyXMLHandler SitlesList Object */
        sitesList = MyXMLHandler.sitesList;
        ArrayList<Integer> Latitude = new ArrayList<Integer>();
        ArrayList<Integer> Longtitude = new ArrayList<Integer>();
        RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        // mapView.setStreetView(true);
        mapView.setSatellite(true);
        mapController = mapView.getController();
        mapController.setZoom(14);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
        /*
         * how to pass here latitude and longitude getting after xml parsing for
         * displaying all lat and long in map
         */
        p = new GeoPoint((int) (32.864 * 1E6), (int) (-117.2353 * 1E6));
        mapController.animateTo(p);
        mapController.setZoom(17);
        // ---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);
        mapView.invalidate();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    public class GeoUpdateHandler implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude() * 1E6);
            int lng = (int) (location.getLongitude() * 1E6);
            GeoPoint point = new GeoPoint(lat, lng);
            mapController.animateTo(point); // mapController.setCenter(point);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
}

siteslist.java:

public class SitesList {
    /** Variables */
    private ArrayList<String> Latitude = new ArrayList<String>();
    private ArrayList<String> Longitude = new ArrayList<String>();

    /**
     * In Setter method default it will return arraylist change that to add
     */
    public ArrayList<String> getLatitude() {
        return Latitude;
    }

    public void setLatitude(String latitude) {
        this.Latitude.add(latitude);
    }

    public ArrayList<String> getLongitude() {
        return Longitude;
    }

    public void setLongitude(String longitude) {
        this.Longitude.add(longitude);
    }
}

Body:
hope I don't missunderstand you, but you can add as many overlays as you want with

.getoverlays().add(geopoint);

edit:

public static ArrayList<MapRouteOverlay> postadded_overlays;

...

String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude   lngLat[2]=height
                // src
                GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
                //mMapView01.getOverlays().add(overlayitem);
                GeoPoint gp1;
                GeoPoint gp2 = startGP;
                for(int i1=1;i1<pairs.length;i1++) {
                    lngLat = pairs[i1].split(",");
                    gp1 = gp2;
                    gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
                        postadded_overlays.add(new MapRouteOverlay(gp1,gp2,2,color));

                }`

...

        mapOverlays.addAll(postadded_overlays);


问:
Is there a command to delete Webchat channel using Azure CLI
I am trying to delete webchat channel using Azure CLI but unable to find commands something similar to az bot webchat or az bot webchat show.

Please help me !
Thanks in advance.

答: There is not and no current way to remove with CLI. You might be able to use REST endpoints to delete the channel, or try calling the Azure botservice management SDK in a language of your choosing to delete the channel to do it programmatically. You can also use the GUI to remove the channel.


问:
Should GroupPrincipal supply ALL AD fileds?
VisualStudio 2019, C#, .NetCore 2.2

Something odd is happening.  I have the following code.  It works but if I put a breakpoint on the var thing = member; line I can see that member has a lot of object.member values.  Things like: EmailAddress and other AD fields.  However, in the editor if I try to use member.EmailAddress I get the message thatEmailAddress can not be resolved.

I am pretty sure that the user/pass pair for the PrincipalContext is a "privileged" account that should have access to all AD fields, if that matters.

```<code>    using (var ctx = new PrincipalContext(ContextType.Domain,
        "ad.myCompany.com",  userName:"ad-svc-account", "...")) {
        var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName,
            "CN=My Group Staff,OU=Groups - DLs,OU=My,OU=Org,DC=ad,DC=myCompany,DC=com");

        if (grp == null) {
            return StatusCode(StatusCodes.Status500InternalServerError, "Group list is empty");
        }

        foreach (var member in grp.Members) {
            var thing = member;
        }
    }
</code>```

What am I missing?

答:
When you go through the members of the group by using var member, you are iterating over the members of type Principal[1]. Principal type itself doesnt have the details that you would normally see on a GroupPrincipal[2] or perhaps a UserPrincipal[3].

Since the member of the groups could either be UserPrincipal or GroupPrincipal or other types, you will need to first figure out the type of the Principal you are working with, cast it to the correct type and then look up all the properties.

```<code>foreach(var member in grp.Members)
{
  if (member is UserPrincipal)
  {
      var memberP = member as UserPrincipal;
      memberP.<will have all the properties of UserPrincipal>;
  }
  else if (member is GroupPrincipal)
  {
      var memberG = member as GroupPrincipal;
      memberG.<will have all properties of GroupPrincipal>;
  }
  else
  {
    //handle other types (such as ComputerPrincipal) or all others.
  }
}
</code>```

[1]Principal

Initializes a new instance of the Principal class. This constructor is called by derived-class constructors to initialize the base class and is not intended to be called directly from your code

[2]GroupPrincipal

Encapsulates group accounts. Group accounts can be arbitrary collections of principal objects or accounts created for administrative purposes

[3]UserPrincipal

Encapsulates principals that are user accounts

Body:
VisualStudio 2019, C#, .NetCore 2.2

Something odd is happening.  I have the following code.  It works but if I put a breakpoint on the var thing = member; line I can see that member has a lot of object.member values.  Things like: EmailAddress and other AD fields.  However, in the editor if I try to use member.EmailAddress I get the message thatEmailAddress can not be resolved.

I am pretty sure that the user/pass pair for the PrincipalContext is a "privileged" account that should have access to all AD fields, if that matters.

    using (var ctx = new PrincipalContext(ContextType.Domain,
        "ad.myCompany.com",  userName:"ad-svc-account", "...")) {
        var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName,
            "CN=My Group Staff,OU=Groups - DLs,OU=My,OU=Org,DC=ad,DC=myCompany,DC=com");

        if (grp == null) {
            return StatusCode(StatusCodes.Status500InternalServerError, "Group list is empty");
        }

        foreach (var member in grp.Members) {
            var thing = member;
        }
    }

What am I missing?

Body:
When you go through the members of the group by using var member, you are iterating over the members of type Principal[1]. Principal type itself doesnt have the details that you would normally see on a GroupPrincipal[2] or perhaps a UserPrincipal[3].

Since the member of the groups could either be UserPrincipal or GroupPrincipal or other types, you will need to first figure out the type of the Principal you are working with, cast it to the correct type and then look up all the properties.

foreach(var member in grp.Members)
{
  if (member is UserPrincipal)
  {
      var memberP = member as UserPrincipal;
      memberP.<will have all the properties of UserPrincipal>;
  }
  else if (member is GroupPrincipal)
  {
      var memberG = member as GroupPrincipal;
      memberG.<will have all properties of GroupPrincipal>;
  }
  else
  {
    //handle other types (such as ComputerPrincipal) or all others.
  }
}

[1]Principal

Initializes a new instance of the Principal class. This constructor is called by derived-class constructors to initialize the base class and is not intended to be called directly from your code

[2]GroupPrincipal

Encapsulates group accounts. Group accounts can be arbitrary collections of principal objects or accounts created for administrative purposes

[3]UserPrincipal

Encapsulates principals that are user accounts


问:
Error: unhashable type: 'dict' with @dataclass
I have a class Table:

@dataclass(frozen=True, eq=True)
class Table:
    name: str
    signature: Dict[str, Type[DBType]]
    prinmary_key: str
    foreign_keys: Dict[str, Type[ForeignKey]]
    indexed: List[str]
```

<p>And need to create such dictionary:</p>

<pre class="lang-py prettyprint-override"><code>
table = Table(*args)
{table: 'id'}
</code>```

TypeError: unhashable type: 'dict'

Don't understand what's the problem.

答:
The autogenerated hash method isn't safe, since it tries to hash the unhashable attributes signature, primary_key, and indexed. You need to define your own __hash__ method that ignores those attributes. One possibility is

```<code>def __hash__(self):
    return hash((self.name, self.primary_key))
</code>```

Both self.name and self.primary_key are immutable, so a tuple containing those values is also immutable and thus hashable.

An alternative to defining this method explicitly would be to use the field function to turn off the mutable fields for hashing purposes.

```<code>@dataclass(frozen=True, eq=True)
class Table:
    name: str
    signature: Dict[str, Type[DBType]] = field(compare=False)
    prinmary_key: str
    foreign_keys: Dict[str, Type[ForeignKey]] = field(compare=False)
    indexed: List[str] = field(compare=False)
</code>```

field has a hash parameter whose default value is the value of compare, and the documentation discourages using a different value for hash. (Probably to ensure that equal items hash identically.) It's unlikely that you really want to use these three fields for the purposes of comparing two tables, so you this should be OK.

I would consult the documentation rather than relying on my relatively uninformed summary of it.

Body:
I have a class Table:

@dataclass(frozen=True, eq=True)
class Table:
    name: str
    signature: Dict[str, Type[DBType]]
    prinmary_key: str
    foreign_keys: Dict[str, Type[ForeignKey]]
    indexed: List[str]

And need to create such dictionary:

table = Table(*args)
{table: 'id'}

TypeError: unhashable type: 'dict'

Don't understand what's the problem.

Body:
The autogenerated hash method isn't safe, since it tries to hash the unhashable attributes signature, primary_key, and indexed. You need to define your own __hash__ method that ignores those attributes. One possibility is

def __hash__(self):
    return hash((self.name, self.primary_key))

Both self.name and self.primary_key are immutable, so a tuple containing those values is also immutable and thus hashable.

An alternative to defining this method explicitly would be to use the field function to turn off the mutable fields for hashing purposes.

@dataclass(frozen=True, eq=True)
class Table:
    name: str
    signature: Dict[str, Type[DBType]] = field(compare=False)
    prinmary_key: str
    foreign_keys: Dict[str, Type[ForeignKey]] = field(compare=False)
    indexed: List[str] = field(compare=False)

field has a hash parameter whose default value is the value of compare, and the documentation discourages using a different value for hash. (Probably to ensure that equal items hash identically.) It's unlikely that you really want to use these three fields for the purposes of comparing two tables, so you this should be OK.

I would consult the documentation rather than relying on my relatively uninformed summary of it.


问:
Azure: Routing between subnets
I have the following situation:

```<code>ASE subnet:
192.168.0.0/24

AKS subnet:
192.168.1.0/24
</code>```

Both subnets are placed inside virtual network 192.168.0.0/8.

I'm using external ASE, and wanted to route traffic between subnets somehow. In my case:

Function app uses internal service which is placed inside AKS, and need to provide internal access from ASE subnet to this services somehow. I tried to add routing table, but not sure how to properly configure it.

答:
From Microsoft documentation:

Azure routes traffic between all subnets within a virtual network, by default. You can create your own routes to override Azure's default routing.

https://learn.microsoft.com/en-us/azure/virtual-network/tutorial-create-route-table-portal

App Service Environment (ASE), by its nature, is private. Your applications all end up with "app.asename.appserviceenvironment.net".

Apps running on AKS can call any apps on the ASE using the following name: appname.asename.appserviceenvironment.net (assuming they all have the permissions, which is a question by itself).

Title: Azure: Routing between subnets

Body:
I have the following situation:

ASE subnet:
192.168.0.0/24

AKS subnet:
192.168.1.0/24

Both subnets are placed inside virtual network 192.168.0.0/8.

I'm using external ASE, and wanted to route traffic between subnets somehow. In my case:

Function app uses internal service which is placed inside AKS, and need to provide internal access from ASE subnet to this services somehow. I tried to add routing table, but not sure how to properly configure it.


问:
Include all pages in tampermonkey(userscript)
I have to include all sites in tampermonkey..this is the script that i have to run

```<code>// ==UserScript==
// @name       Phishing Blockz
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description Phishing block based on hyperlinks
// @match      http://*/*
// @run-at     document-end

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.status;
var locheader=req.getResponseHeader("Location");
alert(headers);
alert(locheader);
</code>```

Have I done something wrong.please help me to run this userscript in all pages in chrome

答:
Doing @include instead of @match works quite nicely

```<code>// ==UserScript==
// @name       Phishing Blockz
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description Phishing block based on hyperlinks
// @include     *
// @run-at     document-end
</code>```

this works on all websites across the web (tested in TamperMonkey)

Body:
I have to include all sites in tampermonkey..this is the script that i have to run

// ==UserScript==
// @name       Phishing Blockz
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description Phishing block based on hyperlinks
// @match      http://*/*
// @run-at     document-end

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.status;
var locheader=req.getResponseHeader("Location");
alert(headers);
alert(locheader);

Have I done something wrong.please help me to run this userscript in all pages in chrome

Body:
Doing @include instead of @match works quite nicely

// ==UserScript==
// @name       Phishing Blockz
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description Phishing block based on hyperlinks
// @include     *
// @run-at     document-end

this works on all websites across the web (tested in TamperMonkey)


问:
How I can display user profile picture on view laravel
Im having trouble when I try to display the user profile picture from logged user, I have my view called DayRequest, but I can't make Laravel to show the user profile image, the image is stored in a different computer with the IP 10.57.2.98 I have the image address stored in a SQL Server Column, called Fotografia, and fotografia field has \10.57.2.98\Fotos_Empleados\userid.jpg

I tried

and

and my output shows 10.57.6.94\Fotos_Empleados\10044.jpg It doesn't show anything, please help thanks

答: Your server shows nothing even in browser, so this is not laravel syntax issue, check your images server to send valid response.</p>


问:
org.webjars in SpringBoot app
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

I also have this property defined in my application.properties

```<code>server.contextPath=/appContext
</code>```

I have this dependencies

```<code><dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui</artifactId>
            <version>1.12.1</version>
        </dependency>
</code>```

in the template:

```<code><script th:src="@{/webjars/jquery/3.2.0/jquery.min.js}"></script>
<script th:src="@{/webjars/jquery/1.12.1/jquery-ui.js}"></script>
</code>```

But I got a 404 accessing to http://localhost:8080/appContext/webjars/jquery/1.12.1/jquery-ui.js

and I try to find the resource in Eclipse using Open Resource.... but I couldn't find it either.

答:
Working on thymeleaf and webjars, following works for me</p>

```<code><script type="text/javascript" th:src="@{/webjars/jquery-ui/1.12.1/jquery-ui.js}"></script>
</code>```

Title: org.webjars in SpringBoot app

Body:
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

I also have this property defined in my application.properties

server.contextPath=/appContext

I have this dependencies

<dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui</artifactId>
            <version>1.12.1</version>
        </dependency>

in the template:

But I got a 404 accessing to http://localhost:8080/appContext/webjars/jquery/1.12.1/jquery-ui.js

and I try to find the resource in Eclipse using Open Resource.... but I couldn't find it either.

Body:
Working on thymeleaf and webjars, following works for me

<script type="text/javascript" th:src="@{/webjars/jquery-ui/1.12.1/jquery-ui.js}"></script>


问:
link in WP not going to the right page
I'm working with WP on different subdomains, and for some reason a link on the landing page isn't going to the subdomain, but rather it's trying to go to a page that doesn't exist on the main domain level. I'm guessing this is some kind of auto direct issue, but the link is correct and I'm not sure what is causing this.

The main domain is in  staging status: staging2.definingstudios.com.  There are three links there, Lifestyle, Schools, and Commercial. The linnk to schools had been doing this too, but then it stopped and is working properly, but the Lifestyle one is trying to go elsewhere.

Thoughts?

Thanks,
Christine

答:
This isn't a WP issue but generally an issue with the theme. They tend to save this data in the DB. A lot of the time its serialized and doesn't get updated.

You can do a few things. Search the DB and see if you can find it. Use a plugin to do it or 95% of the time just go into that page and update/save and it generally fixes it.

Title: link in WP not going to the right page


问:
How to Enable Docker layer caching in Azure DevOps
I am running the below yaml script to build docker images and push into kubernetes cluster but at the same time I wanted to enable docker layer caching in the azure DevOps while building the yaml script.Could you please explain how to enable or how to add the task in azure devops to do this.

Yaml:

# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  tag: 'web'
  DockerImageName: 'boiyaa/google-cloud-sdk-nodejs'

steps:
- task: Docker@2
  inputs:
    command: 'build'
    Dockerfile: '**/Dockerfile'
    tags: 'web'

- script: |
    echo ${GCLOUD_SERVICE_KEY_STAGING} > ${HOME}/gcp-key.json
               gcloud auth activate-service-account --key-file ${HOME}/gcp-key.json --project ${GCLOUD_PROJECT_ID_STAGING}
               gcloud container clusters get-credentials ${GCLOUD_PROJECT_CLUSTER_ID_STAGING} \
        --zone ${GCLOUD_PROJECT_CLUSTER_ZONE_STAGING} \
        --project ${GCLOUD_PROJECT_ID_STAGING}
  displayName: 'Setup-staging_credentials'

- bash: bash ./deploy/deploy-all.sh staging
  displayName: 'Deploy_script_staging'
```

答:
Edit: as pointed out in the comments, this feature is actually available without BuildKit. There's an example here on how to use a Docker image as the cache source during a build.

By adding the variable DOCKER_BUILDKIT: 1 (see this link) to the pipeline job and installing buildx, I managed to achieve layer caching by storing the cache as a separate image. See this link for some basics

Here's an example step in Azure DevOps

```<code>- script: |
    image="myreg.azurecr.io/myimage"
    tag=$(Build.SourceBranchName)-$(Build.SourceVersion)
    cache_tag=cache-$(Build.SourceBranchName)

    docker buildx create --use
    docker buildx build \
      -t "${image}:${tag}"
      --cache-from=type=registry,ref=${image}:${cache_tag}\
      --cache-to=type=registry,ref=${image}:${cache_tag},mode=max \
      --push \
      --progress=plain \
      .
  displayName: Build & push image using remote BuildKit layer cache
</code>```

This of course will require each run to download the image cache, but for images that have long-running installation steps in the Docker build process this is definitely faster (in our case from about 8 minutes to 2).

Body:
Edit: as pointed out in the comments, this feature is actually available without BuildKit. There's an example here on how to use a Docker image as the cache source during a build.

By adding the variable DOCKER_BUILDKIT: 1 (see this link) to the pipeline job and installing buildx, I managed to achieve layer caching by storing the cache as a separate image. See this link for some basics

Here's an example step in Azure DevOps

- script: |
    image="myreg.azurecr.io/myimage"
    tag=$(Build.SourceBranchName)-$(Build.SourceVersion)
    cache_tag=cache-$(Build.SourceBranchName)

    docker buildx create --use
    docker buildx build \
      -t "${image}:${tag}"
      --cache-from=type=registry,ref=${image}:${cache_tag}\
      --cache-to=type=registry,ref=${image}:${cache_tag},mode=max \
      --push \
      --progress=plain \
      .
  displayName: Build & push image using remote BuildKit layer cache

This of course will require each run to download the image cache, but for images that have long-running installation steps in the Docker build process this is definitely faster (in our case from about 8 minutes to 2).


问:
Unable to bind LINQ to gridview
I just using a simple LINQ query having group by clause and trying to bind its result set to GridView.
My LINQ query looks like

```<code>var expData = from c in WebDB.TransTable
              group c by c.enterdate into g
              select g;
</code>```

Grid view on ASP.NET page

```<code><asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />
</code>```

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?

None of the answers were helpful

答:
EDIT This ignores the "" in your linq statement

Look at the attribute on your asp.net GridView(aspx code): DataKeyField="" is pointing to a column name that does not exist in your linq query

```<code><asp:GridView AutoGenerateColumns="true" DataKeyField="Key"/>
</code>```

Title: Unable to bind LINQ to gridview

Body:
I just using a simple LINQ query having group by clause and trying to bind its result set to GridView.
My LINQ query looks like

var expData = from c in WebDB.TransTable
              group c by c.enterdate into g
              select g;

Grid view on ASP.NET page

<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?

None of the answers were helpful

Body:
EDIT This ignores the "" in your linq statement

Look at the attribute on your asp.net GridView(aspx code): DataKeyField="" is pointing to a column name that does not exist in your linq query

<asp:GridView AutoGenerateColumns="true" DataKeyField="Key"/>


问:
How can I pass dynamically generated CSS to Sass?
I have a chunk of dynamically generated CSS I'd like to include in a Sass stylesheet being rendered via sass.renderSync. How can I provide the CSS to Sass in such a way that it is then emitted in the output? Due to how Sass is being called, I can't write any modifications to disk, so I'm unable to add the CSS to the main Sass file or emit a new Sass file to be included.

Here's a simplified example of what I'm trying to do:

app.js

const css = ".main { font-family: sans-serif; }";
const generatedCss = sass.renderSync({ file: "styles/index.scss" });
```

<p><em>styles/index.scss</em></p>

```body { margin: 0; }
// I want to include `css` here
```

答:
you could append the dynamic css to the file that your passing in before doing sass.renderSync

const fs = require('fs')
const sass = require('node-sass')

const css = '.main { font-family: sans-serif; }'
fs.appendFile('styles/index.scss', css, (err) => {
  if (err) throw err
  const generatedCss = sass.renderSync({ file: "styles/index.scss" });
})
```

Body:
I have a chunk of dynamically generated CSS I'd like to include in a Sass stylesheet being rendered via sass.renderSync. How can I provide the CSS to Sass in such a way that it is then emitted in the output? Due to how Sass is being called, I can't write any modifications to disk, so I'm unable to add the CSS to the main Sass file or emit a new Sass file to be included.

Here's a simplified example of what I'm trying to do:

app.js

const css = ".main { font-family: sans-serif; }";
const generatedCss = sass.renderSync({ file: "styles/index.scss" });

styles/index.scss

body { margin: 0; }
// I want to include `css` here


问:
Execute newtork code with app in background
I have this scenario in my app:

I have to execute 2 block of code repeatedly for N times.

in the first block I have to do a network call with Alamofire (I call a HTTP service).
this call returns data and in this data there is a image path that I have to download on device

in the second block I have to download the image and then save it on device

After this start over again for N times.

My problem is that the user can have app in background and I would to like that this process continues when app is in background too.

For this reason, after the Alamofire call, I insert this code for download image:

```<code>let config = URLSessionConfiguration.background(withIdentifier: "XXXXXX.XXXX")
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
let url = URL(string: "testurl")
let task = session.downloadTask(with: url!)
task.resume()

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

    //save image on device and I recall Alamofire for the next call
}
</code>```

My problem is this: this process doesent execute when app goes in background.
What I'm wrong?

答:
You need to implement the below delegate,

```<code>func application(_ application: UIApplication,
             handleEventsForBackgroundURLSession identifier: String,
             completionHandler: @escaping () -> Void) {
    // send the completion handler as background completion handler
}
</code>```

Please refer the below answer for more information:
https://stackoverflow.com/a/44140059/1244403

Body:
I have this scenario in my app:

I have to execute 2 block of code repeatedly for N times.

in the first block I have to do a network call with Alamofire (I call a HTTP service).
this call returns data and in this data there is a image path that I have to download on device

in the second block I have to download the image and then save it on device

After this start over again for N times.

My problem is that the user can have app in background and I would to like that this process continues when app is in background too.

For this reason, after the Alamofire call, I insert this code for download image:

let config = URLSessionConfiguration.background(withIdentifier: "XXXXXX.XXXX")
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
let url = URL(string: "testurl")
let task = session.downloadTask(with: url!)
task.resume()

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

    //save image on device and I recall Alamofire for the next call
}

My problem is this: this process doesent execute when app goes in background.
What I'm wrong?

Body:
You need to implement the below delegate,

func application(_ application: UIApplication,
             handleEventsForBackgroundURLSession identifier: String,
             completionHandler: @escaping () -> Void) {
    // send the completion handler as background completion handler
}

Please refer the below answer for more information:
https://stackoverflow.com/a/44140059/1244403


问:
Pytest - How to mock or patch global variables
I have following file and i am running pytests on this file. One of the use case is to test the logger function which is global.  How can we mock this in my pytest ?</p>

```<code>import spark_fn

def run_job(params):
    do_something()
    logger.info("some info")

def main(params):
    global logger
    app_name = "test app"
    spark, logger = spark_fn(app_name)
    run_job(params)

if __name__ == "__main__":
    params = "some params"
    main(params)

===============================================================
</code>```

答:
How's something like this? You should think of it less like a global variable and more like patching what spark_fn is returning to have a "fake" logger class. Also I'm curious how you're using the spark_fn module overall with how you're importing it.

import yoursampletest

def test_monkeytest(monkeypatch):
    """
        Monkey patches a fake logger into spark_fn
    """
    class myFakeLogger:

        def info(self, value):
            return value

    def mock_info(mylogstatement):
        return 1, myFakeLogger()

    monkeypatch.setattr(yoursampletest, 'spark_fn', mock_info)

    assert yoursampletest.main(1) == 'some info'
```

Body:
I have following file and i am running pytests on this file. One of the use case is to test the logger function which is global.  How can we mock this in my pytest ?

import spark_fn

def run_job(params):
    do_something()
    logger.info("some info")

def main(params):
    global logger
    app_name = "test app"
    spark, logger = spark_fn(app_name)
    run_job(params)

if __name__ == "__main__":
    params = "some params"
    main(params)

===============================================================


问:
Find user with role (list of roles) who has exactly these roles from list and no other
Description of problem;

I have model of user with set of Roles (many to many relacion).
I would like to pick from database (MySQL) user who have exactly this roles which i askin (no more no less).

This is my query (doesn't work properly) if i looking for users with roles Admin and User:

```<code>select * from login.user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in ('ROLE_ADMIN', 'ROLE_USER')
</code>```

Equivalent from Hibernate (NativeQuerty);

```<code>select * from user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in (:roles)
</code>```

This query return users who have roles Admin or User.
I am after Admin and User in this case.

If ask user with Admin role I would like have users who have only Admin roles.

答:
Well you are basically saying "give me any user who has either 'ROLE_ADMIN' or 'ROLE_USER' or both" in your query. If you specify only the role you are interested in you will get the results necessary.

This returns only admins for example:

```<code>select * from login.user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in ('ROLE_ADMIN')
</code>```

Body:
Description of problem;

I have model of user with set of Roles (many to many relacion).
I would like to pick from database (MySQL) user who have exactly this roles which i askin (no more no less).

This is my query (doesn't work properly) if i looking for users with roles Admin and User:

select * from login.user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in ('ROLE_ADMIN', 'ROLE_USER')

Equivalent from Hibernate (NativeQuerty);

select * from user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in (:roles)

This query return users who have roles Admin or User.
I am after Admin and User in this case.

If ask user with Admin role I would like have users who have only Admin roles.

Body:
Well you are basically saying "give me any user who has either 'ROLE_ADMIN' or 'ROLE_USER' or both" in your query. If you specify only the role you are interested in you will get the results necessary.

This returns only admins for example:

select * from login.user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.id where r.name in ('ROLE_ADMIN')


问:
Help with Windows Visa / 7 UAC file system virtualisation
I am working on a program that is designed to operate in conjunction with an old C++ application.  A game called Age of Wonders.  When running under Windows Vista or Windows 7 (with the UAC enabled) the game save files are written to the virtualisation path instead of the real path.

So for example;

Original:
C:\Program Files (x86)\Age of Wonders\Save

Virtualized:
C:\Users\UserName\AppData\Local\VirtualStore\Program Files (x86)\Age of Wonders\Save

In my .Net application I download files from an email server and place them in the Save folder, if I try to write to the original path I receive an Unauthorised Access Exception when the UAC is enabled.  Windows doesn’t automatically convert it to the Virtualised path for me.  I’ve been working around this by getting my users to run the application as administrator.  However I would like to make a more elegant solution.

I could write some code to handle the exception and write to the virtualised path in my code, but I think a better solution would be to somehow switch my program into a mode so that this is done by Windows itself and not in my code.  This I feel would be a better long term solution for future versions of Windows.

I have spent time searching on the internet and I have found other people who are talking about this, but no one provides any help which is actually usable.  Here are the links I have looked at;

Should I use a VirtualStore solution on Vista?

Create Process with FS Virtualization Enabled

http://us.generation-nt.com/answer/using-settokeninformation-control-file-system-virtualization-vista-help-37057472.html

I need to solution to not involve the user having to modify their system settings or create any accounts to run the process under etc.

So, below I have the code for a simple Windows Forms app.  It has one button and one check box, the check box is intended to switch the virtualisation mode and the button writes a small text file to the a Program Files folder.  I want to be able to use this to test the virtualisation behaviour.  So I would expect the File.txt to be written to the virtualised path when the check box is checked etc.

If anyone can help me fill in the blank function I would be extremely grateful.  Thanks in advance.

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string testText = "Dave was here";
            File.WriteAllText("C:\\Program Files\\DaveTest\\File.txt", testText);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        SetVirtualization(checkBox1.Checked);
    }

    private void SetVirtualization(bool enabled)
    {
        //What code do I need here, please provide examples than can be used
    }
}
</code>```

答:
FYI all, I have come up with this - which does do what I wanted;</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace VirtualizationTest
{
    public class FileVirtualizationHelper
    {
        #region Win32 API routines

        enum TOKEN_INFORMATION_CLASS
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin,
            MaxTokenInfoClass  // MaxTokenInfoClass should always be the last enum
        }

        const UInt32 MAXIMUM_ALLOWED = 0x2000000;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern Boolean CloseHandle(IntPtr hSnapshot);

        [DllImport("advapi32", SetLastError = true), System.Security.SuppressUnmanagedCodeSecurityAttribute]
        static extern Boolean OpenProcessToken(IntPtr ProcessHandle, // handle to process
                                            UInt32 DesiredAccess, // desired access to process
                                            ref IntPtr TokenHandle); // handle to open access token

        [DllImport("advapi32.dll", SetLastError = true)]
        static extern Boolean SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref UInt32 TokenInformation, UInt32 TokenInformationLength);

        #endregion

        #region Public Methods

        public static bool Enable()
        {
            return SetVirtualization(true);
        }

        public static bool Disable()
        {
            return SetVirtualization(false);
        }

        #endregion

        #region Private Methods

        private static bool SetVirtualization(bool DoEnable)
        {
            IntPtr Token = (IntPtr)0;
            UInt32 EnableValue = DoEnable ? (UInt32)1 : (UInt32)0;
            UInt32 EnableValueSize = sizeof(UInt32);

            if (!OpenProcessToken(Process.GetCurrentProcess().Handle, MAXIMUM_ALLOWED, ref Token))
            {
                return false;
            }
            if (!SetTokenInformation(Token, (TOKEN_INFORMATION_CLASS)24, ref EnableValue, EnableValueSize))
            {
                CloseHandle(Token);
                return false;
            }
            CloseHandle(Token);
            return true;
        }

        #endregion
    }
}
</code>```

Body:
I am working on a program that is designed to operate in conjunction with an old C++ application.  A game called Age of Wonders.  When running under Windows Vista or Windows 7 (with the UAC enabled) the game save files are written to the virtualisation path instead of the real path.

So for example;

Original:
C:\Program Files (x86)\Age of Wonders\Save

Virtualized:
C:\Users\UserName\AppData\Local\VirtualStore\Program Files (x86)\Age of Wonders\Save

In my .Net application I download files from an email server and place them in the Save folder, if I try to write to the original path I receive an Unauthorised Access Exception when the UAC is enabled.  Windows doesn’t automatically convert it to the Virtualised path for me.  I’ve been working around this by getting my users to run the application as administrator.  However I would like to make a more elegant solution.

I could write some code to handle the exception and write to the virtualised path in my code, but I think a better solution would be to somehow switch my program into a mode so that this is done by Windows itself and not in my code.  This I feel would be a better long term solution for future versions of Windows.

I have spent time searching on the internet and I have found other people who are talking about this, but no one provides any help which is actually usable.  Here are the links I have looked at;

Should I use a VirtualStore solution on Vista?

Create Process with FS Virtualization Enabled

http://us.generation-nt.com/answer/using-settokeninformation-control-file-system-virtualization-vista-help-37057472.html

I need to solution to not involve the user having to modify their system settings or create any accounts to run the process under etc.

So, below I have the code for a simple Windows Forms app.  It has one button and one check box, the check box is intended to switch the virtualisation mode and the button writes a small text file to the a Program Files folder.  I want to be able to use this to test the virtualisation behaviour.  So I would expect the File.txt to be written to the virtualised path when the check box is checked etc.

If anyone can help me fill in the blank function I would be extremely grateful.  Thanks in advance.

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string testText = "Dave was here";
            File.WriteAllText("C:\\Program Files\\DaveTest\\File.txt", testText);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        SetVirtualization(checkBox1.Checked);
    }

    private void SetVirtualization(bool enabled)
    {
        //What code do I need here, please provide examples than can be used
    }
}

Body:
FYI all, I have come up with this - which does do what I wanted;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace VirtualizationTest
{
    public class FileVirtualizationHelper
    {
        #region Win32 API routines

        enum TOKEN_INFORMATION_CLASS
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin,
            MaxTokenInfoClass  // MaxTokenInfoClass should always be the last enum
        }

        const UInt32 MAXIMUM_ALLOWED = 0x2000000;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern Boolean CloseHandle(IntPtr hSnapshot);

        [DllImport("advapi32", SetLastError = true), System.Security.SuppressUnmanagedCodeSecurityAttribute]
        static extern Boolean OpenProcessToken(IntPtr ProcessHandle, // handle to process
                                            UInt32 DesiredAccess, // desired access to process
                                            ref IntPtr TokenHandle); // handle to open access token

        [DllImport("advapi32.dll", SetLastError = true)]
        static extern Boolean SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref UInt32 TokenInformation, UInt32 TokenInformationLength);

        #endregion

        #region Public Methods

        public static bool Enable()
        {
            return SetVirtualization(true);
        }

        public static bool Disable()
        {
            return SetVirtualization(false);
        }

        #endregion

        #region Private Methods

        private static bool SetVirtualization(bool DoEnable)
        {
            IntPtr Token = (IntPtr)0;
            UInt32 EnableValue = DoEnable ? (UInt32)1 : (UInt32)0;
            UInt32 EnableValueSize = sizeof(UInt32);

            if (!OpenProcessToken(Process.GetCurrentProcess().Handle, MAXIMUM_ALLOWED, ref Token))
            {
                return false;
            }
            if (!SetTokenInformation(Token, (TOKEN_INFORMATION_CLASS)24, ref EnableValue, EnableValueSize))
            {
                CloseHandle(Token);
                return false;
            }
            CloseHandle(Token);
            return true;
        }

        #endregion
    }
}


问:
D3,js path data string - should I parse it or there is an API for it?
learning D3 now and I have a use case where I have the following code:

```<code>let length = (3 + ((15000000 / 1500) % 8)) | 0;
let polygon = d3
      .radialLine()
      .angle((_, i) => (i / length) * 2 * Math.PI)
      .curve(d3.curveCardinalClosed)
      .radius(() => 150);
let path = polygon({ length });
</code>```

So the 'path' variable does give me the "d" attribute as a string.

Now for the implementation, I have in mind I need the same path data in more of a "parseable" format.

Question - surely I can just parse the string right away (there are many parsers out there to turn d path string to an array etc), but I am just wondering if there is d3 embedded method for that? so that I do not have to use additional parser?

答:
I don’t think there’s one built into d3 but if there is I’d love to hear about it!

You could use this npm package:

https://www.npmjs.com/package/svg-path-parser

Or the browser’s built in path.getPathData() New API (which replaces the old path.pathSegList)

Sadly not implemented in all browsers yet so we can use a polyFill for now and hopefully it will be broadly supported soon.

Example:

const route = document.querySelector('#route');
console.log(route.getPathData()); //.pathSegList(); .getPathData();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 500 500">
    <path stroke="grey" fill="none" id="route" d="M50,25 75,55 Q75,75 35,75 z" />
</svg>
<script src="https://cdn.jsdelivr.net/npm/path-data-polyfill@1.0.3/path-data-polyfill.min.js"></script></code>```

Body:
learning D3 now and I have a use case where I have the following code:

let length = (3 + ((15000000 / 1500) % 8)) | 0;
let polygon = d3
      .radialLine()
      .angle((_, i) => (i / length) * 2 * Math.PI)
      .curve(d3.curveCardinalClosed)
      .radius(() => 150);
let path = polygon({ length });

So the 'path' variable does give me the "d" attribute as a string.

Now for the implementation, I have in mind I need the same path data in more of a "parseable" format.

Question - surely I can just parse the string right away (there are many parsers out there to turn d path string to an array etc), but I am just wondering if there is d3 embedded method for that? so that I do not have to use additional parser?

Body:
I don’t think there’s one built into d3 but if there is I’d love to hear about it!

You could use this npm package:

https://www.npmjs.com/package/svg-path-parser

Or the browser’s built in path.getPathData() New API (which replaces the old path.pathSegList)

Sadly not implemented in all browsers yet so we can use a polyFill for now and hopefully it will be broadly supported soon.

Example:

const route = document.querySelector('#route');
console.log(route.getPathData()); //.pathSegList(); .getPathData();

<svg viewBox="0 0 500 500">
    <path stroke="grey" fill="none" id="route" d="M50,25 75,55 Q75,75 35,75 z" />
</svg>
<script src="https://cdn.jsdelivr.net/npm/path-data-polyfill@1.0.3/path-data-polyfill.min.js"></script>


问:
User Defined Function in SQL
I am trying to write a UDF similar to this but it keeps failing the syntax. I keep getting an error near concat.

```<code>CREATE FUNCTION ParseUserAgentString (@user_agent VARCHAR(200))
RETURNS VARCHAR(400)
RETURN CONCAT( user_agent LIKE "%Chrome%",
    " ",
    user_agent LIKE "%Firefox%",
    " ",
    user_agent LIKE "%Mozilla%",
    " ",
    user_agent LIKE "%MSIE%",
    " ",
    user_agent LIKE "%Opera%",
    " ",
    user_agent LIKE "%Safari%"
    );
</code>```

I get the following error on execution.

```<code>[SQL: CREATE FUNCTION ParseUserAgentString (user_agent VARCHAR(200))
 RETURNS VARCHAR(200)
 RETURN CONCAT_WS(" ",
     user_agent LIKE "%Chrome%",
     user_agent LIKE "%Firefox%",
     user_agent LIKE "%Mozilla%",
     user_agent LIKE "%MSIE%",
     user_agent LIKE "%Opera%",
     user_agent LIKE "%Safari%"
     );]
(Background on this error at: http://sqlalche.me/e/e3q8)```

  [1]: https://i.stack.imgur.com/biGrF.png
```

答:
You can't use a session variable as a function parameter, @user_agent should be just user_agent.

The VARCHAR datatype requires a length.

```<code>CREATE FUNCTION ParseUserAgentString (user_agent VARCHAR(200))
RETURNS VARCHAR(200)
RETURN CONCAT_WS(" ",
    user_agent LIKE "%Chrome%",
    user_agent LIKE "%Firefox%",
    user_agent LIKE "%Mozilla%",
    user_agent LIKE "%MSIE%",
    user_agent LIKE "%Opera%",
    user_agent LIKE "%Safari%"
    );
</code>```

Title: User Defined Function in SQL

Body:
I am trying to write a UDF similar to this but it keeps failing the syntax. I keep getting an error near concat.

CREATE FUNCTION ParseUserAgentString (@user_agent VARCHAR(200))
RETURNS VARCHAR(400)
RETURN CONCAT( user_agent LIKE "%Chrome%",
    " ",
    user_agent LIKE "%Firefox%",
    " ",
    user_agent LIKE "%Mozilla%",
    " ",
    user_agent LIKE "%MSIE%",
    " ",
    user_agent LIKE "%Opera%",
    " ",
    user_agent LIKE "%Safari%"
    );

I get the following error on execution.

[SQL: CREATE FUNCTION ParseUserAgentString (user_agent VARCHAR(200))
 RETURNS VARCHAR(200)
 RETURN CONCAT_WS(" ",
     user_agent LIKE "%Chrome%",
     user_agent LIKE "%Firefox%",
     user_agent LIKE "%Mozilla%",
     user_agent LIKE "%MSIE%",
     user_agent LIKE "%Opera%",
     user_agent LIKE "%Safari%"
     );]
(Background on this error at: http://sqlalche.me/e/e3q8)```

  [1]: https://i.stack.imgur.com/biGrF.png

Body:
You can't use a session variable as a function parameter, @user_agent should be just user_agent.

The VARCHAR datatype requires a length.

CREATE FUNCTION ParseUserAgentString (user_agent VARCHAR(200))
RETURNS VARCHAR(200)
RETURN CONCAT_WS(" ",
    user_agent LIKE "%Chrome%",
    user_agent LIKE "%Firefox%",
    user_agent LIKE "%Mozilla%",
    user_agent LIKE "%MSIE%",
    user_agent LIKE "%Opera%",
    user_agent LIKE "%Safari%"
    );


问:
Does react hook component re-render when parent component re-renders?
Say I have a react hook component

```<code>const Child = (props) => {
    useEffect(()=>{
        // fetch data
        ...
    });

    return (
        //Displays fetched data
    )
}
</code>```

Then it is used in the parent component

```<code>class Parent extends Component {

    render () {
        ... <Child ... /> ...
    }
}
</code>```

My question is, if Parent rerenders when its state changes (but irrelevant to Child), would it cause the Child component to rerender and ultimately fetching data again?

If Child2 has a dependency array, would it suffer the same problem?

```<code>const Child2 = (props) => {

    let [data, setData] = useState();
    useEffect(()=>{
        // fetch data
        ajax(...).then((result)=>setData(result));
    }, [data]);

    return (
        //Displays fetched data
    )
}
</code>```

答:
Yes, the standard behavior in react is that when a component renders, its children render too. To improve performance you can skip some renders with shouldComponentUpdate on a class component or React.memo on a functional component, but this is a performance optimization, not something you should rely on for skipping effects.

If you're fetching data in a component, you often only want to do it on mount, or only when certain relevant data changes. This is controlled with useEffect's dependency array. To run it only on mount, provide an empty array []. The component will still rerender when the parent component changes, but its effect will not rerun.

Body:
Say I have a react hook component

const Child = (props) => {
    useEffect(()=>{
        // fetch data
        ...
    });

    return (
        //Displays fetched data
    )
}

Then it is used in the parent component

class Parent extends Component {

    render () {
        ... <Child ... /> ...
    }
}

My question is, if Parent rerenders when its state changes (but irrelevant to Child), would it cause the Child component to rerender and ultimately fetching data again?

If Child2 has a dependency array, would it suffer the same problem?

const Child2 = (props) => {

    let [data, setData] = useState();
    useEffect(()=>{
        // fetch data
        ajax(...).then((result)=>setData(result));
    }, [data]);

    return (
        //Displays fetched data
    )
}