问:
Can't get React Hot Loader to work
I am trying to config react-hot-loader into my app. It's built on webpack 2, webpack-dev-middleware, browser-sync, express and doing server side rendering.

Here's my webpack.config

```<code>require('dotenv').config()
import path from 'path'
import webpack from 'webpack'
import extend from 'extend'
import AssetsPlugin from 'assets-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import bundles from '../src/bundles'
import merge from 'lodash/merge'
import fs from 'fs'

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const GLOBALS = {
  'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
  'process.env.MORTGAGE_CALCULATOR_API': process.env.MORTGAGE_CALCULATOR_API ? `"${process.env.MORTGAGE_CALCULATOR_API}"` : null,
  'process.env.API_HOST': process.env.BROWSER_API_HOST ? `"${process.env.BROWSER_API_HOST}"` : process.env.API_HOST ? `"${process.env.API_HOST}"` : null,
  'process.env.GOOGLE_ANALYTICS_ID': process.env.GOOGLE_ANALYTICS_ID ? `"${process.env.GOOGLE_ANALYTICS_ID}"` : null,
  'process.env.OMNITURE_SUITE_ID': process.env.OMNITURE_SUITE_ID ? `"${process.env.OMNITURE_SUITE_ID}"` : null,
  'process.env.COOKIE_DOMAIN': process.env.COOKIE_DOMAIN ? `"${process.env.COOKIE_DOMAIN}"` : null,
  'process.env.FEATURE_FLAG_BAZAAR_VOICE': process.env.FEATURE_FLAG_BAZAAR_VOICE ? `"${process.env.FEATURE_FLAG_BAZAAR_VOICE}"` : null,
  'process.env.FEATURE_FLAG_REALTIME_RATING': process.env.FEATURE_FLAG_REALTIME_RATING ? `"${process.env.FEATURE_FLAG_REALTIME_RATING}"` : null,
  'process.env.SALE_RESULTS_PAGE_FLAG': process.env.SALE_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RESULTS_PAGE_FLAG}"` : null,
  'process.env.SALE_RELOADED_RESULTS_PAGE_FLAG': process.env.SALE_RELOADED_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RELOADED_RESULTS_PAGE_FLAG}"` : null,
  'process.env.TRACKER_DOMAIN': process.env.TRACKER_DOMAIN ? `"${process.env.TRACKER_DOMAIN}"` : null,
  'process.env.USER_SERVICE_ENDPOINT': process.env.USER_SERVICE_ENDPOINT ? `"${process.env.USER_SERVICE_ENDPOINT}"` : null,
  __DEV__: isDebug
};

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

const config = {
  output: {
    publicPath: '/blaze-assets/',
  },

  cache: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  plugins: [
    new ExtractTextPlugin({
      filename: isDebug ? '[name].css' : '[name].[chunkhash].css',
      allChunks: true,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: isDebug,
    }),
  ],

  resolve: {
    extensions: ['.webpack.js', '.web.js', '.js', '.jsx', '.json'],
    modules: [
      path.resolve('./src'),
      'node_modules',
    ]
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, '../src'),
        ],
        loader: 'babel-loader',
      }, {
        test: /\.(scss|css)$/,
        exclude: ['node_modules'],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'sass-loader',
          ]
        })
      }, {
        test: /\.txt$/,
        loader: 'raw-loader',
      }, {
        test: /\.(otf|png|jpg|jpeg|gif|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000',
      }, {
        test: /\.(eot|ttf|wav|mp3)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      }, {
        test: /\.jade$/,
        loader: 'jade-loader',
      }
    ],
  },
};

//
// Configuration for the client-side bundles
// -----------------------------------------------------------------------------
let clientBundles = {}

Object.keys(bundles).forEach(function (bundle) {
  clientBundles[bundle] = [
    'bootstrap-loader',
    `./src/bundles/${bundle}/index.js`
  ]
})

merge(
  clientBundles,
  {
    'embedWidget': ['./src/components/Widgets/EmbedWidget/widgetLoader.js']
  },
)

const clientConfig = extend(true, {}, config, {
  entry: clientBundles,
  output: {
    path: path.join(__dirname, '../build/public/blaze-assets/'),
    filename: isDebug ? '[name].js' : '[name].[chunkhash].js',
    chunkFilename: isDebug ? '[name].chunk.js' : '[name].[chunkhash].chunk.js',
  },
  node: {
    fs: "empty"
  },
  // Choose a developer tool to enhance debugging
  // http://webpack.github.io/docs/configuration.html#devtool
  // devtool: isDebug ? 'cheap-module-source-map' : false,
  plugins: [
    ...config.plugins,
    ...(isDebug ? [
        new webpack.EvalSourceMapDevToolPlugin({
          filename: '[file].map',
          exclude: /\.(css)($)/i,
        }),
      ] : []),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      ...GLOBALS,
      'process.env.BROWSER': true
    }),
    ...(!isDebug ? [
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
          screw_ie8: true,

          // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
          warnings: isVerbose,
          unused: true,
          dead_code: true,
        },
      }),
      new webpack.optimize.AggressiveMergingPlugin(),
    ] : []),
    new AssetsPlugin({
      path: path.join(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
  ],
});

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

var srcDirs = {};
fs.readdirSync('src').forEach(function(path) {
  srcDirs[path] = true
});

function isExternalFile(context, request, callback) {
  var isExternal = request.match(/^[@a-z][a-z\/\.\-0-9]*$/i) && !srcDirs[request.split("/")[0]]
  callback(null, Boolean(isExternal));
}

const serverConfig = extend(true, {}, config, {
  entry: './src/server.js',
  output: {
    path: path.join(__dirname, '../build/public/blaze-assets/'),
    filename: '../../server.js',
    libraryTarget: 'commonjs2',
  },
  target: 'node',
  externals: [
    /^\.\/assets\.json$/,
    isExternalFile
  ],
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
  devtool: isDebug ? 'cheap-module-source-map' : 'source-map',
  plugins: [
    ...config.plugins,
    new webpack.DefinePlugin({
      ...GLOBALS,
      'process.env.BROWSER': false,
      'process.env.API_HOST': process.env.API_HOST ? `"${process.env.API_HOST}"` : null
    }),
    new webpack.NormalModuleReplacementPlugin(/\.(scss|css|eot|ttf|woff|woff2)$/, 'node-noop'),
    new webpack.BannerPlugin({
      banner: `require('dotenv').config(); require('newrelic'); require('source-map-support').install();`,
      raw: true,
      entryOnly: false
    })
  ],
});

export default [clientConfig, serverConfig];
</code>```

start.js file

```<code>import Browsersync from 'browser-sync'
import webpack from 'webpack'
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import WriteFilePlugin from 'write-file-webpack-plugin'
import run from './run'
import runServer from './runServer'
import webpackConfig from './webpack.config'
import clean from './clean'
import copy from './copy'

const isDebug = !process.argv.includes('--release')
const [, serverConfig] = webpackConfig
process.argv.push('--watch')
/**
 * Launches a development web server with "live reload" functionality -
 * synchronizing URLs, interactions and code changes across multiple devices.
 */
async function start () {
  await run(clean)
  await run(copy.bind(undefined, { watch: true }))
  await new Promise((resolve) => {

    serverConfig.plugins.push(new WriteFilePlugin({ log: false }))
    // Patch the client-side bundle configurations
    // to enable Hot Module Replacement (HMR) and React Transform
    webpackConfig.filter((x) => x.target !== 'node').forEach((config) => {
      /* eslint-disable no-param-reassign */
      Object.keys(config.entry).forEach((entryKey) => {
        if (!Array.isArray(config.entry[entryKey])) {
          config.entry[entryKey] = [config.entry[entryKey]]
        }
        config.entry[entryKey].unshift('react-hot-loader/patch', 'webpack-hot-middleware/client')
      })
      if (config.output.filename) {
        config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]')
      }
      if (config.output.chunkFilename) {
        config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]')
      }
      config.plugins.push(new webpack.HotModuleReplacementPlugin())
      config.plugins.push(new webpack.NoEmitOnErrorsPlugin())
      config
        .module
        .rules
        .filter((x) => x.loader === 'babel-loader')
        .forEach((x) => (x.query = {
          ...x.query,
          cacheDirectory: true,
          presets: [
            ['es2015', {modules: false}],
            'stage-0',
            'react'
          ],
          plugins: [
            ...(x.query ? x.query.plugins : []),
            [
              'react-hot-loader/babel',
            ],
          ],
        }))
      /* eslint-enable no-param-reassign */
    })

    const bundler = webpack(webpackConfig)
    const wpMiddleware = webpackMiddleware(bundler, {

      // IMPORTANT: webpack middleware can't access config,
      // so we should provide publicPath by ourselves
      publicPath: webpackConfig[0].output.publicPath,

      // Pretty colored output
      stats: webpackConfig[0].stats,

      // For other settings see
      // https://webpack.github.io/docs/webpack-dev-middleware
    })
    const hotMiddleware = webpackHotMiddleware(bundler.compilers[0])

    let handleBundleComplete = async () => {
      handleBundleComplete = (stats) => !stats.stats[1].compilation.errors.length && runServer()

      const server = await runServer()
      const bs = Browsersync.create()

      bs.init({
        ...isDebug ? {} : { notify: false, ui: false },

        proxy: {
          target: server.host,
          middleware: [wpMiddleware, hotMiddleware],
          proxyOptions: {
            xfwd: true,
          },
        },
        open: false,
        files: ['build/content/**/*.*'],
      }, resolve)
    }

    bundler.plugin('done', (stats) => handleBundleComplete(stats))
  })
}

export default start
</code>```

To hot load reducers, I have changed my code like this,

```<code>const configureStore = (initialState = {}) => {
  const store = createStore(
    // storage.reducer is what merges storage state into redux state
    storage.reducer(rootReducer),
    inflateDecorators(initialState),
    applyMiddleware(...middleware)
  )

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const nextRootReducer = require('./reducers')

      store.replaceReducer(nextRootReducer)
    })
  }

  return store
}
</code>```

We have multiple bundles, so there is common function to handle the entry logic,

```<code>import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import FastClick from 'fastclick'
import { Provider } from 'react-redux'
import { setUrl } from 'actions'
import Location from '../../libs/Location'
import configureStore, { loadFromLocalStorage } from '../../configureStore'
import { AppContainer } from 'react-hot-loader'

const initialState = window.__INITIAL_STATE__

const store = configureStore(initialState)

function runner (createBody) {
  return function () {
    // Make taps on links and buttons work fast on mobiles
    FastClick.attach(document.body)

    const component = (
     <AppContainer>
      <Provider store={store}>
        {createBody()}
      </Provider>
    </AppContainer>
    )

    if (!initialState) {
      store.dispatch(setUrl(`${Location.location.pathname}${Location.location.search}`))
    }

    Location.listen((location) => {
      store.dispatch(setUrl(`${location.pathname}${location.search}`))
    })

    ReactDOM.render(component, document.getElementById('app'))

    // only apply stored state after first render
    // this allows serverside and clientside rendering to agree on initial state
    loadFromLocalStorage(store)
  }
}

export default function run (createBody) {
  if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) {
    runner(createBody)()
  } else {
    document.addEventListener('DOMContentLoaded', runner(createBody), false)
  }
}
</code>```

This is one of the bundles entry point where the above common function is called,

```<code>import run from '../util/run'
import createBody from './body'

run(createBody)
if (module.hot) {
  module.hot.accept('./body', () => run(createBody))
}
</code>```

Not sure what I am missing still, I tried to follow a few blog post and react hot loader docs but I couldn't get it to working.

答:
Thought it would be helpful for people who have similar kind of setup, even in webpack 2 for react hot loader to work your entry point code should be something like this,

```<code>if (module.hot) {
  module.hot.accept('./body', () => {
    const body = require('./body').default
    run(body)
  })
}
</code>```

As I am using extract-text-webpack-plugin it is not possible to hot reload css changes. As I am already using browser-sync, the simple work around is to use write-file-webpack-plugin to write the css files out and let browser-sync listen to the changes.

Title: Can't get React Hot Loader to work

Body:
I am trying to config react-hot-loader into my app. It's built on webpack 2, webpack-dev-middleware, browser-sync, express and doing server side rendering.

Here's my webpack.config

require('dotenv').config()
import path from 'path'
import webpack from 'webpack'
import extend from 'extend'
import AssetsPlugin from 'assets-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import bundles from '../src/bundles'
import merge from 'lodash/merge'
import fs from 'fs'

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const GLOBALS = {
  'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
  'process.env.MORTGAGE_CALCULATOR_API': process.env.MORTGAGE_CALCULATOR_API ? `"${process.env.MORTGAGE_CALCULATOR_API}"` : null,
  'process.env.API_HOST': process.env.BROWSER_API_HOST ? `"${process.env.BROWSER_API_HOST}"` : process.env.API_HOST ? `"${process.env.API_HOST}"` : null,
  'process.env.GOOGLE_ANALYTICS_ID': process.env.GOOGLE_ANALYTICS_ID ? `"${process.env.GOOGLE_ANALYTICS_ID}"` : null,
  'process.env.OMNITURE_SUITE_ID': process.env.OMNITURE_SUITE_ID ? `"${process.env.OMNITURE_SUITE_ID}"` : null,
  'process.env.COOKIE_DOMAIN': process.env.COOKIE_DOMAIN ? `"${process.env.COOKIE_DOMAIN}"` : null,
  'process.env.FEATURE_FLAG_BAZAAR_VOICE': process.env.FEATURE_FLAG_BAZAAR_VOICE ? `"${process.env.FEATURE_FLAG_BAZAAR_VOICE}"` : null,
  'process.env.FEATURE_FLAG_REALTIME_RATING': process.env.FEATURE_FLAG_REALTIME_RATING ? `"${process.env.FEATURE_FLAG_REALTIME_RATING}"` : null,
  'process.env.SALE_RESULTS_PAGE_FLAG': process.env.SALE_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RESULTS_PAGE_FLAG}"` : null,
  'process.env.SALE_RELOADED_RESULTS_PAGE_FLAG': process.env.SALE_RELOADED_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RELOADED_RESULTS_PAGE_FLAG}"` : null,
  'process.env.TRACKER_DOMAIN': process.env.TRACKER_DOMAIN ? `"${process.env.TRACKER_DOMAIN}"` : null,
  'process.env.USER_SERVICE_ENDPOINT': process.env.USER_SERVICE_ENDPOINT ? `"${process.env.USER_SERVICE_ENDPOINT}"` : null,
  __DEV__: isDebug
};

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

const config = {
  output: {
    publicPath: '/blaze-assets/',
  },

  cache: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  plugins: [
    new ExtractTextPlugin({
      filename: isDebug ? '[name].css' : '[name].[chunkhash].css',
      allChunks: true,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: isDebug,
    }),
  ],

  resolve: {
    extensions: ['.webpack.js', '.web.js', '.js', '.jsx', '.json'],
    modules: [
      path.resolve('./src'),
      'node_modules',
    ]
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, '../src'),
        ],
        loader: 'babel-loader',
      }, {
        test: /\.(scss|css)$/,
        exclude: ['node_modules'],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'sass-loader',
          ]
        })
      }, {
        test: /\.txt$/,
        loader: 'raw-loader',
      }, {
        test: /\.(otf|png|jpg|jpeg|gif|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000',
      }, {
        test: /\.(eot|ttf|wav|mp3)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      }, {
        test: /\.jade$/,
        loader: 'jade-loader',
      }
    ],
  },
};

//
// Configuration for the client-side bundles
// -----------------------------------------------------------------------------
let clientBundles = {}

Object.keys(bundles).forEach(function (bundle) {
  clientBundles[bundle] = [
    'bootstrap-loader',
    `./src/bundles/${bundle}/index.js`
  ]
})

merge(
  clientBundles,
  {
    'embedWidget': ['./src/components/Widgets/EmbedWidget/widgetLoader.js']
  },
)

const clientConfig = extend(true, {}, config, {
  entry: clientBundles,
  output: {
    path: path.join(__dirname, '../build/public/blaze-assets/'),
    filename: isDebug ? '[name].js' : '[name].[chunkhash].js',
    chunkFilename: isDebug ? '[name].chunk.js' : '[name].[chunkhash].chunk.js',
  },
  node: {
    fs: "empty"
  },
  // Choose a developer tool to enhance debugging
  // http://webpack.github.io/docs/configuration.html#devtool
  // devtool: isDebug ? 'cheap-module-source-map' : false,
  plugins: [
    ...config.plugins,
    ...(isDebug ? [
        new webpack.EvalSourceMapDevToolPlugin({
          filename: '[file].map',
          exclude: /\.(css)($)/i,
        }),
      ] : []),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      ...GLOBALS,
      'process.env.BROWSER': true
    }),
    ...(!isDebug ? [
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
          screw_ie8: true,

          // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
          warnings: isVerbose,
          unused: true,
          dead_code: true,
        },
      }),
      new webpack.optimize.AggressiveMergingPlugin(),
    ] : []),
    new AssetsPlugin({
      path: path.join(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
  ],
});

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

var srcDirs = {};
fs.readdirSync('src').forEach(function(path) {
  srcDirs[path] = true
});

function isExternalFile(context, request, callback) {
  var isExternal = request.match(/^[@a-z][a-z\/\.\-0-9]*$/i) && !srcDirs[request.split("/")[0]]
  callback(null, Boolean(isExternal));
}

const serverConfig = extend(true, {}, config, {
  entry: './src/server.js',
  output: {
    path: path.join(__dirname, '../build/public/blaze-assets/'),
    filename: '../../server.js',
    libraryTarget: 'commonjs2',
  },
  target: 'node',
  externals: [
    /^\.\/assets\.json$/,
    isExternalFile
  ],
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
  devtool: isDebug ? 'cheap-module-source-map' : 'source-map',
  plugins: [
    ...config.plugins,
    new webpack.DefinePlugin({
      ...GLOBALS,
      'process.env.BROWSER': false,
      'process.env.API_HOST': process.env.API_HOST ? `"${process.env.API_HOST}"` : null
    }),
    new webpack.NormalModuleReplacementPlugin(/\.(scss|css|eot|ttf|woff|woff2)$/, 'node-noop'),
    new webpack.BannerPlugin({
      banner: `require('dotenv').config(); require('newrelic'); require('source-map-support').install();`,
      raw: true,
      entryOnly: false
    })
  ],
});

export default [clientConfig, serverConfig];

start.js file

import Browsersync from 'browser-sync'
import webpack from 'webpack'
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import WriteFilePlugin from 'write-file-webpack-plugin'
import run from './run'
import runServer from './runServer'
import webpackConfig from './webpack.config'
import clean from './clean'
import copy from './copy'

const isDebug = !process.argv.includes('--release')
const [, serverConfig] = webpackConfig
process.argv.push('--watch')
/**
 * Launches a development web server with "live reload" functionality -
 * synchronizing URLs, interactions and code changes across multiple devices.
 */
async function start () {
  await run(clean)
  await run(copy.bind(undefined, { watch: true }))
  await new Promise((resolve) => {

    serverConfig.plugins.push(new WriteFilePlugin({ log: false }))
    // Patch the client-side bundle configurations
    // to enable Hot Module Replacement (HMR) and React Transform
    webpackConfig.filter((x) => x.target !== 'node').forEach((config) => {
      /* eslint-disable no-param-reassign */
      Object.keys(config.entry).forEach((entryKey) => {
        if (!Array.isArray(config.entry[entryKey])) {
          config.entry[entryKey] = [config.entry[entryKey]]
        }
        config.entry[entryKey].unshift('react-hot-loader/patch', 'webpack-hot-middleware/client')
      })
      if (config.output.filename) {
        config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]')
      }
      if (config.output.chunkFilename) {
        config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]')
      }
      config.plugins.push(new webpack.HotModuleReplacementPlugin())
      config.plugins.push(new webpack.NoEmitOnErrorsPlugin())
      config
        .module
        .rules
        .filter((x) => x.loader === 'babel-loader')
        .forEach((x) => (x.query = {
          ...x.query,
          cacheDirectory: true,
          presets: [
            ['es2015', {modules: false}],
            'stage-0',
            'react'
          ],
          plugins: [
            ...(x.query ? x.query.plugins : []),
            [
              'react-hot-loader/babel',
            ],
          ],
        }))
      /* eslint-enable no-param-reassign */
    })

    const bundler = webpack(webpackConfig)
    const wpMiddleware = webpackMiddleware(bundler, {

      // IMPORTANT: webpack middleware can't access config,
      // so we should provide publicPath by ourselves
      publicPath: webpackConfig[0].output.publicPath,

      // Pretty colored output
      stats: webpackConfig[0].stats,

      // For other settings see
      // https://webpack.github.io/docs/webpack-dev-middleware
    })
    const hotMiddleware = webpackHotMiddleware(bundler.compilers[0])

    let handleBundleComplete = async () => {
      handleBundleComplete = (stats) => !stats.stats[1].compilation.errors.length && runServer()

      const server = await runServer()
      const bs = Browsersync.create()

      bs.init({
        ...isDebug ? {} : { notify: false, ui: false },

        proxy: {
          target: server.host,
          middleware: [wpMiddleware, hotMiddleware],
          proxyOptions: {
            xfwd: true,
          },
        },
        open: false,
        files: ['build/content/**/*.*'],
      }, resolve)
    }

    bundler.plugin('done', (stats) => handleBundleComplete(stats))
  })
}

export default start

To hot load reducers, I have changed my code like this,

const configureStore = (initialState = {}) => {
  const store = createStore(
    // storage.reducer is what merges storage state into redux state
    storage.reducer(rootReducer),
    inflateDecorators(initialState),
    applyMiddleware(...middleware)
  )

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const nextRootReducer = require('./reducers')

      store.replaceReducer(nextRootReducer)
    })
  }

  return store
}

We have multiple bundles, so there is common function to handle the entry logic,

import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import FastClick from 'fastclick'
import { Provider } from 'react-redux'
import { setUrl } from 'actions'
import Location from '../../libs/Location'
import configureStore, { loadFromLocalStorage } from '../../configureStore'
import { AppContainer } from 'react-hot-loader'

const initialState = window.__INITIAL_STATE__

const store = configureStore(initialState)

function runner (createBody) {
  return function () {
    // Make taps on links and buttons work fast on mobiles
    FastClick.attach(document.body)

    const component = (
     <AppContainer>
      <Provider store={store}>
        {createBody()}
      </Provider>
    </AppContainer>
    )

    if (!initialState) {
      store.dispatch(setUrl(`${Location.location.pathname}${Location.location.search}`))
    }

    Location.listen((location) => {
      store.dispatch(setUrl(`${location.pathname}${location.search}`))
    })

    ReactDOM.render(component, document.getElementById('app'))

    // only apply stored state after first render
    // this allows serverside and clientside rendering to agree on initial state
    loadFromLocalStorage(store)
  }
}

export default function run (createBody) {
  if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) {
    runner(createBody)()
  } else {
    document.addEventListener('DOMContentLoaded', runner(createBody), false)
  }
}

This is one of the bundles entry point where the above common function is called,

import run from '../util/run'
import createBody from './body'

run(createBody)
if (module.hot) {
  module.hot.accept('./body', () => run(createBody))
}

Not sure what I am missing still, I tried to follow a few blog post and react hot loader docs but I couldn't get it to working.

Body:
Thought it would be helpful for people who have similar kind of setup, even in webpack 2 for react hot loader to work your entry point code should be something like this,

if (module.hot) {
  module.hot.accept('./body', () => {
    const body = require('./body').default
    run(body)
  })
}

As I am using extract-text-webpack-plugin it is not possible to hot reload css changes. As I am already using browser-sync, the simple work around is to use write-file-webpack-plugin to write the css files out and let browser-sync listen to the changes.


来源: stackexchange

问:
Professional jQuery based Combobox control?
Are there any professional Combobox controls (dropdown list with autosuggestion) based on the jQuery library?

It should be able to handle large datasets and have some skinning options. A multi-column result list would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a wrapper for it.

I'm already using a third-party control, but I ran into some compatibilty issues between two vendor's controls. Well, I want to get rid of this kind of dependencies.

答:
all what you need
http://jquerycomboboxtmpl.codeplex.com/

drop-down on templates

OwnerDisplayName: splattne

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Variable Dependence scipy.special.genlaguerre
I'm new to python. If I wanted L(n, a, x) where L is the general Laguerre polynomial then I could simply use

```<code>from scipy.special import genlaguerre
print(genlaguerre(n, a))
</code>```

However, I am having trouble obtaining something like L(n, a, 2 pi x) since  there is no explicit variable dependence in the function genlaguerre.

答:
The object returned by genlaguerre(n, a) is callable; you call it to evaluate it at a given x.

For example,

```<code>In [71]: import numpy as np

In [72]: import matplotlib.pyplot as plt

In [73]: from scipy.special import genlaguerre

In [74]: n = 3

In [75]: alpha = 4.5

In [76]: L = genlaguerre(n, alpha)
</code>```

To get the value of the polynomial at x, call L(x):

```<code>In [77]: L(0)
Out[77]: 44.6875

In [78]: L(1)
Out[78]: 23.895833333333332

In [79]: L([2, 2.5, 3])
Out[79]: array([ 9.60416667,  4.58333333,  0.8125    ])

In [80]: x = np.linspace(0, 14, 100)

In [81]: plt.plot(x, L(x))
Out[81]: [<matplotlib.lines.Line2D at 0x11cde42b0>]

In [82]: plt.xlabel('x')
Out[82]: <matplotlib.text.Text at 0x11cddc4a8>

In [83]: plt.ylabel('$L_{%d}^{(%g)}(x)$' % (n, alpha))
Out[83]: <matplotlib.text.Text at 0x11cdce320>

In [84]: plt.grid()
</code>```

Here's the plot generated by the above code:

Body:
I'm new to python. If I wanted L(n, a, x) where L is the general Laguerre polynomial then I could simply use

from scipy.special import genlaguerre
print(genlaguerre(n, a))

However, I am having trouble obtaining something like L(n, a, 2 pi x) since  there is no explicit variable dependence in the function genlaguerre.

Body:
The object returned by genlaguerre(n, a) is callable; you call it to evaluate it at a given x.

For example,

In [71]: import numpy as np

In [72]: import matplotlib.pyplot as plt

In [73]: from scipy.special import genlaguerre

In [74]: n = 3

In [75]: alpha = 4.5

In [76]: L = genlaguerre(n, alpha)

To get the value of the polynomial at x, call L(x):

In [77]: L(0)
Out[77]: 44.6875

In [78]: L(1)
Out[78]: 23.895833333333332

In [79]: L([2, 2.5, 3])
Out[79]: array([ 9.60416667,  4.58333333,  0.8125    ])

In [80]: x = np.linspace(0, 14, 100)

In [81]: plt.plot(x, L(x))
Out[81]: [<matplotlib.lines.Line2D at 0x11cde42b0>]

In [82]: plt.xlabel('x')
Out[82]: <matplotlib.text.Text at 0x11cddc4a8>

In [83]: plt.ylabel('$L_{%d}^{(%g)}(x)$' % (n, alpha))
Out[83]: <matplotlib.text.Text at 0x11cdce320>

In [84]: plt.grid()

Here's the plot generated by the above code:


问:
Storing and checking a boolean in a python class
So I was trying to create an object which basically has a constructor that takes two coordinates, xcoord and ycoord. I further created methods which shift the coordinates and I have to check if the point is valid or not(criteria for validity is if the coordinates are out of a specified range it should return False else True).

Problem:

My class only returns the validity for the initial points, not the shifted points.

What do I need to correct my code?

Code:

```<code>class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True
    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY
</code>```

Test Code:

I tried my code and it only returns the isValidFunction variable for my initial points (gives me True instead of False for following code)

```<code>p=Point(9,2)
p.translateX(20)
p.translateY(10)
p.isValidPt
</code>```

答:
Constructor is used basically for initiate the values. In your case the constructor checks the initial value and set  the validate flag. ie, isValidPt.
It will be True for the scope of p object you created. So you have to create  a validate function and call the validate function on both init and shift functions.
Check the following

```<code>class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        self.validate()

    def validate(self):
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True

    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
        self.validate()
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY
        self.validate()
</code>```

in the above code each time the validation will perform and update the values
of isValidPt.

Body:
So I was trying to create an object which basically has a constructor that takes two coordinates, xcoord and ycoord. I further created methods which shift the coordinates and I have to check if the point is valid or not(criteria for validity is if the coordinates are out of a specified range it should return False else True).

Problem:

My class only returns the validity for the initial points, not the shifted points.

What do I need to correct my code?

Code:

class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True
    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY

Test Code:

I tried my code and it only returns the isValidFunction variable for my initial points (gives me True instead of False for following code)

p=Point(9,2)
p.translateX(20)
p.translateY(10)
p.isValidPt

Body:
Constructor is used basically for initiate the values. In your case the constructor checks the initial value and set  the validate flag. ie, isValidPt.
It will be True for the scope of p object you created. So you have to create  a validate function and call the validate function on both init and shift functions.
Check the following

class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        self.validate()

    def validate(self):
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True

    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
        self.validate()
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY
        self.validate()

in the above code each time the validation will perform and update the values
of isValidPt.


问:
Signal when new serial port is present
Is there a cross platform way to receive a signal (or other notification) in Qt, when a new serial port device becomes present, or one that was present before becomes absent? This is a simple case of getting to know when someone connected a new USB to serial port converter (discovering COM ports in windows and ttyS in linux). My only idea now is to periodically (for example using QTimer) run the QSerialPortInfo routines. Is there a way to accomplish this with event driven system? I would appreciate all help.

答:
As of Qt 5.9, there is no such cross-platform way.

Whatever you'll do will be platform-specific.

Title: Signal when new serial port is present


问:
Creating security groups for a custom module in odoo 10
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">
   <!-- Creating a Group Category -->
   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>
   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>
</code>```

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

```<code><menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>
</code>```

Then in csv file of my security folder I added this :

```<code>id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1
</code>```

When I updated my module I have an error saying "csv file could not be proccessed"

```<code>In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
</code>```

The link to my previous question.

答:
You have given ir.model.access file before security.xml file, that's why it is giving you error

You have to change following points :

In manifest.py file, add security.xml file before ir.model.access.csv file.

In group you have given

In implied_ids, base.group_sale_manager is given, but in Odoo v10, that group is defined in sales_team module, so external id of that group is "sales_team.group_sale_manager".

Here's

```<code><record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>
   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation_subj"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('sales_team.group_sale_manager'))]"/>
   </record>
</code>```

Body:
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">

   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>

   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>

       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

<menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>

Then in csv file of my security folder I added this :

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1

When I updated my module I have an error saying "csv file could not be proccessed"

In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.

The link to my previous question.

Body:
You have given ir.model.access file before security.xml file, that's why it is giving you error

You have to change following points :

In manifest.py file, add security.xml file before ir.model.access.csv file.

In group you have given

In implied_ids, base.group_sale_manager is given, but in Odoo v10, that group is defined in sales_team module, so external id of that group is "sales_team.group_sale_manager".

Here's

<record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>
   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation_subj"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('sales_team.group_sale_manager'))]"/>
   </record>


问:
Exec function in c is not running
This is not running on my Mac for some reasons that I can't figure out. the output I am getting is only from the main.c
the output is

```<code>Parent PID 4066
Child PID 4067
Process 4067 exited with status 5
</code>```

I need the main.c to execute counter.c and pass the argument 5 which I will then have to use it inside the for a loop, but I can't get exec to run at all no matter what path I put.

//main.c

```<code>int main(int argc, char *argv[]) {

    pid_t childOrZero = fork();

    if (childOrZero < 0){
        perror("Error happened while trying to fork\n");
        exit(-1);
    }

    if (childOrZero == 0){
        printf("Child PID %d\n", (int)getpid());
        execl("./counter", "5", NULL);
        exit(5);
    }

    // THis must be parent
    printf("Parent PID %d\n", (int)getpid());
    int status = 0;
    pid_t childpid = wait(&status);
    int childReturnedValue = WEXITSTATUS(status);
    printf("Process %d exited with status %d\n", (int)childOrZero, childReturnedValue);

    return 0;
}
</code>```

counter.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main (int argc, char *argv[]){
    for (int i = 0; i<5; i++){
        printf("Process: %d  %d\n", (int)getpid(),i);
        //sleep(3);
    }
}
</code>```

答:
In a comment, you mention you compile counter.c into an executable called a.out. This is the default executable name when you do not provide an output name explicitly to the compiler. Thus, if you compile both counter.c and main.c, only one of them will be the a.out.

You can provide gcc an option to name your executable different from the default:

gcc -o counter counter.c

Also, your invocation of execl is not quite correct. The first argument is the path to the executable, but the remaining arguments will become argv[0], argv[1], etc. Thus, you really want to invoke execl this way:

```<code>     execl("./counter", "counter", "5", NULL);
</code>```

Title: Exec function in c is not running

Body:
This is not running on my Mac for some reasons that I can't figure out. the output I am getting is only from the main.c
the output is

Parent PID 4066
Child PID 4067
Process 4067 exited with status 5

I need the main.c to execute counter.c and pass the argument 5 which I will then have to use it inside the for a loop, but I can't get exec to run at all no matter what path I put.

//main.c

int main(int argc, char *argv[]) {

    pid_t childOrZero = fork();

    if (childOrZero < 0){
        perror("Error happened while trying to fork\n");
        exit(-1);
    }

    if (childOrZero == 0){
        printf("Child PID %d\n", (int)getpid());
        execl("./counter", "5", NULL);
        exit(5);
    }

    // THis must be parent
    printf("Parent PID %d\n", (int)getpid());
    int status = 0;
    pid_t childpid = wait(&status);
    int childReturnedValue = WEXITSTATUS(status);
    printf("Process %d exited with status %d\n", (int)childOrZero, childReturnedValue);

    return 0;
}

counter.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main (int argc, char *argv[]){
    for (int i = 0; i<5; i++){
        printf("Process: %d  %d\n", (int)getpid(),i);
        //sleep(3);
    }
}

Body:
In a comment, you mention you compile counter.c into an executable called a.out. This is the default executable name when you do not provide an output name explicitly to the compiler. Thus, if you compile both counter.c and main.c, only one of them will be the a.out.

You can provide gcc an option to name your executable different from the default:

gcc -o counter counter.c

Also, your invocation of execl is not quite correct. The first argument is the path to the executable, but the remaining arguments will become argv[0], argv[1], etc. Thus, you really want to invoke execl this way:

     execl("./counter", "counter", "5", NULL);


问:
Fastest way to learn Zend Framework?
If you already have a website design in mind and want to just use Zend Framework's modules (mainly the one's for security and performance) how would you go about learning Zend for rapid web development?

答:
http://framework.zend.com/manual/en/learning.quickstart.intro.html

Sample code, an example starter project, lots of documentation; the Zend Framework manual is one of my constantly open browser tabs.

Title: Fastest way to learn Zend Framework?


问:
How to render custom label colors for different xAxis labels?
I'm creating a chart using Charts library to draw a combined chart in  my app.

I succeeded in drawing the graph. Now I want to change the xAxis label text color of specific labels. The example was shown in the pic.

As in the picture I want to change the color of specific values for example 03/06 & 06/06. When I referred the library on github they told me to override the drawValues() function to achieve this. As I'm newbie to swift programming I don't know how to achieve this. Please guide me on how to achieve this task. Thanks in advance.

答:
there is below method in XAxisRendererHorizontalBarChart.swift file of charts library. It will set the text for xAxis. You can customize it according to your use case.

```<code>open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
</code>```

Body:
there is below method in XAxisRendererHorizontalBarChart.swift file of charts library. It will set the text for xAxis. You can customize it according to your use case.

open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)


问:
Using form authentication and Azure AD login in same mvc application
I am using mvc application with azure AD login option(OpenId Authentication). i need to provide impersonation option for Admins. so i have decided to use form authentication for this impersonation login. now my problem is when enabling form authentication in webconfig affects azure AD login. once added form authentication it will show redirect continously with the belo url,
http://localhost:9666/members/logon?ReturnUrl=%2fmembers%2flogonusingazure%3freturnUrl%3d%2f&returnUrl=/

code used in web config for form authentication.

```<code><authentication mode="Forms">
      <forms loginUrl="~/members/logon" cookieless="UseCookies" name="MvcForumAuth" slidingExpiration="true" timeout="432000" />
    </authentication>
</code>```

Thanks,
Nagaraj M.

答:
Forms authentication is old version of the authentication framework for ASP.NET, The default template for ASP.NET MVC in the latest version of Visual Studio has an implementation of ASP.NET Identity Framework .

You could try using OWIN CookieAuthentication and ASP.NET identity to handle the local authentication with OpenIdConnect for the AzureAD authentication.

To use asp.net identity , if you generate a new MVC project using Individual accounts for authentication you can see the auto generated code for the Startup class in addition to the Account controller which has Login Actions for both Direct Authentication and ExternalLogin (3rd party).

Then you could use the ASP.Net OpenID Connect OWIN middleware to sign-in users from Azure Active Directory tenant :

install the Microsoft.Owin.Security.OpenIdConnect library in NuGet .

in Startup class , set OpenIdConnect pipeline :

```<code>app.UseOpenIdConnectAuthentication(
  new OpenIdConnectAuthenticationOptions
  {
      ClientId = clientId,
      Authority = Authority,
      PostLogoutRedirectUri = postLogoutRedirectUri,
      RedirectUri = postLogoutRedirectUri,
      Notifications = new OpenIdConnectAuthenticationNotifications
      {
          AuthenticationFailed = context =>
          {
              context.HandleResponse();
              context.Response.Redirect("/Error?message=" + context.Exception.Message);
              return Task.FromResult(0);
          }
      }
  });
</code>```

Now you could login into your app with local identity account and azure ad accounts as external user :

In addition , you need to set <authentication mode="none" /> in the web.config to let OWIN take over the Authentication/Authorization process for your application from IIS.

Body:
I am using mvc application with azure AD login option(OpenId Authentication). i need to provide impersonation option for Admins. so i have decided to use form authentication for this impersonation login. now my problem is when enabling form authentication in webconfig affects azure AD login. once added form authentication it will show redirect continously with the belo url,
http://localhost:9666/members/logon?ReturnUrl=%2fmembers%2flogonusingazure%3freturnUrl%3d%2f&returnUrl=/

code used in web config for form authentication.

<authentication mode="Forms">
      <forms loginUrl="~/members/logon" cookieless="UseCookies" name="MvcForumAuth" slidingExpiration="true" timeout="432000" />
    </authentication>

Thanks,
Nagaraj M.

Body:
Forms authentication is old version of the authentication framework for ASP.NET, The default template for ASP.NET MVC in the latest version of Visual Studio has an implementation of ASP.NET Identity Framework .

You could try using OWIN CookieAuthentication and ASP.NET identity to handle the local authentication with OpenIdConnect for the AzureAD authentication.

To use asp.net identity , if you generate a new MVC project using Individual accounts for authentication you can see the auto generated code for the Startup class in addition to the Account controller which has Login Actions for both Direct Authentication and ExternalLogin (3rd party).

Then you could use the ASP.Net OpenID Connect OWIN middleware to sign-in users from Azure Active Directory tenant :

install the Microsoft.Owin.Security.OpenIdConnect library in NuGet .

in Startup class , set OpenIdConnect pipeline :

app.UseOpenIdConnectAuthentication(
  new OpenIdConnectAuthenticationOptions
  {
      ClientId = clientId,
      Authority = Authority,
      PostLogoutRedirectUri = postLogoutRedirectUri,
      RedirectUri = postLogoutRedirectUri,
      Notifications = new OpenIdConnectAuthenticationNotifications
      {
          AuthenticationFailed = context =>
          {
              context.HandleResponse();
              context.Response.Redirect("/Error?message=" + context.Exception.Message);
              return Task.FromResult(0);
          }
      }
  });

Now you could login into your app with local identity account and azure ad accounts as external user :

In addition , you need to set <authentication mode="none" /> in the web.config to let OWIN take over the Authentication/Authorization process for your application from IIS.


问:
How to add two imageview and display as single image on button click
I need this imageviews to be combined and display as new image view

I have tried to merge the both imageviews but the images are not getting merged as a single image.

this image should be the frame and another image should be in the blank space

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    collageImage = (ImageView)findViewById(R.id.center);
    Button combineImage = (Button)findViewById(R.id.Btn_comineimage);
    combineImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.multiple);
            smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.multipletwo);
            mergeimage();//merge and display on click.

        }
    });

}

public void mergeimage()
{
    //need code for combining both image to one and setimagebitmap to collageimage.

}
</code>```

Main.xml

Here I have attached my xml coding for your reference.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/Main_layout"
tools:context="com.imagemerge.albin.imagemerge.MainActivity">
<ImageView
android:id="@+id/base"
android:layout_height="200dp"
android:layout_width="200dp"
android:src="@drawable/multiple"
android:scaleType="fitXY"
android:layout_alignTop="@+id/center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="@+id/center"
android:layout_height="180dp"
android:layout_width="85dp"
android:src="@drawable/multipletwo"
android:layout_marginLeft="230dp"
android:layout_marginTop="15dp"
android:scaleType="fitXY"/>
<Button
android:id="@+id/Btn_comineimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/center"
android:layout_alignRight="@+id/center"
android:layout_below="@+id/base"
android:layout_marginEnd="89dp"
android:layout_marginRight="89dp"
android:layout_marginTop="10dp"
android:text="Merge" />
<ImageView
android:id="@+id/Mergedimage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@+id/Btn_comineimage"
android:layout_marginLeft="100dp"
android:background="@color/colorAccent"
android:scaleType="fitXY"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
</code>```

答:
You can use FrameLayout. Check below link for more details:

https://developer.android.com/reference/android/widget/FrameLayout.html

Using FrameLayout you can add one element on other.

Body:
I need this imageviews to be combined and display as new image view

I have tried to merge the both imageviews but the images are not getting merged as a single image.

this image should be the frame and another image should be in the blank space

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    collageImage = (ImageView)findViewById(R.id.center);
    Button combineImage = (Button)findViewById(R.id.Btn_comineimage);
    combineImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.multiple);
            smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.multipletwo);
            mergeimage();//merge and display on click.

        }
    });

}

public void mergeimage()
{
    //need code for combining both image to one and setimagebitmap to collageimage.

}

Main.xml

Here I have attached my xml coding for your reference.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/Main_layout"
tools:context="com.imagemerge.albin.imagemerge.MainActivity">
<ImageView
android:id="@+id/base"
android:layout_height="200dp"
android:layout_width="200dp"
android:src="@drawable/multiple"
android:scaleType="fitXY"
android:layout_alignTop="@+id/center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="@+id/center"
android:layout_height="180dp"
android:layout_width="85dp"
android:src="@drawable/multipletwo"
android:layout_marginLeft="230dp"
android:layout_marginTop="15dp"
android:scaleType="fitXY"/>
<Button
android:id="@+id/Btn_comineimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/center"
android:layout_alignRight="@+id/center"
android:layout_below="@+id/base"
android:layout_marginEnd="89dp"
android:layout_marginRight="89dp"
android:layout_marginTop="10dp"
android:text="Merge" />
<ImageView
android:id="@+id/Mergedimage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@+id/Btn_comineimage"
android:layout_marginLeft="100dp"
android:background="@color/colorAccent"
android:scaleType="fitXY"
android:layout_marginTop="10dp"
/>
</RelativeLayout>


问:
How to get the user "Name" using Swift?
I'm trying to create an app that when the user open the first view it will provide with a nice greeting.

For example depending on the time of the day it would say "Good Morning/Afternoon/Night - User Name".

How do I get the name that the User has on his iPhone? I need the name that is on Settings > General > About _ NAME?

答:
UIDevice.current.name gives back device name, so you should parse the string trying to distinguish between device type (iPhone, iPad and so on...) and the name.
But is  bit tricky: suppose You have "My iPhone" , "Mary's iPhone" or "IPhone of John" or similar.

Soem people try to use regular expressions, but result is not so good, specially for non-english names.
see at:

http://stackoverflow.com/questions/8261961/better-way-to-get-the-users-name-from-device

Title: How to get the user "Name" using Swift?


问:
How to print piecewise functions in GNU Octave
How does one print out a piecewise function in GNU Octave in a human readable way?

Somehow produce output similar to this in either the console or a file: x^(4) + x^(3) + x^(2) + x + 1 for each polynomial in the piecewise function.

答:
You can use fprintf in MATLAB to write the polynomial you want into a file. Check the below code:

```<code>str = 'x^(4) + x^(3) + x^(2) + x + 1' ;
fid = fopen('check.txt','w') ;
fprintf(fid,'%s\n',str) ;
fclose(fid) ;
</code>```

Body:
You can use fprintf in MATLAB to write the polynomial you want into a file. Check the below code:

str = 'x^(4) + x^(3) + x^(2) + x + 1' ;
fid = fopen('check.txt','w') ;
fprintf(fid,'%s\n',str) ;
fclose(fid) ;


问:
Woocommerce allow html in short description on category page
I am adding short description (excerpts) of a product on the category page but I can't get the html tags in the excerpts to work. Strangely they work in the single product page. Given below is the function I'm using, just in case. I'm using understrap theme framework for wordpress.

```<code>function woocommerce_after_shop_loop_item_title_short_description() {
    global $product;
    if ( ! $product->post->post_excerpt ) return;
    ?>
    <div itemprop="description">
        <?php echo apply_filters( 'woocommerce_short_description', $product->post->post_excerpt ) ?>
    </div>
    <?php
}
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_after_shop_loop_item_title_short_description', 5);
</code>```

This is the output that I'm getting:

```<code><p>lorem lipsum losem</p>
</code>```

This is the output that I desire (this is what I've added in the short description box on woocommerce product backend):

```<code><ul>
    <li> lorem </li>
    <li> lipsum </li>
    <li> losem </li>
</ul>
</code>```

答:
```<code>foreach ( array( 'pre_term_description' ) as $filter ) {
    remove_filter( $filter, 'wp_filter_kses' );
}

foreach ( array( 'term_description' ) as $filter ) {
    remove_filter( $filter, 'wp_kses_data' );
}
</code>```

Try by adding this snippet to your active child theme's functions.php

ContentLicense: CC BY-SA 4.0

Body:
I am adding short description (excerpts) of a product on the category page but I can't get the html tags in the excerpts to work. Strangely they work in the single product page. Given below is the function I'm using, just in case. I'm using understrap theme framework for wordpress.

function woocommerce_after_shop_loop_item_title_short_description() {
    global $product;
    if ( ! $product->post->post_excerpt ) return;
    ?>

        <?php echo apply_filters( 'woocommerce_short_description', $product->post->post_excerpt ) ?>

    <?php
}
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_after_shop_loop_item_title_short_description', 5);

This is the output that I'm getting:

lorem lipsum losem

This is the output that I desire (this is what I've added in the short description box on woocommerce product backend):

 lorem

 lipsum

 losem

Body:
foreach ( array( 'pre_term_description' ) as $filter ) {
    remove_filter( $filter, 'wp_filter_kses' );
}

foreach ( array( 'term_description' ) as $filter ) {
    remove_filter( $filter, 'wp_kses_data' );
}

Try by adding this snippet to your active child theme's functions.php


问:
Laravel 5.4 query check if value exists between the keys/values of an array
I'm using Laravel 5.4 and this is my use case:

I have a list of Lessons, every Lesson is associated with a specific User and has a date, star_at and end_at fields. In the form that allows me to add/edit Lessons I need to do a validation check ( we choose the date, start and end
 in the form ):
- The new Lesson shouldn't be in the time range (start_at -> end_at) of another Lesson during the selected date.

So I did a query to retrieve all the Lessons ( as an array of key(start_at) & value(end_at) ) of the current User where date = the selected date in the form.

Now I need to check if the start_at value that we've chosen in the form exists in the time range of any of the retrieved Lessons array records. and maybe then display the error ( There is already a Lesson in this time range at this date ).

Please help, it can be a bit unclear, but I can explain further if you need.

Thank you in advance.

答:
Based on my understanding of the question, the below code should do the trick. Change the model and field names based on your application.</p>

```<code>protected function store()
{
    $input = request()->all();

    $lessons = Lesson::whereDate('date', Carbon::parse($input['date']))
        ->where('start_at', '>=', Carbon::parse($input['start_at']))
        ->where('end_at', '<=', Carbon::parse($input['start_at']))
        ->count();

    if ($lessons) {
        // lesson in exists on this date in the given time frame.
        // handle error
    }

    Lesson::create($input);

    // handle success
}
</code>```

Body:
Based on my understanding of the question, the below code should do the trick. Change the model and field names based on your application.

protected function store()
{
    $input = request()->all();

    $lessons = Lesson::whereDate('date', Carbon::parse($input['date']))
        ->where('start_at', '>=', Carbon::parse($input['start_at']))
        ->where('end_at', '<=', Carbon::parse($input['start_at']))
        ->count();

    if ($lessons) {
        // lesson in exists on this date in the given time frame.
        // handle error
    }

    Lesson::create($input);

    // handle success
}


问:
simple implemented method for human silhouette extraction (python,opencv)
Is there any simple implemented method for human silhouette extraction in OpenCV? The method can be work only for video.

Here is a sample frame:

答:
For images like these, OpenCV's HOG (Histogram of Oriented Gradients) works very well. And example can be found here. The example is in python, but it is not hard to create a C++ version if you want. The trained parameters are already there, so you can use it immediately.

If you are interested in deep learning based approaches, both SSD (Single Shot Multiple Box Detector) and YOLO (You Only Look Once) can detect persons.

All these methods can only exact a bounding box. For extracting the exact silhouette, you will need to combine the results with image differencing or background subtraction.


问:
finishActivityAffinity NullPointerException
Am getting this Error in production. When calling finishAffinity in splashscreen.

答:
Just surround it by try case:</p>

```<code> try {
        ActivityCompat.finishAffinity(this);
      } catch (IllegalStateException e) {
        finish();
      }
</code>```

Body:
Just surround it by try case:

 try {
        ActivityCompat.finishAffinity(this);
      } catch (IllegalStateException e) {
        finish();
      }


问:
Session Variable lost in iFrame asp.net
I have session variable that is created in EditPlaylist.aspx.  Edit.aspx is loading EditPlaylist.aspx in an iframe.

when loading sessions from EditPlaylist.aspx page they are null.

the session was not before I added the  EditPlaylist.aspx to an iFrame.  Is there a workaround for this?

答:
If its running under IIS , how many workers processes do you have ?
if more than 1 - you have to share your session over all instances .</p>

Title: Session Variable lost in iFrame asp.net


问:
Coding a Scatter plot with smooth lines in VBA
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

```<code>Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines
</code>```

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?

答:
You may try something like this...

```<code>Sub CreateChart()
Dim wsData As Worksheet, wsChart As Worksheet
Dim LastRow As Long
Dim xData As Range, yData As Range, GraphRange As Range
Dim cht As Shape

Application.ScreenUpdating = False

Set wsChart = Sheets(1)
Set wsData = Sheets(2)
LastRow = wsData.Cells(Rows.Count, 1).End(xlUp).Row
Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow)

Set GraphRange = Union(xData, yData)

'Create a chart
Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2(, xlXYScatterLinesNoMarkers)

'Give chart some data
cht.Chart.SetSourceData Source:=GraphRange
cht.Chart.FullSeriesCollection(1).Format.Line.Weight = 5
Application.ScreenUpdating = True
End Sub
</code>```

Body:
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?

Body:
You may try something like this...

Sub CreateChart()
Dim wsData As Worksheet, wsChart As Worksheet
Dim LastRow As Long
Dim xData As Range, yData As Range, GraphRange As Range
Dim cht As Shape

Application.ScreenUpdating = False

Set wsChart = Sheets(1)
Set wsData = Sheets(2)
LastRow = wsData.Cells(Rows.Count, 1).End(xlUp).Row
Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow)

Set GraphRange = Union(xData, yData)

'Create a chart
Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2(, xlXYScatterLinesNoMarkers)

'Give chart some data
cht.Chart.SetSourceData Source:=GraphRange
cht.Chart.FullSeriesCollection(1).Format.Line.Weight = 5
Application.ScreenUpdating = True
End Sub


问:
How to get CNN kernel values in Tensorflow
I am using the code below to create CNN layers.

```<code>conv1 = tf.layers.conv2d(inputs = input, filters = 20, kernel_size = [3,3],
    padding = "same", activation = tf.nn.relu)
</code>```

and I want to get the values of all kernels after training. It does not work it I simply do

```<code>kernels = conv1.kernel
</code>```

So how should I retrieve the value of these kernels? I am also not sure what variables and method does conv2d has since tensorflow don't really tell it in conv2d class.

答:
You can find all the variables in list returned by tf.global_variables() and easily lookup for variable you need.

If you wish to get these variables by name, declare a layer as:

```<code>conv_layer_1 = tf.layers.conv2d(activation=tf.nn.relu,
                                filters=10,
                                inputs=input_placeholder,
                                kernel_size=(3, 3),
                                name="conv1",         # NOTE THE NAME
                                padding="same",
                                strides=(1, 1))
</code>```

Recover the graph as:

```<code>gr = tf.get_default_graph()
</code>```

Recover the kernel values as:

```<code>conv1_kernel_val = gr.get_tensor_by_name('conv1/kernel:0').eval()
</code>```

Recover the bias values as:

```<code>conv1_bias_val = gr.get_tensor_by_name('conv1/bias:0').eval()
</code>```

Body:
I am using the code below to create CNN layers.

conv1 = tf.layers.conv2d(inputs = input, filters = 20, kernel_size = [3,3],
    padding = "same", activation = tf.nn.relu)

and I want to get the values of all kernels after training. It does not work it I simply do

kernels = conv1.kernel

So how should I retrieve the value of these kernels? I am also not sure what variables and method does conv2d has since tensorflow don't really tell it in conv2d class.

Body:
You can find all the variables in list returned by tf.global_variables() and easily lookup for variable you need.

If you wish to get these variables by name, declare a layer as:

conv_layer_1 = tf.layers.conv2d(activation=tf.nn.relu,
                                filters=10,
                                inputs=input_placeholder,
                                kernel_size=(3, 3),
                                name="conv1",         # NOTE THE NAME
                                padding="same",
                                strides=(1, 1))

Recover the graph as:

gr = tf.get_default_graph()

Recover the kernel values as:

conv1_kernel_val = gr.get_tensor_by_name('conv1/kernel:0').eval()

Recover the bias values as:

conv1_bias_val = gr.get_tensor_by_name('conv1/bias:0').eval()


问:
Can't find my.ini (mysql 5.7)
I've installed MySQL 5.7 and I'm trying to change the default setting written in my.ini file.

So, I followed the path that I found in Stackoverflow (MySQL\MySQL Server 5.7).

However, what I found was only a few folders, but not my.ini file.
I searched every folder, but I couldn't find it. Where is it?

答:
If you're in Linux there's an easy way of finding any file if you know the filename.

```<code>$ locate <filename>
</code>```

But before using the above command you may need to update your file database. You may do so using

```<code>$ sudo updatedb
</code>```

In windows the search bar gives you the option to locate files.

Title: Can't find my.ini (mysql 5.7)

Body:
If you're in Linux there's an easy way of finding any file if you know the filename.

$ locate <filename>

But before using the above command you may need to update your file database. You may do so using

$ sudo updatedb

In windows the search bar gives you the option to locate files.


问:
Way to shrink Resources folder?
I have 100 pictures in my Resources folder and they can really be annoying when trying to find some other resource. Is there a way I could "create another resource folder" to put the 100 pictures in?

Or do I just have to deal with scrolling and scrolling when trying to find another resource?

答:
I totally agree with @quixoto ans,

one thing more you can categories your folders according to any visible form.And use proper hierarchy for folders.because when you having number of folder and files then this necessary to make hierarchy also naming conventions are necessary for quick understanding and quick search. (e.g. Make images folder for images and in this folder sub folders, for backgrond image,button images,tab images etc.).so it helps you in quick search.

Title: Way to shrink Resources folder?


问:
Firebase Storage very slow compared to Firebase Hosting
Anyone know why firebase storage would be so ridiculously slow compared to firebase hosting?

Results

Time to download image of firebase hosting: 16ms

Time to download same image from firebase storage: 2.23s (2.22s is TTFB)

Time to download same image from firebase storage (Asia Pacific Region): 1.72s (1.70s is TTFB)

(File size: 22.7kb / jpeg / firebase storage has read open to everyone)

This is repeated over and over in tests. Is there any way to speed this up to a decent time, or is firebase storage unusable for small files (images/thumbs)?

For Comparison

S3 North Cal - approximately 500ms

S3 Asia Pacific - Approximately 30ms

Cloudinary - Approximately 20ms

Extra info:

I am based in Australia.

Exact same files. Always images under 100kb.

The slow down is always in the TTFB according to dev tools.

Hosting URL: https://.firebaseapp.com/images/thumb.jpg

Storage URL: https://firebasestorage.googleapis.com/v0/b/.appspot.com/o/thumb.jpg?alt=media&token=

答:
I found the solution.

If you have your files already uploaded to storage go to: https://console.cloud.google.com/storage/browser?project=your_project > pick your bucket > select all interesting files and click Make public (or something similar - I'm not english native).

To have all new uploaded files public by default you need to install Google cloud SDK (https://cloud.google.com/sdk/docs/) and from your command line use the following command for your bucket:

gsutil defacl set public-read gs://your_bucket

After that all my current and new images are available here storage.googleapis.com/my_project.appspot.com/img/image_name.jpg
and downloading time is definitely shorter.


问:
jQuery UI : Increase the padding on resizeable()
I want to know that is it possible to increase and decrease padding on resize instead of increase and decreasing the height.

```<code>$( function() {
    $( "#resizable" ).resizable({
        handles: 'n,s'
    });
 });
</code>```

Fiddle example

Update :

I actually want to know that if I resize the div I want to dynamically increase the padding on resize instead of height
Updated Fiddle

Try to resize the div from north and south position

答:
Yes its possible to include padding. Find the updated fiddle link.

```<code>div#resizable {
  height: 200px;
  width : 400px;
  background-color : aqua;
  padding: 0.5em;
}
</code>```

https://jsfiddle.net/h2cjsc5h/4/

Body:
I want to know that is it possible to increase and decrease padding on resize instead of increase and decreasing the height.

$( function() {
    $( "#resizable" ).resizable({
        handles: 'n,s'
    });
 });

Fiddle example

Update :

I actually want to know that if I resize the div I want to dynamically increase the padding on resize instead of height
Updated Fiddle

Try to resize the div from north and south position

Body:
Yes its possible to include padding. Find the updated fiddle link.

div#resizable {
  height: 200px;
  width : 400px;
  background-color : aqua;
  padding: 0.5em;
}

https://jsfiddle.net/h2cjsc5h/4/


问:
replace every second line of my triangle with a blank line for loops
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

```<code>  5

 555

55555
</code>```

This is my code:

```<code> for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}
</code>```

答:
Check this:

int num= 5; // 'num' denotes the number of lines

```<code>    int numOfSpaces;

    for(int i = 1; i <= num; i++) {
        if( i%2 != 0)  // checks whether the line number is odd. If odd, prints '*'
        {
            numOfSpaces = (num-i) / 2; // find the number of blank spaces
             for(int j = 1; j <= numOfSpaces; j++) {
                   System.out.print(" ");
               }
              for(int k = 1; k <= i; k++) {  // number of '*'s to be printed = current line number = i
                  System.out.print("*");
              }
                 System.out.println();
        }

        else{
              System.out.println(); // leaves every second line blank (ie.,if line number is even.)
       }

    }
</code>```

Body:
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

  5

 555

55555

This is my code:

 for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}

Body:
Check this:

int num= 5; // 'num' denotes the number of lines

    int numOfSpaces;

    for(int i = 1; i <= num; i++) {
        if( i%2 != 0)  // checks whether the line number is odd. If odd, prints '*'
        {
            numOfSpaces = (num-i) / 2; // find the number of blank spaces
             for(int j = 1; j <= numOfSpaces; j++) {
                   System.out.print(" ");
               }
              for(int k = 1; k <= i; k++) {  // number of '*'s to be printed = current line number = i
                  System.out.print("*");
              }
                 System.out.println();
        }

        else{
              System.out.println(); // leaves every second line blank (ie.,if line number is even.)
       }

    }


问:
Firebase Push Notification - XCode 8.0 / Swift 3.0/ ios 10.0
I'm using Firebase for Push Notifications.

In didRegisterForRemoteNotificationsWithDeviceToken, I have following line :

```<code>FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
</code>```

I get the following error message :

Cannot convert value of type 'Data' to expected argument type 'Data'.

答:
Update your Firebase SDK to 4.0.0 and add the following code :

```<code> func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        Messaging.messaging().apnsToken = deviceToken

        let firebaseAuth = Auth.auth()
        // .sandbox is used during development, later on it can be changed to .prod

        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
 }
</code>```

Body:
I'm using Firebase for Push Notifications.

In didRegisterForRemoteNotificationsWithDeviceToken, I have following line :

FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)

I get the following error message :

Cannot convert value of type 'Data' to expected argument type 'Data'.

Body:
Update your Firebase SDK to 4.0.0 and add the following code :

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        Messaging.messaging().apnsToken = deviceToken

        let firebaseAuth = Auth.auth()
        // .sandbox is used during development, later on it can be changed to .prod

        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
 }


问:
Mantis bugnotes formatting
Is it possible to format bugnotes(comments) entered in Mantis bug tracker for an issue ?

I am using Mantis v1.0.8

e.g.

"sample mantis bug notes"

which appears as plain text.

I would like to make it bold  or to display in different color

e.g. similar to https://stackoverflow.com/editing-help

does any other bug tracking system allow such feature ?

答:
In Mantis one can use some of HTML tags (unfortunately not all are supported). From my experience (as I remember well) I've successfully used: , , <U>, <S> and lists, both ordered

 and unordered (bullets):

. It makes notes and descriptions more readable.

Currently I'm using 1.1.8 version of Mantis but I was successfully using it in older version (prior to 1.0) - so yours should also handle that.

Title: Mantis bugnotes formatting

Body:
In Mantis one can use some of HTML tags (unfortunately not all are supported). From my experience (as I remember well) I've successfully used: <B>, <I>, <U>, <S> and lists, both ordered <OL><LI> and unordered (bullets): <UL><LI>. It makes notes and descriptions more readable.

Currently I'm using 1.1.8 version of Mantis but I was successfully using it in older version (prior to 1.0) - so yours should also handle that.


问:
Unable to calculate the ETA and directions using iOS mapkit for chinese poi's
Currently, my application has a feature of displaying the ETA and directions(mapkit framework provided by apple) between two locations/poi's. but when we test this feature by passing some Chinese POI's, i always get the error saying directions not available for this location. I had even verified the map features support page from apple and china is listed under directions features.
So how can i identify as what causes this issue? </p>

答:
Actually, i had figured out the issue.
The problem, was with the accessibility of the chinese data outside china. The mapkit api's worked pretty well when tested inside china with Chinese Network.</p>


问:
Passport Node(Error: Failed to deserialize user out of session.)
I'm using Node.js, express, passport and MySQL.

Here is my deserialize code:

```<code>passport.deserializeUser(function(id, done) {
connection.query("select * from users where UserId = "+id,function(err,rows){
        console.log(rows);
        done(err, rows[0]);
    });
});
</code>```

Also, checked using console.log that "rows" is returning the row of the required user.

```<code>app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});
</code>```

答:
return the row </p>

```<code>    if(err){
        console.log(err);
        return done(null,err);
    }
    done(null, rows[0]); // return row[0]
</code>```

Body:
I'm using Node.js, express, passport and MySQL.

Here is my deserialize code:

passport.deserializeUser(function(id, done) {
connection.query("select * from users where UserId = "+id,function(err,rows){
        console.log(rows);
        done(err, rows[0]);
    });
});

Also, checked using console.log that "rows" is returning the row of the required user.

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

Body:
return the row

    if(err){
        console.log(err);
        return done(null,err);
    }
    done(null, rows[0]); // return row[0]


问:
Git branch is still on same line as master
I am getting something unexpected happening in the git tree. I have created a branch off of master, however while I am performing commits on the new branch it appears as though these are taking place in the same code line as master...

As you can see, on the very left hand side is the code line for master (dark blue) and right at the top we can see Sprint_15 which is a branch taken from master that appears to have commits on the same line... I am not sure why this is taking place. I would expect to see the code diverge into a new line since features are being merged into Sprint_15 and not master...

My thought is that by merging Sprint_14 and Sprint_15 together this has done something funky to the history but I am not sure why.

I am still fairly new to git so some of its underpinnings still confuse me.

答:
This is a speculation, but I suggest that the reason your current feature branch appears to be on the same line as master is because currently that branch is directly ahead of master by some number of commits.  To test this, try doing a pull on the latest master branch.  If this changes your configuration such that Sprint_15 appears as a separate line, then my hunch was correct.

In any case, you can always check such things directly from the Git bash if you are in doubt.


问:
Xamarin Forms: how to hide back button title?
In my Xamarin Forms iOS application the previous page name is also appearing with the back button in all pages. Is there any way to hide the title of the previous page?

答:
Adding to Cuckooshka answer, back button title gets hidden in landscape mode as </p>

```<code>UIBarButtonItem.Appearance.SetBackButtonTitlePositionAdjustment (new UIOffset (-100, -60), UIBarMetrics.LandscapePhone);
</code>```

Body:
Adding to Cuckooshka answer, back button title gets hidden in landscape mode as

UIBarButtonItem.Appearance.SetBackButtonTitlePositionAdjustment (new UIOffset (-100, -60), UIBarMetrics.LandscapePhone);


问:
Send custom error message in Ajax error in codeigniter
I am currently using Codeigniter and working on CRUD operation in one HTML form.
I am using Ajax for this create/read/update.

I have also used Transaction Management as best practices in a database query.

The Problem:

(1) I want separate Error message for Update and Insert Error. Which I did not get in the ajax error section.

(2) I have used the debugger to debug this problem but I do not get it proper.

Here is the Code of my controller.

Controller:

```<code>    public function save_candidate_experience() {
    $this->db->trans_start();

        if(empty($postId))){
            $query_staus = $this->test_model->insert_function( $data );

            if($query_staus != TRUE) {
                $msg = array('message'=>'Failed To Save! Erroe Wile Inserting.');
            } else{
                $msg = array('message'=>'Successfully Insert');
            }

        } else {
            $query_staus2 = $this->test_model->update_function( $data );
            if($query_staus2 != TRUE) {
                $msg = array('message'=>'Failed To Save! Erroe Wile Updateing.');
            }else{
                $msg = array('message'=>'Successfully Updated');
            }
        }

       if ($this->db->trans_status() === FALSE)
         {
           $this->db->trans_rollback();
           echo json_encode ($msg);
         }
      else
         {
           $this->db->trans_commit();
           echo json_encode ($msg);
         }
 }
</code>```

This is the Model Code:

```<code> public function insert_function() {

        $this->db->insert('table_name', $data);
            if($this->db->affected_rows() > 0){
                return TRUE;
            } else{
                return FALSE;
            }

 }

 public function update_function() {

        $this->db->where('id', $id);
        $this->db->update('test_table', $data);
            if($this->db->affected_rows() > 0){
                return TRUE;
            } else{
                return FALSE;
            }

 }
</code>```

Ajax Code in my view.

```<code>$.ajax({
     type: 'POST',
     async: true,
     dataType: 'Json',
     url: save_experience,
     data: $('#candidata_exp_form').serialize(),
     success: function (response) {
        //doing something with ajax success
     },error: function (msg)
     {
       alert(msg.message);
        // I know I can give alert message here but.
        //I don't want to give alert message here.
        //I want to indicate user that the error occure whilt insert or update seperately.
     }
});
</code>```

答:
You have to understand 2 things.

Form validation error and ajax error is different.

Ajax error - Is not validation error.
It means, suppose you call a function and there is php error in that function, or 404 error. At that time .error() will be called.

Ajax Success - No error(No syntax error).

So now you should write the logic in ajax success().

```<code>$.ajax({
    type: 'POST',
    async: true,
    dataType: 'Json',
    url: save_experience,
    data: $('#candidata_exp_form').serialize(),
    success: function (response) {
        alert(response.message);// this will alert you the message which you have put in `json_encode()`
    }
});
</code>```

Body:
I am currently using Codeigniter and working on CRUD operation in one HTML form.
I am using Ajax for this create/read/update.

I have also used Transaction Management as best practices in a database query.

The Problem:

(1) I want separate Error message for Update and Insert Error. Which I did not get in the ajax error section.

(2) I have used the debugger to debug this problem but I do not get it proper.

Here is the Code of my controller.

Controller:

    public function save_candidate_experience() {
    $this->db->trans_start();

        if(empty($postId))){
            $query_staus = $this->test_model->insert_function( $data );

            if($query_staus != TRUE) {
                $msg = array('message'=>'Failed To Save! Erroe Wile Inserting.');
            } else{
                $msg = array('message'=>'Successfully Insert');
            }

        } else {
            $query_staus2 = $this->test_model->update_function( $data );
            if($query_staus2 != TRUE) {
                $msg = array('message'=>'Failed To Save! Erroe Wile Updateing.');
            }else{
                $msg = array('message'=>'Successfully Updated');
            }
        }

       if ($this->db->trans_status() === FALSE)
         {
           $this->db->trans_rollback();
           echo json_encode ($msg);
         }
      else
         {
           $this->db->trans_commit();
           echo json_encode ($msg);
         }
 }

This is the Model Code:

 public function insert_function() {

        $this->db->insert('table_name', $data);
            if($this->db->affected_rows() > 0){
                return TRUE;
            } else{
                return FALSE;
            }

 }

 public function update_function() {

        $this->db->where('id', $id);
        $this->db->update('test_table', $data);
            if($this->db->affected_rows() > 0){
                return TRUE;
            } else{
                return FALSE;
            }

 }

Ajax Code in my view.

$.ajax({
     type: 'POST',
     async: true,
     dataType: 'Json',
     url: save_experience,
     data: $('#candidata_exp_form').serialize(),
     success: function (response) {
        //doing something with ajax success
     },error: function (msg)
     {
       alert(msg.message);
        // I know I can give alert message here but.
        //I don't want to give alert message here.
        //I want to indicate user that the error occure whilt insert or update seperately.
     }
});

Body:
You have to understand 2 things.

Form validation error and ajax error is different.

Ajax error - Is not validation error.
It means, suppose you call a function and there is php error in that function, or 404 error. At that time .error() will be called.

Ajax Success - No error(No syntax error).

So now you should write the logic in ajax success().

$.ajax({
    type: 'POST',
    async: true,
    dataType: 'Json',
    url: save_experience,
    data: $('#candidata_exp_form').serialize(),
    success: function (response) {
        alert(response.message);// this will alert you the message which you have put in `json_encode()`
    }
});


问:
align labels and textbox horizontally and veritcally
I am working on making a form as shown just like in this image but I am not able to figure out how can I align those labels and textbox vertically and horizontally in the same format shown in that image.

Here is my jsfiddle: https://jsfiddle.net/w6Lq9a1m/1/

And below is my simple HTML:

 INSURANCE FORM

 BASIC DETAILS

  <form action="/action_page.php">
    FIRST NAME

    <input type="text" name="fname" value="Mickey">

 LAST NAME

    <input type="text" name="lname" value="Mouse">

 EMAIL

    <input type="text" name="email" value="abc@host.com">

 PHONE NUMBER

    <input type="text" name="number" value="123-456-789">

 COUNTRY

    <select name="country">
      <option value="canada">Canada</option>
    </select>

 PROVINCE

    <select name="province">
      <option value="ontario">ONTARIO</option>
    </select>

 CITY

    <select name="city">
      <option value="ottawa">OTTAWA</option>
    </select>

  </form>

```

答:
Try this Without Bootstrap :

.left, .right {
   width: 45%;
   margin-bottom: 30px;
}

.left {
  float: left;
}

.right {
   float: right;
}

.hh {
   width: 45%;
   float: right;
}

.halfleft,.halfright {
   width: 45%;
}

.halfleft {
   float: left;
}

.halfright {
   float: right;
}

input[type='text'],select {
   width: 100%;
   border:none;
   border-bottom: 2px orange solid;
   margin-top: 3px;
   outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class ="row">
   <h2> INSURANCE FORM</h2>
   <h4> <i>BASIC DETAILS</i></h4>
   <form action="/action_page.php">
     <div class="left">
       FIRST NAME<br>
         <input type="text" name="fname" value="Mickey">
     </div>
     <div class="right">
       LAST NAME<br>
      <input type="text" name="lname" value="Mouse">
     </div>
      <div class="left">
       EMAIL<br>
      <input type="text" name="email" value="abc@host.com">
      </div>
      <div class="right">
       PHONE NUMBER<br>
      <input type="text" name="number" value="123-456-789">
      </div>
      <div class="left">
       COUNTRY<br>
      <select name="country">
         <option value="canada">Canada</option>
      </select>
      </div>
      <div class="hh">
      <div class="right halfleft">
        PROVINCE<br>
      <select name="province">
         <option value="ontario">ONTARIO</option>
      </select>
      </div>
      <div class="right halfright">
       CITY<br>
      <select name="city">
         <option value="ottawa">OTTAWA</option>
      </select>
      </div>
      </div>
   </form>
</div></code>```

Body:
Try this Without Bootstrap :

.left, .right {
   width: 45%;
   margin-bottom: 30px;
}

.left {
  float: left;
}

.right {
   float: right;
}

.hh {
   width: 45%;
   float: right;
}

.halfleft,.halfright {
   width: 45%;
}

.halfleft {
   float: left;
}

.halfright {
   float: right;
}

input[type='text'],select {
   width: 100%;
   border:none;
   border-bottom: 2px orange solid;
   margin-top: 3px;
   outline: none;
}

<div class ="row">
   <h2> INSURANCE FORM</h2>
   <h4> <i>BASIC DETAILS</i></h4>
   <form action="/action_page.php">
     <div class="left">
       FIRST NAME<br>
         <input type="text" name="fname" value="Mickey">
     </div>
     <div class="right">
       LAST NAME<br>
      <input type="text" name="lname" value="Mouse">
     </div>
      <div class="left">
       EMAIL<br>
      <input type="text" name="email" value="abc@host.com">
      </div>
      <div class="right">
       PHONE NUMBER<br>
      <input type="text" name="number" value="123-456-789">
      </div>
      <div class="left">
       COUNTRY<br>
      <select name="country">
         <option value="canada">Canada</option>
      </select>
      </div>
      <div class="hh">
      <div class="right halfleft">
        PROVINCE<br>
      <select name="province">
         <option value="ontario">ONTARIO</option>
      </select>
      </div>
      <div class="right halfright">
       CITY<br>
      <select name="city">
         <option value="ottawa">OTTAWA</option>
      </select>
      </div>
      </div>
   </form>
</div>