问:
React-table css not loading is webpack the issue?
I'm not too familiar with webpack but I think it's causing a problem.  I'm using a react boilerplate and have installed react-table as a dependancy.  Added the code and all is displaying but the css is not.  If anyone can point me in the right direction I would be very grateful!

This is how I added it to my component

```<code>import ReactTable from 'react-table';
import 'react-table/react-table.css';
</code>```

In my render, I'm doing the following

```<code>  <ReactTable
    noDataText="No data available"
    data={this.state.rows}
    columns={[
      {
        columns: this.state.columns
      }
    ]}
  getTdProps={(state, rowInfo, column, instance) => ({
    onMouseEnter: e =>
      console.log('Cell - onMouseEnter', {
        state,
        rowInfo,
        column,
        instance,
        event: e,
      }),
  })}
    defaultPageSize={10}
  className="-striped -highlight"
  />
</code>```

This is what my webpack.config.js looks like

```<code>  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,
          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,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            ['@babel/preset-stage-2', { decoratorsLegacy: true }],
            // 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: [
            // 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
          // {
          //   exclude: ['react-table/react-table.css'],
          //   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'],
    client_config: './src/appSettings.config'
  },

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

    // 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>```

UPDATE MODIFIED webpack.config

```<code> // 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,
        },
      },
      {
         loader: 'style-loader'
      },
</code>```

答:
My issue was I was not importing react-table.css with WithStyle that's why it was not working. then I used it like see example</p>

```<code>import rt from "react-table/react-table.css";

export default compose(
 withStyles(rt),
  connect(
   mapStateToProps,
   {

   },
 ),
)(ApplicationList);
</code>```

Body:
I'm not too familiar with webpack but I think it's causing a problem.  I'm using a react boilerplate and have installed react-table as a dependancy.  Added the code and all is displaying but the css is not.  If anyone can point me in the right direction I would be very grateful!

This is how I added it to my component

import ReactTable from 'react-table';
import 'react-table/react-table.css';

In my render, I'm doing the following

  <ReactTable
    noDataText="No data available"
    data={this.state.rows}
    columns={[
      {
        columns: this.state.columns
      }
    ]}
  getTdProps={(state, rowInfo, column, instance) => ({
    onMouseEnter: e =>
      console.log('Cell - onMouseEnter', {
        state,
        rowInfo,
        column,
        instance,
        event: e,
      }),
  })}
    defaultPageSize={10}
  className="-striped -highlight"
  />

This is what my webpack.config.js looks like

  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,
          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,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            ['@babel/preset-stage-2', { decoratorsLegacy: true }],
            // 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: [
            // 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
          // {
          //   exclude: ['react-table/react-table.css'],
          //   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'],
    client_config: './src/appSettings.config'
  },

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

    // 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];

UPDATE MODIFIED webpack.config

 // 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,
        },
      },
      {
         loader: 'style-loader'
      },

Body:
My issue was I was not importing react-table.css with WithStyle that's why it was not working. then I used it like see example

import rt from "react-table/react-table.css";

export default compose(
 withStyles(rt),
  connect(
   mapStateToProps,
   {

   },
 ),
)(ApplicationList);


来源: stackexchange

问:
Multiple Application_Start events firing
I am debugging an ASP.NET 2.0 application that is suffering from slow loading of the initial page.

Through adding logging, I've found that the Application_Start event fires twice on startup with a short delay between the two events. The Session_Start event also fires twice, with the same Session ID value.

e.g.

```
[Header]
2010-09-10 14:52:36.331 INFO  Web.Global.Application_Start          START
2010-09-10 14:52:37.409 INFO  Web.Global.Session_Start              Session.SessionID=xxqjvun2ce2yqsumq1hfoj45
[Header]
2010-09-10 14:53:10.028 INFO  Web.Global.Application_Start          START
2010-09-10 14:53:10.325 INFO  Web.Global.Session_Start              Session.SessionID=xxqjvun2ce2yqsumq1hfoj45
```

I am running this on my local machine, under IIS 5.1. The project also uses ASP.NET MVC and the aspx page URL being used is altered using routing, using the technique shown on Phil Haack's site.

Any suggestions about what could cause this?

答:
We eventually realised that this was down to our IIS configuration.

Some time ago a decision was made to rename the virtual directory used for this website. This was done by adding a whole new virtual directory configuration, leaving the previous one in place. Essentially we had two virtual directories pointing at the same ASP.NET app!

The migration to the new virtual directory was never completed, so parts of the website still referenced the old one. Hence two Application_Start events...

The fix was to change to setup to the old virtual directory in IIS to be A redirection to a URL with the URL set to /NewVirtualDirectory$S$Q

ContentLicense: CC BY-SA 2.5

Body:
I am debugging an ASP.NET 2.0 application that is suffering from slow loading of the initial page.

Through adding logging, I've found that the Application_Start event fires twice on startup with a short delay between the two events. The Session_Start event also fires twice, with the same Session ID value.

e.g.

[Header]
2010-09-10 14:52:36.331 INFO  Web.Global.Application_Start          START
2010-09-10 14:52:37.409 INFO  Web.Global.Session_Start              Session.SessionID=xxqjvun2ce2yqsumq1hfoj45
[Header]
2010-09-10 14:53:10.028 INFO  Web.Global.Application_Start          START
2010-09-10 14:53:10.325 INFO  Web.Global.Session_Start              Session.SessionID=xxqjvun2ce2yqsumq1hfoj45

I am running this on my local machine, under IIS 5.1. The project also uses ASP.NET MVC and the aspx page URL being used is altered using routing, using the technique shown on Phil Haack's site.

Any suggestions about what could cause this?

ContentLicense: CC BY-SA 3.0


问:
Resize cell after scrolling (Autolayout)
Resize cell size after some scrolling.

CommentViewController.swift Code

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tblView.register(UINib(nibName: "CellComment", bundle: nil), forCellReuseIdentifier: "CellComment")

    // Remove extra space from group tableview
    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tblView.tableFooterView = UIView(frame: frame)

    tblView.rowHeight = UITableView.automaticDimension
    tblView.estimatedRowHeight = 123

    tblView.estimatedSectionFooterHeight = 0.01
    tblView.separatorColor = .clear
    tblView.reloadData()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

}

// UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 15
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tblView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath) as! CellComment
    cell.selectionStyle = .none
    cell.delegate = self
    cell.imgViewUser.image = UIImage.init(named: "userImage1.jpg")
    cell.lblUserName.text = "User Name \(indexPath.row + 1)"

    if indexPath.row % 2 == 0 {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }
    else {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."

    }
    //        cell.updateConstraintsIfNeeded() //I try but not working
    //        cell.layoutIfNeeded()
    cell.layoutSubviews()
    return cell
}
</code>```

CellComment.swift

```<code>override func layoutSubviews() {
        super.layoutSubviews()
        //lblComment.preferredMaxLayoutWidth = lblComment.bounds.width
        lblComment.preferredMaxLayoutWidth = lblComment.bounds.size.width
    }
</code>```

Full Video

答:
Remove this cell.layoutSubviews() and add this protocol .

```<code> func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
</code>```

Add constraints like this.

ContentLicense: CC BY-SA 4.0

Body:
Resize cell size after some scrolling.

CommentViewController.swift Code

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tblView.register(UINib(nibName: "CellComment", bundle: nil), forCellReuseIdentifier: "CellComment")

    // Remove extra space from group tableview
    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tblView.tableFooterView = UIView(frame: frame)

    tblView.rowHeight = UITableView.automaticDimension
    tblView.estimatedRowHeight = 123

    tblView.estimatedSectionFooterHeight = 0.01
    tblView.separatorColor = .clear
    tblView.reloadData()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

}

// UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 15
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tblView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath) as! CellComment
    cell.selectionStyle = .none
    cell.delegate = self
    cell.imgViewUser.image = UIImage.init(named: "userImage1.jpg")
    cell.lblUserName.text = "User Name \(indexPath.row + 1)"

    if indexPath.row % 2 == 0 {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }
    else {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."

    }
    //        cell.updateConstraintsIfNeeded() //I try but not working
    //        cell.layoutIfNeeded()
    cell.layoutSubviews()
    return cell
}

CellComment.swift

override func layoutSubviews() {
        super.layoutSubviews()
        //lblComment.preferredMaxLayoutWidth = lblComment.bounds.width
        lblComment.preferredMaxLayoutWidth = lblComment.bounds.size.width
    }

Full Video

Body:
Remove this cell.layoutSubviews() and add this protocol .

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Add constraints like this.


问:
How to adress variable Columns of SQL query with TWIG
I am trying to address a specific column of a SQL query depending on the value of another row from the query.

The result I am getting from the SQL query is something like this:

```<code>Number | Value1 | Value2 | Value3
1      |      3 |      5 |     4
3      |      5 |      2 |     6
2      |      1 |      3 |     2
</code>```

For each row, I want to get the Value of the Column by the Index of the Number.
So for example in the first row, I want to get the Value of 'Value1', which is 3.
In the second row, I want to get the Value of 'Value3', which is 6, and so on.

Then I am iterating through the list with a TWIG for loop and can access the 'Number' parameter like this:

```<code>{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
{% endfor %}
</code>```

Unfortunately, I cannot address the 'Value'-columns using that number.

I have tried things like:

```<code>{{examplelist[key].Value . number }}
</code>```

or

```<code>{{examplelist[key].Value + number }}
</code>```

or

```<code>{{examplelist[key].Value ~ number }}
</code>```

but none of these work...

答:
this should do the trick</p>

```<code>{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
   {% set value  = examplelist[key]["Value"~number] %}
{% endfor %}
</code>```

Body:
I am trying to address a specific column of a SQL query depending on the value of another row from the query.

The result I am getting from the SQL query is something like this:

Number | Value1 | Value2 | Value3
1      |      3 |      5 |     4
3      |      5 |      2 |     6
2      |      1 |      3 |     2

For each row, I want to get the Value of the Column by the Index of the Number.
So for example in the first row, I want to get the Value of 'Value1', which is 3.
In the second row, I want to get the Value of 'Value3', which is 6, and so on.

Then I am iterating through the list with a TWIG for loop and can access the 'Number' parameter like this:

{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
{% endfor %}

Unfortunately, I cannot address the 'Value'-columns using that number.

I have tried things like:

{{examplelist[key].Value . number }}

or

{{examplelist[key].Value + number }}

or

{{examplelist[key].Value ~ number }}

but none of these work...

Body:
this should do the trick

{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
   {% set value  = examplelist[key]["Value"~number] %}
{% endfor %}


问:
How to make an exe for python script that uses weasyprint?
I wanted to make an exe file for my little project that I made. But it doesnt run at all.

I tried PyInstaller does not include dependency file
But it throws

```<code>Traceback (most recent call last):
  File "C:\Program Files\Python37\Scripts\pyinstaller-script.py", line 11, in <module>
    load_entry_point('PyInstaller==3.4', 'console_scripts', 'pyinstaller')()
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 8, in <module>
IndexError: list index out of range
</code>```

And if I just do "pyinstaller --clean --onefile Start.py" it says:

```<code>  File "Start.py", line 5, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "Modules\HTMLToPDF.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\weasyprint\__init__.py", line 20, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\cssselect2\__init__.py", line 20, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\cssselect2\compiler.py", line 7, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\tinycss2\__init__.py", line 10, in <module>
  File "pathlib.py", line 1189, in read_text
  File "pathlib.py", line 1176, in open
  File "pathlib.py", line 1030, in _opener
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Daniel\\AppData\\Local\\Temp\\_MEI100202\\tinycss2\\VERSION'
[12796] Failed to execute script Start
</code>```

How can I fix it? I just want a nice way to distribute my code.

答:
Honestly, your project is huge and has many complex libraries so PyInstaller can't handle all of them by itself. Here I tell you some tips to work it out.

First, when PyInstaller complains about missing a file, it means that you need to feed that file manually. For example in your error, it complains about missing a file named VERSION that should be exist in C:\\Users\\Daniel\\AppData\\Local\\Temp\\_MEI100202\\tinycss2 but it doesn't. You need to add it as a data file by yourself.

Second, if you need to bring some external dependencies like cairo you need to bring the whole directory of the dependence with Tree function. You can find more about that here.

I built the project and fix some of these dependencies so it no longer shows an error about missing those files, I also added a try/except on the whole project to be able to trace missing files which might be helpful.
I just added the missing files and some hiddenimports to the spec file so you need to take care of those.

Start.py:

```<code>import traceback
try:
    """
    Whole Start.py script
    """
except Exception:
    traceback.print_exc()
    while(True):
        pass
</code>```

Start.spec:

```<code># -*- mode: python -*-

block_cipher = None

a = Analysis(['Start.py'],
             pathex=['C:\\Users\\Daniel\\Desktop\\SOAPUIReportingTool-master\\soap'],
             binaries=[],
             datas=[
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\tinycss2\\VERSION", "tinycss2"),
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\cairocffi\\VERSION", "cairocffi"),
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\\weasyprint\\VERSION", ".")
                     ],
             hiddenimports=["tinycss2", "matplotlib", "weasyprint"],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='Start',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=False,
          runtime_tmpdir=None,
          console=True )
</code>```

Body:
I wanted to make an exe file for my little project that I made. But it doesnt run at all.

I tried PyInstaller does not include dependency file
But it throws

Traceback (most recent call last):
  File "C:\Program Files\Python37\Scripts\pyinstaller-script.py", line 11, in <module>
    load_entry_point('PyInstaller==3.4', 'console_scripts', 'pyinstaller')()
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 8, in <module>
IndexError: list index out of range

And if I just do "pyinstaller --clean --onefile Start.py" it says:

  File "Start.py", line 5, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "Modules\HTMLToPDF.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\weasyprint\__init__.py", line 20, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\cssselect2\__init__.py", line 20, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\cssselect2\compiler.py", line 7, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:\Program Files\Python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\tinycss2\__init__.py", line 10, in <module>
  File "pathlib.py", line 1189, in read_text
  File "pathlib.py", line 1176, in open
  File "pathlib.py", line 1030, in _opener
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Daniel\\AppData\\Local\\Temp\\_MEI100202\\tinycss2\\VERSION'
[12796] Failed to execute script Start

How can I fix it? I just want a nice way to distribute my code.

Body:
Honestly, your project is huge and has many complex libraries so PyInstaller can't handle all of them by itself. Here I tell you some tips to work it out.

First, when PyInstaller complains about missing a file, it means that you need to feed that file manually. For example in your error, it complains about missing a file named VERSION that should be exist in C:\\Users\\Daniel\\AppData\\Local\\Temp\\_MEI100202\\tinycss2 but it doesn't. You need to add it as a data file by yourself.

Second, if you need to bring some external dependencies like cairo you need to bring the whole directory of the dependence with Tree function. You can find more about that here.

I built the project and fix some of these dependencies so it no longer shows an error about missing those files, I also added a try/except on the whole project to be able to trace missing files which might be helpful.
I just added the missing files and some hiddenimports to the spec file so you need to take care of those.

Start.py:

import traceback
try:
    """
    Whole Start.py script
    """
except Exception:
    traceback.print_exc()
    while(True):
        pass

Start.spec:

# -*- mode: python -*-

block_cipher = None

a = Analysis(['Start.py'],
             pathex=['C:\\Users\\Daniel\\Desktop\\SOAPUIReportingTool-master\\soap'],
             binaries=[],
             datas=[
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\tinycss2\\VERSION", "tinycss2"),
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\cairocffi\\VERSION", "cairocffi"),
                 ("C:\\Program Files\\Python37\\Lib\\site-packages\\\weasyprint\\VERSION", ".")
                     ],
             hiddenimports=["tinycss2", "matplotlib", "weasyprint"],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='Start',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=False,
          runtime_tmpdir=None,
          console=True )


问:
How to extract data from a dropdown menu using python beautifulsoup
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

```<code>enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]
</code>```

答:
Because of https://www.wheelmax.com has multilevel drop-down menu dependent on each other for example if you select Select Year drop down option, after selected year based on Select Make drop down is enable and display option based on the selected year option.

So basically you need to use Selenium package for handle dynamic option.

Install selenium web driver as per your browser

Download chrome web driver :

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

```<code>unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
</code>```

selenium tutorial

https://selenium-python.readthedocs.io/

Eg. using selenium to select multiple dropdown options

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(4)

selectYear = Select(driver.find_element_by_id("icm-years-select"))
selectYear.select_by_value('2019')

time.sleep(2)

selectMakes = Select(driver.find_element_by_id("icm-makes-select"))
selectMakes.select_by_value('58')
</code>```

Update:

select drop down option value or count total options

```<code>for option in selectYear.options:
    print(option.text)

print(len(selectYear.options))
</code>```

Se more

Body:
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]

Body:
Because of https://www.wheelmax.com has multilevel drop-down menu dependent on each other for example if you select Select Year drop down option, after selected year based on Select Make drop down is enable and display option based on the selected year option.

So basically you need to use Selenium package for handle dynamic option.

Install selenium web driver as per your browser

Download chrome web driver :

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

selenium tutorial

https://selenium-python.readthedocs.io/

Eg. using selenium to select multiple dropdown options

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(4)

selectYear = Select(driver.find_element_by_id("icm-years-select"))
selectYear.select_by_value('2019')

time.sleep(2)

selectMakes = Select(driver.find_element_by_id("icm-makes-select"))
selectMakes.select_by_value('58')

Update:

select drop down option value or count total options

for option in selectYear.options:
    print(option.text)

print(len(selectYear.options))

Se more


问:
Expression Language support in Golang
I am trying to implement a functionality that lets users try out configurations in run rime.

Basically, there are some preexisting configurations in DB, but users can make some tweaks on top of those and see results.

This component is written in Golang. One approach i am thinking is about using expression language support. I found some open source packages like https://github.com/araddon/qlbridge

But there are almost negligible number of sample programs / tutorials that demo how to use expression language along with PostgresQL.

Has any one used and attempted such thing? Any suggestions are welcome. Thank you for your time!

答:
Try https://github.com/antonmedv/expr – is an engine that can evaluate expressions.

It can handle expressions like this:

```<code>user.Group in ["good_customers", "collaborator"]

len(article.Comments) > 100 and article.Category not in ["misc"]

product.Stock < 15

all(Tickets, {.Price >0})
</code>```

And also has static type checker and user-friendly error messages

```<code>error: unclosed "("
 | (boo + bar]
 | ----------^
</code>```

Title: Expression Language support in Golang

Body:
Try https://github.com/antonmedv/expr – is an engine that can evaluate expressions.

It can handle expressions like this:

user.Group in ["good_customers", "collaborator"]

len(article.Comments) > 100 and article.Category not in ["misc"]

product.Stock < 15

all(Tickets, {.Price >0})

And also has static type checker and user-friendly error messages

error: unclosed "("
 | (boo + bar]
 | ----------^


问:
Open a windows from this script using Tkinter
I have two scripts, the one bellow is the script I am using as menu, so is the first windows that I need to open, from this one, when I click on "Simular" I need to close this window or "script" and open another one but passing the parameters.

```<code>from tkinter import *
main = Tk()

# Limpiar registros con botonLimpiar
def valoresLimpiar(*args):
  varDes.set('Seleccionar...')
  varModo.set('Seleccionar...')
  varEst.set('Seleccionar...')

# Obtener Valores con botonSimular
def valoresSimular(*args):
  print(varDes.get())
  print(varModo.get())
  print(varEst.get())

# Variables
varDes = StringVar(main)
varDes.set('Seleccionar...')

varModo = StringVar(main)
varModo.set('Seleccionar...')

varEst = StringVar(main)
varEst.set('Seleccionar...')

main.title("Configuración")
main.configure(background = 'light grey') # Color de Fondo

# Caja texto
labelOpciones = Label(main, bg = "light grey", text = 'Ventana Deslizante', padx = 30, pady = 5, width=20)
labelOpciones.grid(row = 0, column = 0)
labelOpciones2 = Label(main, bg = "light grey", text = 'Modo de Transmisión', padx = 30, pady = 5, width=20)
labelOpciones2.grid(row = 1, column = 0)
labelOpciones3 = Label(main, bg = "light grey", text = 'Estrategia de Transmisión', padx = 30, pady = 5, width=20)
labelOpciones3.grid(row = 2, column = 0)

# Caja de Opciones
opciones = ['1','2', '3', '4', '5', '6', '7']
ventanaDeslizante = OptionMenu(main, varDes, *opciones)
ventanaDeslizante.config(width=20)
ventanaDeslizante.grid(row = 0, column = 1, padx = 30, pady = 30)
opciones2 = ['NRM','ABM']
ventanaModoTrans = OptionMenu(main, varModo, *opciones2)
ventanaModoTrans.config(width=20)
ventanaModoTrans.grid(row = 1, column = 1, padx = 30, pady = 30)
opciones3 = ['GoBack-N','Repetición Selectiva']
ventanaEstTrans = OptionMenu(main, varEst, *opciones3)
ventanaEstTrans.config(width=20)
ventanaEstTrans.grid(row = 2, column = 1, padx = 30, pady = 30)

# Botones Limpiar y Simular
botonLimpiar = Button(main, text="Limpiar", width=20, command=valoresLimpiar)
botonLimpiar.grid(row = 3, column = 0, padx = 20, pady = 30)
botonSimular = Button(main, text="Simular", width=20, command=valoresSimular)
botonSimular.grid(row = 3, column = 1, padx = 20, pady = 30)

main.mainloop()
</code>```

I know the is a way to do this with classes, but I don't know how to use them, hope you can help me, thanks.

答:
I make some changes in you code replace OptionMenu by Combobox.
Then create new function for new window and pass variables after button is pushed.</p>

```<code>from tkinter import *
from tkinter.ttk import *
main = Tk()

# Limpiar registros con botonLimpiar
def valoresLimpiar(*args):
   varDes.set('Seleccionar...')
   varModo.set('Seleccionar...')
   varEst.set('Seleccionar...')

# Obtener Valores con botonSimular
def move_data():
    window = Tk()  # initiate tkinter to build window
    window.geometry('800x500')  # set window size
    label = Label(window, text='ventanaDeslizante = ' + data_1.get())  # set label
    label.grid(column=0, row=0)  # position of label
    label = Label(window, text='ventanaModoTrans = ' + data_2.get())  # set label
    label.grid(column=0, row=1)  # position of label
    label = Label(window, text='ventanaModoTrans = ' + data_3.get())  # set label
    label.grid(column=0, row=2)  # position of label
    window.mainloop()  # loop to show window

# Variables
varDes = StringVar(main)
varDes.set('Seleccionar...')

varModo = StringVar(main)
varModo.set('Seleccionar...')

varEst = StringVar(main)
varEst.set('Seleccionar...')

main.title("Configuración")
main.configure(background = 'light grey') # Color de Fondo

# Caja texto
label = Label(main, text='Ventana Deslizante')
label.grid(row = 0, column = 0)
label = Label(main, text = 'Modo de Transmisión')
label.grid(row = 1, column = 0)
label = Label(main, text = 'Estrategia de Transmisión')
label.grid(row = 2, column = 0)

# Caja de Opciones
data_1= StringVar()
ventanaDeslizante = Combobox(main, width=8, textvariable=data_1)
# create box list
ventanaDeslizante['values'] = ['1','2', '3', '4', '5', '6', '7']
# setup values for the list
ventanaDeslizante.current(0)
# set starting index from the list
ventanaDeslizante.grid(row = 0, column = 1, padx = 30, pady = 30)

data_2= StringVar()
ventanaModoTrans = Combobox(main, width=8, textvariable=data_2)
# create box list
ventanaModoTrans['values'] = ['NRM','ABM']
ventanaModoTrans.current(0)
ventanaModoTrans.grid(row = 1, column = 1, padx = 30, pady = 30)

data_3= StringVar()
ventanaEstTrans = Combobox(main, width=8, textvariable=data_3)
# create box list
ventanaEstTrans['values'] = ['GoBack-N','Repetición Selectiva']
ventanaEstTrans.current(0)
ventanaEstTrans.grid(row = 2, column = 1, padx = 30, pady = 30)

# Botones Limpiar y Simular
botonLimpiar = Button(main, text="Limpiar", width=20,
command=valoresLimpiar)
botonLimpiar.grid(row = 3, column = 0, padx = 20, pady = 30)
botonSimular = Button(main, text="Simular", width=20,
command=move_data)
botonSimular.grid(row = 3, column = 1, padx = 20, pady = 30)

main.mainloop()
</code>```

Body:
I have two scripts, the one bellow is the script I am using as menu, so is the first windows that I need to open, from this one, when I click on "Simular" I need to close this window or "script" and open another one but passing the parameters.

from tkinter import *
main = Tk()

# Limpiar registros con botonLimpiar
def valoresLimpiar(*args):
  varDes.set('Seleccionar...')
  varModo.set('Seleccionar...')
  varEst.set('Seleccionar...')

# Obtener Valores con botonSimular
def valoresSimular(*args):
  print(varDes.get())
  print(varModo.get())
  print(varEst.get())

# Variables
varDes = StringVar(main)
varDes.set('Seleccionar...')

varModo = StringVar(main)
varModo.set('Seleccionar...')

varEst = StringVar(main)
varEst.set('Seleccionar...')

main.title("Configuración")
main.configure(background = 'light grey') # Color de Fondo

# Caja texto
labelOpciones = Label(main, bg = "light grey", text = 'Ventana Deslizante', padx = 30, pady = 5, width=20)
labelOpciones.grid(row = 0, column = 0)
labelOpciones2 = Label(main, bg = "light grey", text = 'Modo de Transmisión', padx = 30, pady = 5, width=20)
labelOpciones2.grid(row = 1, column = 0)
labelOpciones3 = Label(main, bg = "light grey", text = 'Estrategia de Transmisión', padx = 30, pady = 5, width=20)
labelOpciones3.grid(row = 2, column = 0)

# Caja de Opciones
opciones = ['1','2', '3', '4', '5', '6', '7']
ventanaDeslizante = OptionMenu(main, varDes, *opciones)
ventanaDeslizante.config(width=20)
ventanaDeslizante.grid(row = 0, column = 1, padx = 30, pady = 30)
opciones2 = ['NRM','ABM']
ventanaModoTrans = OptionMenu(main, varModo, *opciones2)
ventanaModoTrans.config(width=20)
ventanaModoTrans.grid(row = 1, column = 1, padx = 30, pady = 30)
opciones3 = ['GoBack-N','Repetición Selectiva']
ventanaEstTrans = OptionMenu(main, varEst, *opciones3)
ventanaEstTrans.config(width=20)
ventanaEstTrans.grid(row = 2, column = 1, padx = 30, pady = 30)

# Botones Limpiar y Simular
botonLimpiar = Button(main, text="Limpiar", width=20, command=valoresLimpiar)
botonLimpiar.grid(row = 3, column = 0, padx = 20, pady = 30)
botonSimular = Button(main, text="Simular", width=20, command=valoresSimular)
botonSimular.grid(row = 3, column = 1, padx = 20, pady = 30)

main.mainloop()

I know the is a way to do this with classes, but I don't know how to use them, hope you can help me, thanks.

Body:
I make some changes in you code replace OptionMenu by Combobox.
Then create new function for new window and pass variables after button is pushed.

from tkinter import *
from tkinter.ttk import *
main = Tk()

# Limpiar registros con botonLimpiar
def valoresLimpiar(*args):
   varDes.set('Seleccionar...')
   varModo.set('Seleccionar...')
   varEst.set('Seleccionar...')

# Obtener Valores con botonSimular
def move_data():
    window = Tk()  # initiate tkinter to build window
    window.geometry('800x500')  # set window size
    label = Label(window, text='ventanaDeslizante = ' + data_1.get())  # set label
    label.grid(column=0, row=0)  # position of label
    label = Label(window, text='ventanaModoTrans = ' + data_2.get())  # set label
    label.grid(column=0, row=1)  # position of label
    label = Label(window, text='ventanaModoTrans = ' + data_3.get())  # set label
    label.grid(column=0, row=2)  # position of label
    window.mainloop()  # loop to show window

# Variables
varDes = StringVar(main)
varDes.set('Seleccionar...')

varModo = StringVar(main)
varModo.set('Seleccionar...')

varEst = StringVar(main)
varEst.set('Seleccionar...')

main.title("Configuración")
main.configure(background = 'light grey') # Color de Fondo

# Caja texto
label = Label(main, text='Ventana Deslizante')
label.grid(row = 0, column = 0)
label = Label(main, text = 'Modo de Transmisión')
label.grid(row = 1, column = 0)
label = Label(main, text = 'Estrategia de Transmisión')
label.grid(row = 2, column = 0)

# Caja de Opciones
data_1= StringVar()
ventanaDeslizante = Combobox(main, width=8, textvariable=data_1)
# create box list
ventanaDeslizante['values'] = ['1','2', '3', '4', '5', '6', '7']
# setup values for the list
ventanaDeslizante.current(0)
# set starting index from the list
ventanaDeslizante.grid(row = 0, column = 1, padx = 30, pady = 30)

data_2= StringVar()
ventanaModoTrans = Combobox(main, width=8, textvariable=data_2)
# create box list
ventanaModoTrans['values'] = ['NRM','ABM']
ventanaModoTrans.current(0)
ventanaModoTrans.grid(row = 1, column = 1, padx = 30, pady = 30)

data_3= StringVar()
ventanaEstTrans = Combobox(main, width=8, textvariable=data_3)
# create box list
ventanaEstTrans['values'] = ['GoBack-N','Repetición Selectiva']
ventanaEstTrans.current(0)
ventanaEstTrans.grid(row = 2, column = 1, padx = 30, pady = 30)

# Botones Limpiar y Simular
botonLimpiar = Button(main, text="Limpiar", width=20,
command=valoresLimpiar)
botonLimpiar.grid(row = 3, column = 0, padx = 20, pady = 30)
botonSimular = Button(main, text="Simular", width=20,
command=move_data)
botonSimular.grid(row = 3, column = 1, padx = 20, pady = 30)

main.mainloop()


问:
How to delete the first row
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

```<code>DB::table('ahah')->first()->delete().
</code>```

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

答:
It doesn't work because DB::table('ahah')->first() is returning a stdClass object. And of course, stdClass has no delete() method.

So you will need to get the first item of your table with SQL statements:

// Supposing your primary key column is called 'id'

DB::table('ahah')
    ->orderBy('id')
    ->limit(1)
    ->delete();
```

Title: How to delete the first row

Body:
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

DB::table('ahah')->first()->delete().

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?


问:
Django UnicodeDecodeError during error reporting
Error reporting is constantly crashing. In the traceback, I first get the actual error, then many times the same

```<code>During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__
    response = response or self.get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner
    response = response_for_exception(request, exc)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response
    html = reporter.get_traceback_html()
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html
    t = DEBUG_ENGINE.from_string(fh.read())
  File "/var/www/exc2-backend/.venv/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)
</code>```

I am using Python3.6 and Django==2.2. I do not understand where the UnicodeDecodeError comes from.

Running on production server

```<code>from django.test.client import RequestFactory
import sys
from django.views.debug import ExceptionReporter

request = RequestFactory().get('/dummy')
exc_info = sys.exc_info()
reporter = ExceptionReporter(request, is_email=True, *exc_info)
reporter.get_traceback_html()
</code>```

works without crashing.

I am running my website with gunicorn, using the following command

/var/www/exc2-backend/.venv/bin/gunicorn exc2_backend.wsgi --name "exc2_backend" --workers=4 --bind=0.0.0.0:8000 --user="www-data" --group="www-data"

I narrowed down the problem, which happens here

```<code>from django.views.debug import ExceptionReporter, CURRENT_DIR, DEBUG_ENGINE
from pathlib import Path

with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh:
    data = fh.read()
</code>```

if I change to Path(...).open(encoding='utf8'), there is no error.

The error does not happen with the shell, only when code is run with gunicorn.

On the server, even through gunicorn, sys.getdefaultencoding() return utf-8, but locale.getpreferredencoding(False) returns ANSI_X3.4-1968!

Any ideas?

答:
The locale I had set in Gunicorn (fr_FR.UTF8) was not installed on the system, so somehow Python was defaulting to the ANSI_X3.4-1968 encoding.

The solution was to install the missing locale: sudo locale-gen fr_FR.UTF-8

Body:
Error reporting is constantly crashing. In the traceback, I first get the actual error, then many times the same

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__
    response = response or self.get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner
    response = response_for_exception(request, exc)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response
    html = reporter.get_traceback_html()
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html
    t = DEBUG_ENGINE.from_string(fh.read())
  File "/var/www/exc2-backend/.venv/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)

I am using Python3.6 and Django==2.2. I do not understand where the UnicodeDecodeError comes from.

Running on production server

from django.test.client import RequestFactory
import sys
from django.views.debug import ExceptionReporter

request = RequestFactory().get('/dummy')
exc_info = sys.exc_info()
reporter = ExceptionReporter(request, is_email=True, *exc_info)
reporter.get_traceback_html()

works without crashing.

I am running my website with gunicorn, using the following command

/var/www/exc2-backend/.venv/bin/gunicorn exc2_backend.wsgi --name "exc2_backend" --workers=4 --bind=0.0.0.0:8000 --user="www-data" --group="www-data"

I narrowed down the problem, which happens here

from django.views.debug import ExceptionReporter, CURRENT_DIR, DEBUG_ENGINE
from pathlib import Path

with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh:
    data = fh.read()

if I change to Path(...).open(encoding='utf8'), there is no error.

The error does not happen with the shell, only when code is run with gunicorn.

On the server, even through gunicorn, sys.getdefaultencoding() return utf-8, but locale.getpreferredencoding(False) returns ANSI_X3.4-1968!

Any ideas?


问:
How to get city and state name in Autocomplete Places _ Places API
Iam using Places Autocomplete for selecting city from user, its working fine,
But now i want both city and state name..
my code..

Initialising

```<code>  List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
            Intent intent = new Autocomplete.IntentBuilder(
                    AutocompleteActivityMode.OVERLAY, fields)
                    .setTypeFilter(TypeFilter.CITIES)
                    .setCountry("IN")
                    .build(this);
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
</code>```

onActivity Result

```<code>if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //Place place = Autocomplete.getPlaceFromIntent(data);
                Place place = Autocomplete.getPlaceFromIntent(data);

                edit_profile_city_editText.setText(place.getName());

            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i("Autocomplete error", status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
            }
        }
</code>```

While selecting city from search bar its showing both city and state..
eg:Chennai
TamilNadu, India
Kindly help how to get state name also...

答:
Try something like this:

```<code> Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
 List<Address> addresses = new ArrayList<>();
 addresses = geocoder.getFromLocation(lat, lng, 1);
 String country = addresses.get(0).getCountryName();
</code>```

Body:
Iam using Places Autocomplete for selecting city from user, its working fine,
But now i want both city and state name..
my code..

Initialising

  List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
            Intent intent = new Autocomplete.IntentBuilder(
                    AutocompleteActivityMode.OVERLAY, fields)
                    .setTypeFilter(TypeFilter.CITIES)
                    .setCountry("IN")
                    .build(this);
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

onActivity Result

if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //Place place = Autocomplete.getPlaceFromIntent(data);
                Place place = Autocomplete.getPlaceFromIntent(data);

                edit_profile_city_editText.setText(place.getName());

            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i("Autocomplete error", status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
            }
        }

While selecting city from search bar its showing both city and state..
eg:Chennai
TamilNadu, India
Kindly help how to get state name also...

Body:
Try something like this:

 Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
 List<Address> addresses = new ArrayList<>();
 addresses = geocoder.getFromLocation(lat, lng, 1);
 String country = addresses.get(0).getCountryName();


问:
How to fix "signal SIGABRT" when using self.UISegmentedControl.selectedSegmentIndex
each time I using "self.SegControl.selectedSegmentIndex", I would get SIGABRT signal in the following code :

```<code>int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil,     NSStringFromClass([AppDelegate class]));// signal SIGABRT
    }
}
</code>```

I tried to find the value of self.SegControl.selectedSegmentIndex :

```<code>long a=self.SegControl.selectedSegmentIndex;
</code>```

However, I find out I even cannot use self.SegControl.selectedSegmentIndex.

```<code>...
@property (weak, nonatomic) IBOutlet UISegmentedControl *SegControl;
...
- (IBAction)Button:(id)sender {
NSMutableString *str=[NSMutableString new];
if(self.SegControl.selectedSegmentIndex==0){
    [str appendString:@"unit 2"];
}
else if(self.SegControl.selectedSegmentIndex==1){
    [str appendString:@"unit 3"];
}
else if(self.SegControl.selectedSegmentIndex==2){
    [str appendString:@"unit 4"];
}
self.Output.text=str;
}
...
</code>```

I wanna get the output of self.SegControl.selectedSegmentIndex. I wanna let my program know which segment is chosen.
Please help me out!
Thank you!

答:
Is any index selected at the moment of the if statement?

In your storyboard, do you have any selected index as default value? There is a check box where you can set the behavior of the default selected index. Or you should do it programmatically before the if statements.

Body:
each time I using "self.SegControl.selectedSegmentIndex", I would get SIGABRT signal in the following code :

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil,     NSStringFromClass([AppDelegate class]));// signal SIGABRT
    }
}

I tried to find the value of self.SegControl.selectedSegmentIndex :

long a=self.SegControl.selectedSegmentIndex;

However, I find out I even cannot use self.SegControl.selectedSegmentIndex.

...
@property (weak, nonatomic) IBOutlet UISegmentedControl *SegControl;
...
- (IBAction)Button:(id)sender {
NSMutableString *str=[NSMutableString new];
if(self.SegControl.selectedSegmentIndex==0){
    [str appendString:@"unit 2"];
}
else if(self.SegControl.selectedSegmentIndex==1){
    [str appendString:@"unit 3"];
}
else if(self.SegControl.selectedSegmentIndex==2){
    [str appendString:@"unit 4"];
}
self.Output.text=str;
}
...

I wanna get the output of self.SegControl.selectedSegmentIndex. I wanna let my program know which segment is chosen.
Please help me out!
Thank you!


问:
Property displayed as undefined in React Component - Retrieve props.match and additional property in component
I have an index.js from which i am calling a Component like this

```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

答:
```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/" component={() => <MyComponent prop1={prop1}>} />
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

Body:
I have an index.js from which i am calling a Component like this

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1


问:
Shared settings in .NET Core?
I have 3 files named appsettings.[int/stg/prod].json  in my asp.net core app:

```<code>{
    "EmailForFailedNonCrucial":
    {
        "Email": "royin...",
        "Subject": "...",
        "Body": "...",
        "ConnectionString": "Staging-Connection-String"
    },
    "Servers": [
    {
        "Name": "aaa",
        "Services": [
            ...
        ]
    },
    {
        "Name": "bbb",
        "Services": [
            ...
        ]
    }]
}
</code>```

Each section has a corresponded section in C# class. (for IOptions).

I have 3 versions of that file, for each environemnt :

I can use it via :

```<code> public static IConfigurationRoot ConfigureConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($@"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

        }
</code>```

But the only thing that should be different across environments is the ConnectionString.

The Servers section is the same for all environments.

Question:

It seems odd to duplicate the Servers across all 3 files.

How can I accomplish (inheritance?) specifying it once, and have only EmailForFailedNonCrucial per environment?

答:
Simply placing the servers section inside your root appsettings.json removing them from your others should add the servers configuration to all others by default.

Some more reading : Configuration in Core

Title: Shared settings in .NET Core?

Body:
I have 3 files named appsettings.[int/stg/prod].json  in my asp.net core app:

{
    "EmailForFailedNonCrucial":
    {
        "Email": "royin...",
        "Subject": "...",
        "Body": "...",
        "ConnectionString": "Staging-Connection-String"
    },
    "Servers": [
    {
        "Name": "aaa",
        "Services": [
            ...
        ]
    },
    {
        "Name": "bbb",
        "Services": [
            ...
        ]
    }]
}

Each section has a corresponded section in C# class. (for IOptions).

I have 3 versions of that file, for each environemnt :

I can use it via :

 public static IConfigurationRoot ConfigureConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($@"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

        }

But the only thing that should be different across environments is the ConnectionString.

The Servers section is the same for all environments.

Question:

It seems odd to duplicate the Servers across all 3 files.

How can I accomplish (inheritance?) specifying it once, and have only EmailForFailedNonCrucial per environment?