问:
serve public static files with webpack
I struggle to get webpack configured as I want it to be.
I run my dev-server on localhost:8080 and want to serve my app through localhost:8080/static/js/bundle.js and that is what I get with this webpack.config.js file I've attached below. in my file structure i've alse attached I want to serve also the other files located in dist/static as static files, so localhost:8080/static/css/style.css will be serving this dist/static/css/style.css file for example.

it is probably something wrong i did in the config file, and i'm not that familiar with webpack so i don't know if im asking the question so you can understand.

My directory tree is:

```<code>client
  -- /dist
    -- /templates
      -- /admin
        -- index.html
    -- /static
      -- /css
        -- style.css
      -- /js
  -- /node_modules
  -- /src
  -- /test
  -- package.json
  -- webpack.config.json
</code>```

webpack.config.js

```<code>var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var plugins = [
    new webpack.ProvidePlugin({
        'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
    }),
    new ExtractTextPlugin('app.css', {
        allChunks: true
    }),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
    })
];

var cssLoader = {};

if(process.env.NODE_ENV == 'production'){
    plugins.push(
        new webpack.optimize.UglifyJsPlugin()
    );

    cssLoader = {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
    };

} else {

    cssLoader = {
        test: /\.css$/,
        loaders: [
            'style?sourceMap',
            'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
        ]
    }

}

module.exports = {
    entry: [
        'react-hot-loader/patch',
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        './src/index.js'
    ],
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ['babel']
            },
            cssLoader
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    output: {
        path: __dirname + '/dist/static',
        publicPath: '/static/js',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: './dist/templates/admin',
        hot: true,
        historyApiFallback: true
    },
    plugins: plugins
};
</code>```

dist/templates/admin/index.html

```<code><!DOCTYPE html>
<html>
<head>
    <title>My App</title>
    <link href="static/css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="app"></div>
<script src="static/js/bundle.js"></script>
</body>
</html>
</code>```

thanks guys :)

答:
Problem

The origin of the problem is that the WebpackDevServer only serves from one folder. The folder that you should be serving from is the folder containing the index.html, which is what you're correctly doing.

So far you're serving only the content of ./dist/templates/admin, therefore when you look for files in other directories you get a 404. The only exception here is your bundle, because you're setting a publicPath that makes any request to the route /static/js be redirected to your output, which is stored in memory.

You would need the WebpackDevServer to be able to serve from other folders. In your specific case, you need to serve also from ./dist/static/css when you request the path /static/css.

Solution

You need to set some middlewares in your WebpackDevServer. You can do so as described in the documentation of devServer.setup. To do so, I suggest you use express.static, as you're probably already using Express.

You need to require Express:

```<code>const express = require('express')
</code>```

And then, just modify the devServer as follows:

```<code>devServer: {
  contentBase: './dist/templates/admin',
  hot: true,
  historyApiFallback: true,
  setup (app) {
    app.use('/static/css/',
      express.static(path.join(__dirname, 'dist', 'static', 'css')));
    /* Using this commented code will break the HMR, see edit
    app.use('/static/js/',
      express.static(path.join(__dirname, 'dist', 'static', 'js')));
    */

    // in general
    app.use('/public/route/',
      express.static('/your/local/path'));
  }
}
</code>```

This way your devs and build paths stay the same, and the WebpackDevServer serves the static files you need, at the routes you need.

Edit

I just discovered that the code above breaks the Hot Module Replacement. The reason is that the middleware in the setup is handling /static/js/, so the bundle is served from the file system instead of memory.

To keep fetching the bundle from memory define a publicPath in the output property, and don't handle it from a custom middleware inside devServer.setup.

```<code>module.exports = {

  output: {
    path: ...,
    filename: ...,
    publicPath: '/static/js/'
  },

  devServer: {
    contentBase: './dist/templates/admin',
    hot: true,
    historyApiFallback: true,
    setup (app) {
      app.use('/static/css/',
        express.static(path.join(__dirname, 'dist', 'static', 'css')));
    }
  },

  // other properties: entry, module, etc.
}
</code>```

Title: serve public static files with webpack

Body:
I struggle to get webpack configured as I want it to be.
I run my dev-server on localhost:8080 and want to serve my app through localhost:8080/static/js/bundle.js and that is what I get with this webpack.config.js file I've attached below. in my file structure i've alse attached I want to serve also the other files located in dist/static as static files, so localhost:8080/static/css/style.css will be serving this dist/static/css/style.css file for example.

it is probably something wrong i did in the config file, and i'm not that familiar with webpack so i don't know if im asking the question so you can understand.

My directory tree is:

client
  -- /dist
    -- /templates
      -- /admin
        -- index.html
    -- /static
      -- /css
        -- style.css
      -- /js
  -- /node_modules
  -- /src
  -- /test
  -- package.json
  -- webpack.config.json

webpack.config.js

var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var plugins = [
    new webpack.ProvidePlugin({
        'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
    }),
    new ExtractTextPlugin('app.css', {
        allChunks: true
    }),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
    })
];

var cssLoader = {};

if(process.env.NODE_ENV == 'production'){
    plugins.push(
        new webpack.optimize.UglifyJsPlugin()
    );

    cssLoader = {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
    };

} else {

    cssLoader = {
        test: /\.css$/,
        loaders: [
            'style?sourceMap',
            'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
        ]
    }

}

module.exports = {
    entry: [
        'react-hot-loader/patch',
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        './src/index.js'
    ],
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ['babel']
            },
            cssLoader
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    output: {
        path: __dirname + '/dist/static',
        publicPath: '/static/js',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: './dist/templates/admin',
        hot: true,
        historyApiFallback: true
    },
    plugins: plugins
};

dist/templates/admin/index.html

<!DOCTYPE html>

    <title>My App</title>
    <link href="static/css/style.css" type="text/css" rel="stylesheet" />

thanks guys :)

Body:
Problem

The origin of the problem is that the WebpackDevServer only serves from one folder. The folder that you should be serving from is the folder containing the index.html, which is what you're correctly doing.

So far you're serving only the content of ./dist/templates/admin, therefore when you look for files in other directories you get a 404. The only exception here is your bundle, because you're setting a publicPath that makes any request to the route /static/js be redirected to your output, which is stored in memory.

You would need the WebpackDevServer to be able to serve from other folders. In your specific case, you need to serve also from ./dist/static/css when you request the path /static/css.

Solution

You need to set some middlewares in your WebpackDevServer. You can do so as described in the documentation of devServer.setup. To do so, I suggest you use express.static, as you're probably already using Express.

You need to require Express:

const express = require('express')

And then, just modify the devServer as follows:

devServer: {
  contentBase: './dist/templates/admin',
  hot: true,
  historyApiFallback: true,
  setup (app) {
    app.use('/static/css/',
      express.static(path.join(__dirname, 'dist', 'static', 'css')));
    /* Using this commented code will break the HMR, see edit
    app.use('/static/js/',
      express.static(path.join(__dirname, 'dist', 'static', 'js')));
    */

    // in general
    app.use('/public/route/',
      express.static('/your/local/path'));
  }
}

This way your devs and build paths stay the same, and the WebpackDevServer serves the static files you need, at the routes you need.

Edit

I just discovered that the code above breaks the Hot Module Replacement. The reason is that the middleware in the setup is handling /static/js/, so the bundle is served from the file system instead of memory.

To keep fetching the bundle from memory define a publicPath in the output property, and don't handle it from a custom middleware inside devServer.setup.

module.exports = {

  output: {
    path: ...,
    filename: ...,
    publicPath: '/static/js/'
  },

  devServer: {
    contentBase: './dist/templates/admin',
    hot: true,
    historyApiFallback: true,
    setup (app) {
      app.use('/static/css/',
        express.static(path.join(__dirname, 'dist', 'static', 'css')));
    }
  },

  // other properties: entry, module, etc.
}


来源: stackexchange

问:
Mocha finding user from MongoDb in the beginning while it is created later
I am trying to figure out how the user can be found from the database in the beginning of this code, while the user is created later in the code.

The Mocha documentation says

Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).

```<code>var assert = require('assert');
var express = require('express');
var status = require('http-status');
var superagent = require('superagent');
var wagner = require('wagner-core');

var URL_ROOT = 'http://localhost:3000';
var PRODUCT_ID = '000000000000000000000001';

describe('User API', function() {
  var server;
  var Category;
  var Product;
  var User;

  before(function() {
    var app = express();

    models = require('./models')(wagner);

    Category = models.Category;
    Product = models.Product;
    User = models.User;

    app.use(function(req, res, next) {
      User.findOne({}, function(error, user) {
        assert.ifError(error);

        req.user = user;
        console.log(user);
        next();
      });
    });

    app.use(require('./api')(wagner));

    server = app.listen(3000);
  });

  after(function() {
    server.close;
  });

  beforeEach(function(done) {
    Category.remove({}, function(error) {
      assert.ifError(error);
      Product.remove({}, function(error) {
        assert.ifError(error);
        User.remove({}, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });
  });

  beforeEach(function(done) {
    var categories = [
      { _id: 'Electronics' },
      { _id: 'Phones', parent: 'Electronics' },
      { _id: 'Laptops', parent: 'Electronics' },
      { _id: 'Bacon' }
    ];

    var products = [
      {
        name: 'LG G4',
        category: { _id: 'Phones', ancestors: ['Electronics', 'Phones'] },
        price: {
          amount: 300,
          currency: 'USD'
        }
      },
      {
        _id: PRODUCT_ID,
        name: 'Asus Zenbook Prime',
        category: { _id: 'Laptops', ancestors: ['Electronics', 'Laptops'] },
        price: {
          amount: 2000,
          currency: 'USD'
        }
      },
      {
        name: 'Flying Pigs Farm Pasture Raised Pork Bacon',
        category: { _id: 'Bacon', ancestors: ['Bacon'] },
        price: {
          amount: 20,
          currency: 'USD'
        }
      }
    ];

    var users = [{
      profile: {
        username: 'vkarpov15',
        picture: 'http://pbs.twimg.com/profile_images/550304223036854272/Wwmwuh2t.png'
      },
      data: {
        oauth: 'invalid',
        cart: []
      }
    }];
    Category.create(categories, function(error) {
      assert.ifError(error);
      Product.create(products, function(error) {
        assert.ifError(error);
        User.create(users, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });
  });

  it('can save users cart', function(done) {
    var url = URL_ROOT + '/me/cart';

    superagent.
      put(url).
      send({
        data: {
          cart: [{ product: PRODUCT_ID, quantity: 1 }]
        }
      }).
      end(function(error,res) {

        assert.ifError(error);
        assert.equal(res.status, status.OK);
        User.findOne({}, function(error, user) {

          assert.ifError(error);
          assert.equal(user.data.cart.length, 1);
          assert.equal(user.data.cart[0].product, PRODUCT_ID);
          assert.equal(user.data.cart[0].quantity, 1);
          done();
        });
      });
  });

})
</code>```

How can the user 'vkarpov15' be found here, whilst the user is created in the beforeEach function that comes later.

```<code>app.use(function(req, res, next) {
      User.findOne({}, function(error, user) {
        assert.ifError(error);

        req.user = user;
        console.log(user);
        next();
      });
    });
</code>```

It is created here, later in the code:

```<code>Category.create(categories, function(error) {
      assert.ifError(error);
      Product.create(products, function(error) {
        assert.ifError(error);
        User.create(users, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });
</code>```

答:
The user is not queried there, that code just registers an express middleware that will query the user before each request to the server. As you can see, the request is issued  in an it test case, but a user is created before every test case, see the beforeEach block.

ps: You miss the parenthesis after server.close() in the after block.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure out how the user can be found from the database in the beginning of this code, while the user is created later in the code.

The Mocha documentation says

Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).

var assert = require('assert');
var express = require('express');
var status = require('http-status');
var superagent = require('superagent');
var wagner = require('wagner-core');

var URL_ROOT = 'http://localhost:3000';
var PRODUCT_ID = '000000000000000000000001';

describe('User API', function() {
  var server;
  var Category;
  var Product;
  var User;

  before(function() {
    var app = express();

    models = require('./models')(wagner);

    Category = models.Category;
    Product = models.Product;
    User = models.User;

    app.use(function(req, res, next) {
      User.findOne({}, function(error, user) {
        assert.ifError(error);

        req.user = user;
        console.log(user);
        next();
      });
    });

    app.use(require('./api')(wagner));

    server = app.listen(3000);
  });

  after(function() {
    server.close;
  });

  beforeEach(function(done) {
    Category.remove({}, function(error) {
      assert.ifError(error);
      Product.remove({}, function(error) {
        assert.ifError(error);
        User.remove({}, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });
  });

  beforeEach(function(done) {
    var categories = [
      { _id: 'Electronics' },
      { _id: 'Phones', parent: 'Electronics' },
      { _id: 'Laptops', parent: 'Electronics' },
      { _id: 'Bacon' }
    ];

    var products = [
      {
        name: 'LG G4',
        category: { _id: 'Phones', ancestors: ['Electronics', 'Phones'] },
        price: {
          amount: 300,
          currency: 'USD'
        }
      },
      {
        _id: PRODUCT_ID,
        name: 'Asus Zenbook Prime',
        category: { _id: 'Laptops', ancestors: ['Electronics', 'Laptops'] },
        price: {
          amount: 2000,
          currency: 'USD'
        }
      },
      {
        name: 'Flying Pigs Farm Pasture Raised Pork Bacon',
        category: { _id: 'Bacon', ancestors: ['Bacon'] },
        price: {
          amount: 20,
          currency: 'USD'
        }
      }
    ];

    var users = [{
      profile: {
        username: 'vkarpov15',
        picture: 'http://pbs.twimg.com/profile_images/550304223036854272/Wwmwuh2t.png'
      },
      data: {
        oauth: 'invalid',
        cart: []
      }
    }];
    Category.create(categories, function(error) {
      assert.ifError(error);
      Product.create(products, function(error) {
        assert.ifError(error);
        User.create(users, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });
  });

  it('can save users cart', function(done) {
    var url = URL_ROOT + '/me/cart';

    superagent.
      put(url).
      send({
        data: {
          cart: [{ product: PRODUCT_ID, quantity: 1 }]
        }
      }).
      end(function(error,res) {

        assert.ifError(error);
        assert.equal(res.status, status.OK);
        User.findOne({}, function(error, user) {

          assert.ifError(error);
          assert.equal(user.data.cart.length, 1);
          assert.equal(user.data.cart[0].product, PRODUCT_ID);
          assert.equal(user.data.cart[0].quantity, 1);
          done();
        });
      });
  });

})

How can the user 'vkarpov15' be found here, whilst the user is created in the beforeEach function that comes later.

app.use(function(req, res, next) {
      User.findOne({}, function(error, user) {
        assert.ifError(error);

        req.user = user;
        console.log(user);
        next();
      });
    });

It is created here, later in the code:

Category.create(categories, function(error) {
      assert.ifError(error);
      Product.create(products, function(error) {
        assert.ifError(error);
        User.create(users, function(error) {
          assert.ifError(error);
          done();
        });
      });
    });


问:
socket connection between matlab and python
I wrote the following code in matlab and python. I am using heroku server created by python as a client and matlab as server.

MATLAB code:

```<code>t = tcpip('0.0.0.0',4000,'NetworkRole','Server')
fopen(t)
data = fread(t,t.BytesAvailable)
fwrite(t,'hello back')
</code>```

Python Code:

```<code>TCP_IP = 'my_laptop_ip_address'
TCP_PORT = 4000
BUFFER_SIZE = 1024
MESSAGE="Hello World"

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((TCP_IP,TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

return "received data:",data
</code>```

When I run the MATLAB code and then after the server is open I run the test function from heroku, my page keeps loading and doesnt connect with MATLAB server.

答: The TCP_IP variable in the python client should hold the server's IP address, not your laptop address.

Body:
I wrote the following code in matlab and python. I am using heroku server created by python as a client and matlab as server.

MATLAB code:

t = tcpip('0.0.0.0',4000,'NetworkRole','Server')
fopen(t)
data = fread(t,t.BytesAvailable)
fwrite(t,'hello back')

Python Code:

TCP_IP = 'my_laptop_ip_address'
TCP_PORT = 4000
BUFFER_SIZE = 1024
MESSAGE="Hello World"

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((TCP_IP,TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

return "received data:",data

When I run the MATLAB code and then after the server is open I run the test function from heroku, my page keeps loading and doesnt connect with MATLAB server.


问:
PHP & MySQL UPDATE 10 columns
I want to update customer data which means 10 different columns would be updated in one UPDATE SET WHERE statement but I keep getting a warning in NetBeans that says method length 26 ( allowed 20)
Can anyone tell me what the method length refers to and what another way is to update all those columns in one statement ? </p>

答: For what is worth, I suggest you download and install mysql workbench, it will serve as sandbox to test queries before anything else. This always works for me in any development situations</p>

Title: PHP & MySQL UPDATE 10 columns


问:
ProcessSimulator.killAllProcesses(line:78) NoSuchMethodError ConcurrentHashMap.keySet()
Why?
I am using Storm for the first time (learning from getting started with storm) and run success but found NoSuchMethodError:

```<code>java.lang.NoSuchMethodError: java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;
        at org.apache.storm.ProcessSimulator.killAllProcesses(ProcessSimulator.java:78) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.testing$kill_local_storm_cluster.invoke(testing.clj:206) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.LocalCluster$_shutdown.invoke(LocalCluster.clj:66) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.LocalCluster.shutdown(Unknown Source) ~[storm-core-1.0.3.jar:1.0.3]
        at com.wjl.hello.TopologyMain.main(TopologyMain.java:45) ~[storm-hello-0.0.1-SNAPSHOT.jar:?]
</code>```

and

```<code>org.apache.storm.shade.org.apache.zookeeper.server.ServerCnxn$EndOfStreamException: Unable to read additional data from client sessionid 0x15b28de9a8b0011, likely client has closed socket
        at org.apache.storm.shade.org.apache.zookeeper.server.NIOServerCnxn.doIO(NIOServerCnxn.java:228) [storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.shade.org.apache.zookeeper.server.NIOServerCnxnFactory.run(NIOServerCnxnFactory.java:208) [storm-core-1.0.3.jar:1.0.3]
        at java.lang.Thread.run(Thread.java:722) [?:1.7.0_15]
</code>```

Running successfully:

```<code>-- Word Counter [word-counter-2] --
yes: 1 is: 5 it: 1 what: 1 apple: 1 name: 4 your: 3 funny: 1 haha: 2 en: 1 my: 2 this: 2
</code>```

答: That may be Java 8 <> 7 incompatibility issue. Please. check this question: ConcurrentHashMap crashing application compiled with JDK 8 but targeting JRE 7</p>

Body:
Why?
I am using Storm for the first time (learning from getting started with storm) and run success but found NoSuchMethodError:

java.lang.NoSuchMethodError: java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;
        at org.apache.storm.ProcessSimulator.killAllProcesses(ProcessSimulator.java:78) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.testing$kill_local_storm_cluster.invoke(testing.clj:206) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.LocalCluster$_shutdown.invoke(LocalCluster.clj:66) ~[storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.LocalCluster.shutdown(Unknown Source) ~[storm-core-1.0.3.jar:1.0.3]
        at com.wjl.hello.TopologyMain.main(TopologyMain.java:45) ~[storm-hello-0.0.1-SNAPSHOT.jar:?]

and

org.apache.storm.shade.org.apache.zookeeper.server.ServerCnxn$EndOfStreamException: Unable to read additional data from client sessionid 0x15b28de9a8b0011, likely client has closed socket
        at org.apache.storm.shade.org.apache.zookeeper.server.NIOServerCnxn.doIO(NIOServerCnxn.java:228) [storm-core-1.0.3.jar:1.0.3]
        at org.apache.storm.shade.org.apache.zookeeper.server.NIOServerCnxnFactory.run(NIOServerCnxnFactory.java:208) [storm-core-1.0.3.jar:1.0.3]
        at java.lang.Thread.run(Thread.java:722) [?:1.7.0_15]

Running successfully:

-- Word Counter [word-counter-2] --
yes: 1 is: 5 it: 1 what: 1 apple: 1 name: 4 your: 3 funny: 1 haha: 2 en: 1 my: 2 this: 2


问:
error when using wc -c with file names
I am running this code, that sorts files in the desired folders. If a file name has 13 chars it should run the first statement, else the second.

```<code>for i in *.png; do if [ "$($i | wc -c)" -eq 13 ]; then
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:3}.jpg
else
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:4}.jpg
fi;
done
</code>```

the problem is, that [ "$($i | wc -c)" -eq 13 ] is always 0, but clearly, file names have some length. What is the correct way of evaluating wc -c in an if statement?

Title: error when using wc -c with file names

Body:
I am running this code, that sorts files in the desired folders. If a file name has 13 chars it should run the first statement, else the second.

for i in *.png; do if [ "$($i | wc -c)" -eq 13 ]; then
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:3}.jpg
else
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:4}.jpg
fi;
done

the problem is, that [ "$($i | wc -c)" -eq 13 ] is always 0, but clearly, file names have some length. What is the correct way of evaluating wc -c in an if statement?

Body:
Replace

[ "$($i | wc -c)" -eq 13 ]

by

[ $(printf "%s" "$i" | wc -c) -eq 13 ]

or use

[ ${#i} -eq 13 ]


问:
TFS2010 Build Definition to Deploy to multiple servers?
I've been looking into TFS2010 new build and deployment features with MSDeploy. So far everything is going well (although its been hard to find information about specific scenarios).

Can I modify my Build Definition to specify 2 or more servers to deploy to? What I need to do is deploy to multiple servers (as I have two in my testing environment which uses a NLB).

What I have now is a Build definition which Builds, runs my tests, and then Deploys to ONE of my testing servers (which has the MsDeployAgentService running on it). It works fine, and each web project is deployed as configured in its project file. The MSBuild Arguments I use are:

```<code>* /p:DeployOnBuild=True
* /p:DeployTarget=MsDeployPublish
* /p:MSDeployServiceURL=http://oawww.testserver1.com.au/MsDeployAgentService
* /p:CreatePackageOnPublish=True
* /p:MsDeployPublishMethod=RemoteAgent
* /p:AllowUntrustedCertificated=True
* /p:UserName=myusername
* /p:Password=mypassword
</code>```

NB: I dont use /p:DeployIISAppPath="xyz" as it doesnt deploy all my projects and overrides my project config.

Can I add another build argument to get it to call more than one MSDeployServiceURL? Like something like a second /p:MSDeployServiceURL argument that specifies another server?

Or do I have to look for another solution, such as editing the WF?

I saw an almost exact same question here posted 2 months ago: TFS 2010 - Deploy to Multiple Servers After Build , so it doesn't look like I'm the only one trying to solve this.

I also posted on the IIS.NET forums where MSDeploy is discussed: http://forums.iis.net/t/1170741.aspx . It's had quite a lot of views, but again, no answers.

答:
You don't have to build the project twice to deploy to two servers. The build process will build a set of deployment files. You can then use the InvokeProcess to deploy to multiple servers.

First create a variable named ProjectName. Then add an Assign activity to the "Compile the Project" sequence. This is located in the "Try to Compile the Project" sequence. Here are the properties of the Assign:

```<code>To: ProjectName
Value: System.IO.Path.GetFileNameWithoutExtension(localProject)
</code>```

Here are the properties of our InvokeProcess activity that deploys to the test server:

```<code>Arguments: "/y /M:<server> /u:<domain>\<user> /p:<password>"
FileName: String.Format("{0}\{1}.deploy.cmd", BuildDetail.DropLocation, ProjectName)

You will need to change <server>, <domain>, <user>, and <password> to the values that reflect your environment.
</code>```

If you need to manually deploy to a server you can run the command below from your build folder:

```<code>deploy.cmd /y /M:<server> /u:<domain>\<user> /p:<password>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've been looking into TFS2010 new build and deployment features with MSDeploy. So far everything is going well (although its been hard to find information about specific scenarios).

Can I modify my Build Definition to specify 2 or more servers to deploy to? What I need to do is deploy to multiple servers (as I have two in my testing environment which uses a NLB).

What I have now is a Build definition which Builds, runs my tests, and then Deploys to ONE of my testing servers (which has the MsDeployAgentService running on it). It works fine, and each web project is deployed as configured in its project file. The MSBuild Arguments I use are:

* /p:DeployOnBuild=True
* /p:DeployTarget=MsDeployPublish
* /p:MSDeployServiceURL=http://oawww.testserver1.com.au/MsDeployAgentService
* /p:CreatePackageOnPublish=True
* /p:MsDeployPublishMethod=RemoteAgent
* /p:AllowUntrustedCertificated=True
* /p:UserName=myusername
* /p:Password=mypassword

NB: I dont use /p:DeployIISAppPath="xyz" as it doesnt deploy all my projects and overrides my project config.

Can I add another build argument to get it to call more than one MSDeployServiceURL? Like something like a second /p:MSDeployServiceURL argument that specifies another server?

Or do I have to look for another solution, such as editing the WF?

I saw an almost exact same question here posted 2 months ago: TFS 2010 - Deploy to Multiple Servers After Build , so it doesn't look like I'm the only one trying to solve this.

I also posted on the IIS.NET forums where MSDeploy is discussed: http://forums.iis.net/t/1170741.aspx . It's had quite a lot of views, but again, no answers.

Body:
You don't have to build the project twice to deploy to two servers. The build process will build a set of deployment files. You can then use the InvokeProcess to deploy to multiple servers.

First create a variable named ProjectName. Then add an Assign activity to the "Compile the Project" sequence. This is located in the "Try to Compile the Project" sequence. Here are the properties of the Assign:

To: ProjectName
Value: System.IO.Path.GetFileNameWithoutExtension(localProject)

Here are the properties of our InvokeProcess activity that deploys to the test server:

Arguments: "/y /M:<server> /u:<domain>\<user> /p:<password>"
FileName: String.Format("{0}\{1}.deploy.cmd", BuildDetail.DropLocation, ProjectName)

You will need to change <server>, <domain>, <user>, and <password> to the values that reflect your environment.

If you need to manually deploy to a server you can run the command below from your build folder:

deploy.cmd /y /M:<server> /u:<domain>\<user> /p:<password>


问:
Device compabilities issue in iOS
We uploaded an app where in the first version we added to device capabilities “telephony” to restrict only iPhone devices in the info plist. In the second version we forgot to add “telephony” and we submitted to the App store. Third version we are planning to upload with device capabilities as “telephony” but while submitting to the App Store it shows the warning:

This bundle is invalid. The key UIRequiredDeviceCapabilities in the
  Info.plist may not contain values that would prevent this application
  from running on devices that were supported by previous versions.

How can we resolve this issue, if we require the device capability “telephony” for  application lifetime, but due to my mistake on the second version we forgot to add the required device capabilities? What is the solution for it?

Thanks in advance.

答:
I have the same warning when added to device capabilities “healthkit” t in the info plist.

This bundle is invalid - The key UIRequiredDeviceCapabilities in the Info.plist may not contain values that would prevent this application from running on devices that were supported by previous versions.

delete Info.plist -> Required device capabilities -> Item -> healthkit，upload again to submit review success.

Title: Device compabilities issue in iOS


问:
How to loop through all Symbols and check the current bar and the previous one's High?
The problem is that when the i in the for loop reaches 15, I get an Array out of range error.

What I want to achieve is on every tick to check every Symbol in the MarketWatch and in each Symbol to check the current bar ( PERIOD_M5 ) and the previous one if there is a gap.

```<code>void OnTick()
{
 int size = ArraySize( Symbols );

 for( int i = 0; i < size; i++ )
 {
  int  current_bar_index     = iHighest( Symbols[i], PERIOD_M5, MODE_HIGH, 1, 0 );
  int previous_bar_index     = iHighest( Symbols[i], PERIOD_M5, MODE_HIGH, 1, 1 );
  int  current_bar_index_low = iLowest(  Symbols[i], PERIOD_M5, MODE_LOW,  1, 0 );
  int previous_bar_index_low = iLowest(  Symbols[i], PERIOD_M5, MODE_LOW,  1, 1 );

  double  current_high = High[ current_bar_index];
  double previous_high = High[previous_bar_index];
  double  current_low  = Low[  current_bar_index_low];
  double previous_low  = Low[ previous_bar_index_low];

  if (  current_low  > ( previous_high + 0.00002 )
     || current_high < ( previous_low  - 0.00002 )
        )
  {
     Print( "There is a gap" );
  }
 }
}
</code>```

Symbols[] is the array containing all the symbols. I loop through it and pass the current Symbol and get the index for the current bar and the previous one and then simply check if there is a gap.

The first problem is that passing every Symbol doesn't work. It gets only one and that's it. How can I achieve that and also, why I get an Array out of range error?

答:
Let's start with the Array out of range error:

Given the MCVE was not present, let's assume, there is some fair declaration of the MQL4 code in the header or something like that.

So to diagnose this, add a trivial debug tool:

```<code>string SymbolsARRAY[] = { ...,  // be carefull, some Brokers
                          ...,  //              have quite strange names
                          ...
                          };

for ( int cellPTR  = 0;
          cellPTR <  ArraySize( SymbolsARRAY );
          cellPTR++
          )
          PrintFormat( "%s[%d] = %s",
                       "SymbolsARRAY",
                        cellPTR,
                        SymbolsARRAY[cellPTR]
                        );
</code>```

and post here the output.

Next, the GAP detection:

if you would not mind, checking a pair of M5-Bars for a GAP on each and every price QUOTE message arrival, is quite devastating the MQL4 computing resources. The GAP may principally appear only upon a new Bar starts ( and yet may disappear, during the Bar duration ).

Let's detect the initial GAP-condition ( it is similar to engulfing detection ):

```<code>if (   iLow( SymbolsARRAY[cellPTR], PERIOD_M5, 1 ) > iHigh( SymbolsARRAY[cellPTR], PERIOD_M5, 0 )
   || iHigh( SymbolsARRAY[cellPTR], PERIOD_M5, 1 ) <  iLow( SymbolsARRAY[cellPTR], PERIOD_M5, 0 )
      )
      Print( "Initial GAP detected" );
</code>```

Using this inside a detection of a new bar event may look like this:

```<code>void OnTick(){

 // -----------------------------------------------------------------
 // MINIMALISTIC CONTEXT-AWARE GAP DETECT/REMOVE
 // -----------------------------------------------------------------
    static bool      aCurrentGAP  = False;
    static datetime  aCurrentBAR  = Time[0];
    if (             aCurrentBAR != Time[0] ){
                     aCurrentBAR  = Time[0];
                  // testInitGAP .........................present?
                     aCurrentGAP  = testInitialGAP_onNewBarEVENT();
    }
    else {
                if ( aCurrentGAP ){
                  // testInitGAP .....................disappeared?
                     aCurrentGAP  = testInitialGAP_DISAPPEARED();
                }
    }
 // -----------------------------------------------------------------
 // MAIN COMPUTING & TRADING DUTIES OF EA-MQL4-CODE
 // -----------------------------------------------------------------
    ...
}
</code>```

Body:
The problem is that when the i in the for loop reaches 15, I get an Array out of range error.

What I want to achieve is on every tick to check every Symbol in the MarketWatch and in each Symbol to check the current bar ( PERIOD_M5 ) and the previous one if there is a gap.

void OnTick()
{
 int size = ArraySize( Symbols );

 for( int i = 0; i < size; i++ )
 {
  int  current_bar_index     = iHighest( Symbols[i], PERIOD_M5, MODE_HIGH, 1, 0 );
  int previous_bar_index     = iHighest( Symbols[i], PERIOD_M5, MODE_HIGH, 1, 1 );
  int  current_bar_index_low = iLowest(  Symbols[i], PERIOD_M5, MODE_LOW,  1, 0 );
  int previous_bar_index_low = iLowest(  Symbols[i], PERIOD_M5, MODE_LOW,  1, 1 );

  double  current_high = High[ current_bar_index];
  double previous_high = High[previous_bar_index];
  double  current_low  = Low[  current_bar_index_low];
  double previous_low  = Low[ previous_bar_index_low];

  if (  current_low  > ( previous_high + 0.00002 )
     || current_high < ( previous_low  - 0.00002 )
        )
  {
     Print( "There is a gap" );
  }
 }
}

Symbols[] is the array containing all the symbols. I loop through it and pass the current Symbol and get the index for the current bar and the previous one and then simply check if there is a gap.

The first problem is that passing every Symbol doesn't work. It gets only one and that's it. How can I achieve that and also, why I get an Array out of range error?

Body:
Let's start with the Array out of range error:

Given the MCVE was not present, let's assume, there is some fair declaration of the MQL4 code in the header or something like that.

So to diagnose this, add a trivial debug tool:

string SymbolsARRAY[] = { ...,  // be carefull, some Brokers
                          ...,  //              have quite strange names
                          ...
                          };

for ( int cellPTR  = 0;
          cellPTR <  ArraySize( SymbolsARRAY );
          cellPTR++
          )
          PrintFormat( "%s[%d] = %s",
                       "SymbolsARRAY",
                        cellPTR,
                        SymbolsARRAY[cellPTR]
                        );

and post here the output.

Next, the GAP detection:

if you would not mind, checking a pair of M5-Bars for a GAP on each and every price QUOTE message arrival, is quite devastating the MQL4 computing resources. The GAP may principally appear only upon a new Bar starts ( and yet may disappear, during the Bar duration ).

Let's detect the initial GAP-condition ( it is similar to engulfing detection ):

if (   iLow( SymbolsARRAY[cellPTR], PERIOD_M5, 1 ) > iHigh( SymbolsARRAY[cellPTR], PERIOD_M5, 0 )
   || iHigh( SymbolsARRAY[cellPTR], PERIOD_M5, 1 ) <  iLow( SymbolsARRAY[cellPTR], PERIOD_M5, 0 )
      )
      Print( "Initial GAP detected" );

Using this inside a detection of a new bar event may look like this:

void OnTick(){

 // -----------------------------------------------------------------
 // MINIMALISTIC CONTEXT-AWARE GAP DETECT/REMOVE
 // -----------------------------------------------------------------
    static bool      aCurrentGAP  = False;
    static datetime  aCurrentBAR  = Time[0];
    if (             aCurrentBAR != Time[0] ){
                     aCurrentBAR  = Time[0];
                  // testInitGAP .........................present?
                     aCurrentGAP  = testInitialGAP_onNewBarEVENT();
    }
    else {
                if ( aCurrentGAP ){
                  // testInitGAP .....................disappeared?
                     aCurrentGAP  = testInitialGAP_DISAPPEARED();
                }
    }
 // -----------------------------------------------------------------
 // MAIN COMPUTING & TRADING DUTIES OF EA-MQL4-CODE
 // -----------------------------------------------------------------
    ...
}


问:
angularjs bootstrap - set title if
I have a
 that I want to give it title

```<code><tr title="qualified">
</code>```

if a controller variable qualified is true

I am using AngularJS.

答:
Try this:</p>

```<code><tr title="{{ qualified ? 'title' : '' }}">
</code>```

Title: angularjs bootstrap - set title if

Body:
I have a
 that I want to give it title

if a controller variable qualified is true

I am using AngularJS.

Body:
Try this:

<tr title="{{ qualified ? 'title' : '' }}">


问:
How to prepare runnable jar for Open cv java project?
I have devloped one project for face detection using opencv open cv 2.4.9 on windows. now i have to run the jar on ubuntu machine. i gets failed.

```<code>Caused by: java.lang.UnsatisfiedLinkError: no opencv_java249 in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1889)
        at java.lang.Runtime.loadLibrary0(Runtime.java:849)
        at java.lang.System.loadLibrary(System.java:1088)
</code>```

my main concern is how to prepare package (runnable jar) having opencv-249 dependency for ubuntu?

答:
You should load the OpenCV lib pragmatically as below:

```<code>// get the model
String model = System.getProperty("sun.arch.data.model");
// the path the .dll lib location
String libraryPath = "C:/opencv/build/java/x86/";
// check for if system is 64 or 32
if(model.equals("64")) {
    libraryPath = "C:/opencv/build/java/x64/";
}
// set the path
System.setProperty("java.library.path", libraryPath);
Field sysPath = ClassLoader.class.getDeclaredField("sys_paths");
sysPath.setAccessible(true);
sysPath.set(null, null);
// load the lib
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
</code>```

You can run this method when the program starts.

Body:
I have devloped one project for face detection using opencv open cv 2.4.9 on windows. now i have to run the jar on ubuntu machine. i gets failed.

Caused by: java.lang.UnsatisfiedLinkError: no opencv_java249 in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1889)
        at java.lang.Runtime.loadLibrary0(Runtime.java:849)
        at java.lang.System.loadLibrary(System.java:1088)

my main concern is how to prepare package (runnable jar) having opencv-249 dependency for ubuntu?

Body:
You should load the OpenCV lib pragmatically as below:

// get the model
String model = System.getProperty("sun.arch.data.model");
// the path the .dll lib location
String libraryPath = "C:/opencv/build/java/x86/";
// check for if system is 64 or 32
if(model.equals("64")) {
    libraryPath = "C:/opencv/build/java/x64/";
}
// set the path
System.setProperty("java.library.path", libraryPath);
Field sysPath = ClassLoader.class.getDeclaredField("sys_paths");
sysPath.setAccessible(true);
sysPath.set(null, null);
// load the lib
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

You can run this method when the program starts.


问:
How do I configure a heroku app's database that uses postgresql using the schema?
I've been using mysql forever.  never really needed anything fancier.  But I'm using heroku a lot and while I'm working, I like free search, so I'm using the acts_as_tsearch plugin.  If you go to the git repository, it tells you:

```<code>* Preparing your PostgreSQL database

Add a text search configuration 'default':

  CREATE TEXT SEARCH CONFIGURATION public.default ( COPY = pg_catalog.english )
</code>```

So guess what?  I

changed from mysql to postgresql in my rails config

ran that "CREATE TEXT" code in the sql pain of pgAdmin (a gui for postgres)

noticed that now my development DB has something called an "FTS configuration"

tried the search functionality and it works GREAT

But I'm having trouble getting that configuration to show up in the schema.  When I did rake db:dump it doesn't make it in there.  I know I can add this line to the schema.rb:

```<code>execute 'CREATE TEXT SEARCH CONFIGURATION public.default ( COPY = pg_catalog.english )'
</code>```

and that works, but how can I get that configuration into the schema without my having to hand-add it?  Can I create a file that is also loaded after schema.rb when someone types rake db:load?

And for the postgres people, a question:  What does that CREATE TEXT SEARCH CONFIGURATION... do?

答: Why don't you try adding it to a migration file and rake that against the heroku db?</p>

Body:
I've been using mysql forever.  never really needed anything fancier.  But I'm using heroku a lot and while I'm working, I like free search, so I'm using the acts_as_tsearch plugin.  If you go to the git repository, it tells you:

* Preparing your PostgreSQL database

Add a text search configuration 'default':

  CREATE TEXT SEARCH CONFIGURATION public.default ( COPY = pg_catalog.english )

So guess what?  I

changed from mysql to postgresql in my rails config

ran that "CREATE TEXT" code in the sql pain of pgAdmin (a gui for postgres)

noticed that now my development DB has something called an "FTS configuration"

tried the search functionality and it works GREAT

But I'm having trouble getting that configuration to show up in the schema.  When I did rake db:dump it doesn't make it in there.  I know I can add this line to the schema.rb:

execute 'CREATE TEXT SEARCH CONFIGURATION public.default ( COPY = pg_catalog.english )'

and that works, but how can I get that configuration into the schema without my having to hand-add it?  Can I create a file that is also loaded after schema.rb when someone types rake db:load?

And for the postgres people, a question:  What does that CREATE TEXT SEARCH CONFIGURATION... do?


问:
Change The index of a comboBox in windows Application in c#
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working</p>

```<code>private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }
</code>```

答:
try this

User the name of properties defined in class as display member and membervalue

```<code>districtComboBox.DisplayMember = "Areaname";
districtComboBox.ValueMember = "Id";
</code>```

Body:
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working

private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }

Body:
try this

User the name of properties defined in class as display member and membervalue

districtComboBox.DisplayMember = "Areaname";
districtComboBox.ValueMember = "Id";


问:
no resource id found for app:layout_scrollflags from CollapsingToolbarLayout
The title of this question basically says it all. I get the error:
no resource identifier found for app:layout_scrollflags from CollapsingToolbarLayout. I use eclipse and imported the design library jar file. I'm able to use the design support layouts in my classes so that's correct

this is a piece of the code i use:

```<code><LinearLayout
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:orientation="vertical"
android:background="@color/activityBg"
tools:context=".MainActivity"
>

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <include
            layout="@layout/toolbar"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</code>```

examples: http://android-developers.blogspot.in/2015/05/android-design-support-library.html

答:
As others have stated you definitely need to add Design Support Library dependency to your android app. Simplest way is to add following to app level gradle file -

```<code>compile 'com.android.support:design:25.3.1'
</code>```

However couple of points to note-

This support library should not use a different version than the compileSdkVersion. Since I was using compileSdkVersion 25 I had to use compile 'com.android.support:design:25.3.1' and not compile 'com.android.support:design:24.2.1'

Using the design library requires using theme.appcompat or a descendant. If you want add actionbar to your activity then your theme should be AppCompat. In my case I was using android:Theme.Material due to which it was failing. Changing it to Theme.AppCompat.Light.NoActionBar worked for me.

Body:
The title of this question basically says it all. I get the error:
no resource identifier found for app:layout_scrollflags from CollapsingToolbarLayout. I use eclipse and imported the design library jar file. I'm able to use the design support layouts in my classes so that's correct

this is a piece of the code i use:

<LinearLayout
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:orientation="vertical"
android:background="@color/activityBg"
tools:context=".MainActivity"
>

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <include
            layout="@layout/toolbar"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

examples: http://android-developers.blogspot.in/2015/05/android-design-support-library.html

Body:
As others have stated you definitely need to add Design Support Library dependency to your android app. Simplest way is to add following to app level gradle file -

compile 'com.android.support:design:25.3.1'

However couple of points to note-

This support library should not use a different version than the compileSdkVersion. Since I was using compileSdkVersion 25 I had to use compile 'com.android.support:design:25.3.1' and not compile 'com.android.support:design:24.2.1'

Using the design library requires using theme.appcompat or a descendant. If you want add actionbar to your activity then your theme should be AppCompat. In my case I was using android:Theme.Material due to which it was failing. Changing it to Theme.AppCompat.Light.NoActionBar worked for me.


问:
Custom SQL query, for sorting values with "-" as separators
I am trying to create an ORDER BY to sort my values properly.

The values contain a string and anywhere from zero to three sets of numbers separated by a -.

Example:

```<code>dog-2-13
dog-13-54-3
dog-25
cat-63-12
cat
</code>```

I want them to be sorted firstly by the string in front and then by each of the "number sections" so that: dog-2-14 > dog-2-13 but dog-1-14 < dog-2-13.

Expected result (with more examples to make it clearer):

```<code>cat
cat-63-12
dog-2-13
dog-2-14
dog-3
dog-13-53-3
dog-13-54-3
dog-13-54-4
dog-25
</code>```

I'm a SQL novice and completely lost. Thank you!

答:
Please try...

```<code>SELECT fieldName
FROM
(
    SELECT fieldName AS fieldName,
           SUBSTRING_INDEX( fieldName,
                            '-',
                            1 ) AS stringComponent,
           CONVERT( SUBSTRING_INDEX( SUBSTRING( fieldName,
                                                CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 1 ) ) + 2 ),
                                     '-',
                                     1 ),
                    UNSIGNED ) AS firstNumber,
           CONVERT( SUBSTRING_INDEX( SUBSTRING( fieldName,
                                                CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 2 ) ) + 2 ),
                                     '-',
                                     1 ),
                    UNSIGNED ) AS secondNumber,
           CONVERT( SUBSTRING( fieldName,
                               CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 3 ) ) + 2 ),
                    UNSIGNED ) AS thirdNumber
    FROM table1
    ORDER BY stringComponent,
             firstNumber,
             secondNumber,
             thirdNumber
) tempTable;
</code>```

The inner SELECT grabs the field name (which I am assuming is fieldName) and the three components and places each in a separate field and assigning an alias to that field.  Each subfield must be included at this point for sorting purposes.  The list is then sorted based upon those values.

Once this sorting is performed the outer SELECT chooses the original field from the list in a now sorted order.

The four outer instances of SUBSTRING_INDEX() are used to grab the desired fields from their first argument.  As SUBSTRING_INDEX() grabs all of the string from the beginning to just before the first occurence of the delimiting character this makes finding the first field easy (Note : I am assuming that the first field shall contain no hyphens).

The first argument for the remaining occurences of SUBSTRING_INDEX() is formed by using SUBSTRING() to grab everything from just after the parsed part of fieldName and the following delimiting character.  It is told where this is by using CHAR_LENGTH() to count the number of characters before the most recent delimiting character then adding 1 for the most recent delimiting character and another 1 to point SUBSTRING() to the character after the most recent delimiting character.

SUBSTRING_INDEX() will return NULL where it encounters an absent numerical field.  Please note that NULL has a different sort value from zero.

The numerical fields are converted into unsigned Integers using CONVERT().  Unsigned integers were chosen as the supplied data does not contain any real numbers.  If there are real values then you will need to replace UNSIGNED with DECIMAL.  I have also assumed that all of the numbers will be positive.

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_char-length

https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_convert

If you have any questions or comments, then please feel free to post a Comment accordingly.

Body:
I am trying to create an ORDER BY to sort my values properly.

The values contain a string and anywhere from zero to three sets of numbers separated by a -.

Example:

dog-2-13
dog-13-54-3
dog-25
cat-63-12
cat

I want them to be sorted firstly by the string in front and then by each of the "number sections" so that: dog-2-14 > dog-2-13 but dog-1-14 < dog-2-13.

Expected result (with more examples to make it clearer):

cat
cat-63-12
dog-2-13
dog-2-14
dog-3
dog-13-53-3
dog-13-54-3
dog-13-54-4
dog-25

I'm a SQL novice and completely lost. Thank you!

Body:
Please try...

SELECT fieldName
FROM
(
    SELECT fieldName AS fieldName,
           SUBSTRING_INDEX( fieldName,
                            '-',
                            1 ) AS stringComponent,
           CONVERT( SUBSTRING_INDEX( SUBSTRING( fieldName,
                                                CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 1 ) ) + 2 ),
                                     '-',
                                     1 ),
                    UNSIGNED ) AS firstNumber,
           CONVERT( SUBSTRING_INDEX( SUBSTRING( fieldName,
                                                CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 2 ) ) + 2 ),
                                     '-',
                                     1 ),
                    UNSIGNED ) AS secondNumber,
           CONVERT( SUBSTRING( fieldName,
                               CHAR_LENGTH( SUBSTRING_INDEX( fieldName, '-', 3 ) ) + 2 ),
                    UNSIGNED ) AS thirdNumber
    FROM table1
    ORDER BY stringComponent,
             firstNumber,
             secondNumber,
             thirdNumber
) tempTable;

The inner SELECT grabs the field name (which I am assuming is fieldName) and the three components and places each in a separate field and assigning an alias to that field.  Each subfield must be included at this point for sorting purposes.  The list is then sorted based upon those values.

Once this sorting is performed the outer SELECT chooses the original field from the list in a now sorted order.

The four outer instances of SUBSTRING_INDEX() are used to grab the desired fields from their first argument.  As SUBSTRING_INDEX() grabs all of the string from the beginning to just before the first occurence of the delimiting character this makes finding the first field easy (Note : I am assuming that the first field shall contain no hyphens).

The first argument for the remaining occurences of SUBSTRING_INDEX() is formed by using SUBSTRING() to grab everything from just after the parsed part of fieldName and the following delimiting character.  It is told where this is by using CHAR_LENGTH() to count the number of characters before the most recent delimiting character then adding 1 for the most recent delimiting character and another 1 to point SUBSTRING() to the character after the most recent delimiting character.

SUBSTRING_INDEX() will return NULL where it encounters an absent numerical field.  Please note that NULL has a different sort value from zero.

The numerical fields are converted into unsigned Integers using CONVERT().  Unsigned integers were chosen as the supplied data does not contain any real numbers.  If there are real values then you will need to replace UNSIGNED with DECIMAL.  I have also assumed that all of the numbers will be positive.

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_char-length

https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_convert

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
this and protoype javascript
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?</p>

```<code>function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);
</code>```

答:
The prototype property is a property of a constructor function. It's not a property of objects created with that constructor function.

Internally any object must know what its prototype is, but it's not exposed as a property with a name.

In some implementations it may be given a weird name. In Firefox it's called __proto__, but obviously you can't rely on that working in any other browser.

http://www.packtpub.com/article/using-prototype-property-in-javascript

Title: this and protoype javascript

Body:
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?

function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);


问:
Check input data and its sequence by MySQL
i want a drag and drop question and its options in  to be fetched from mysql table and make all options in a correct sequence. how to check my sequence to table correct sequence. i have this drag and drop code.

in this example we know correct sequence is 1,2,3,4,5,6,7. when we will drag all in correct order and submit it, how we match submitted sequence with correct sequence automatically. this is a kind of education test game.

```<code><style>
  body {
    font-family: arial;
    background: rgb(242, 244, 246);
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  h3 {
    color: rgb(199, 204, 209);
    font-size: 28px;
    text-align: center;
  }

  #elements-container {
    text-align: center;
  }

  .draggable-element {
    display: inline-block;
    width: 200px;
    height: 200px;
    background: white;
    border: 1px solid rgb(196, 196, 196);
    line-height: 200px;
    text-align: center;
    margin: 10px;
    color: rgb(51, 51, 51);
    font-size: 30px;
    cursor: move;
  }

  .drag-list {
    width: 400px;
    margin: 0 auto;
  }

  .drag-list > li {
    list-style: none;
    background: rgb(255, 255, 255);
    border: 1px solid rgb(196, 196, 196);
    margin: 5px 0;
    font-size: 24px;
  }

  .drag-list .title {
    display: inline-block;
    width: 130px;
    padding: 6px 6px 6px 12px;
    vertical-align: top;
  }

  .drag-list .drag-area {
    display: inline-block;
    background: rgb(158, 211, 179);
    width: 60px;
    height: 40px;
    vertical-align: top;
    float: right;
    cursor: move;
  }

  .code {
    background: rgb(255, 255, 255);
    border: 1px solid rgb(196, 196, 196);
    width: 600px;
    margin: 22px auto;
    position: relative;
  }

  .code::before {
    content: 'Code';
    background: rgb(80, 80, 80);
    width: 96%;
    position: absolute;
    padding: 8px 2%;
    color: rgb(255, 255, 255);
  }

  .code pre {
    margin-top: 50px;
    padding: 0 13px;
    font-size: 1em;
  }

</style>
</code>```

```<code>    <section class="showcase showcase-2">
      <h3>Example 2</h3>
      <ul class="drag-list">
        <li><span class="title">list 6</span><span class="drag-area"></span></li>
        <li><span class="title">list 4</span><span class="drag-area"></span></li>
        <li><span class="title">list 5</span><span class="drag-area"></span></li>
        <li><span class="title">list 1</span><span class="drag-area"></span></li>
        <li><span class="title">list 3</span><span class="drag-area"></span></li>
        <li><span class="title">list 2</span><span class="drag-area"></span></li>
        <li><span class="title">list 7</span><span class="drag-area"></span></li>
      </ul>
    </section>

    <section class="code">
      ```
$('li').arrangeable({dragSelector: '.drag-area'});
      ```
    </section>

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="drag-arrange.js"></script>

    <script type="text/javascript">
      $(function() {
          $('.draggable-element').arrangeable();
          $('li').arrangeable({dragSelector: '.drag-area'});
      });
    </script>
</code>```

答:
i got this working. but how to apply this for multiple questions fetching automatically from database.

```<code> <script>
  $(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});

var LISTOBJ = {
    saveList: function() {
        var listCSV = "";
        $( "#sortable li" ).each(function() {
            if (listCSV === "") {
                listCSV = $(this).val();
            } else {
                listCSV += "," + $(this).val();
            }
            $("#output").text(listCSV);
            $("#hiddenListInput").val(listCSV);
            //$("#listsaveform").submit();
        });
    }
}
</code>```

```<code> <ul id="sortable">
  <li value="1" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
  <li value="2" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
  <li value="3" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>

</ul>
<input type="button" id="savebutton" value="save"/>
<div id="output"></div>
<form id="listsaveform" method="POST" action="script.php">
    <input type="hidden" name="list" id="hiddenListInput" />
</form>
</code>```

Body:
i want a drag and drop question and its options in  to be fetched from mysql table and make all options in a correct sequence. how to check my sequence to table correct sequence. i have this drag and drop code.

in this example we know correct sequence is 1,2,3,4,5,6,7. when we will drag all in correct order and submit it, how we match submitted sequence with correct sequence automatically. this is a kind of education test game.

Example 2

list 6

list 4

list 5

list 1

list 3

list 2

list 7

$('li').arrangeable({dragSelector: '.drag-area'});

Body:
i got this working. but how to apply this for multiple questions fetching automatically from database.

 <script>
  $(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});

var LISTOBJ = {
    saveList: function() {
        var listCSV = "";
        $( "#sortable li" ).each(function() {
            if (listCSV === "") {
                listCSV = $(this).val();
            } else {
                listCSV += "," + $(this).val();
            }
            $("#output").text(listCSV);
            $("#hiddenListInput").val(listCSV);
            //$("#listsaveform").submit();
        });
    }
}

 <ul id="sortable">
  <li value="1" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
  <li value="2" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
  <li value="3" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>

</ul>
<input type="button" id="savebutton" value="save"/>
<div id="output"></div>
<form id="listsaveform" method="POST" action="script.php">
    <input type="hidden" name="list" id="hiddenListInput" />
</form>


问:
RecyclerView Items are not changing
I have a RecyclerView in a fragment which is repeating in TabLayout. I am having the problem of unchanged view in RecyclerView. I have a spinner on each tab. I want to change the data when spinner items get selected.

My cases:

when switching between tabs - items changed

when selecting another value in the spinner in the first tab -items not changed. (but data is changing in adapter class.Ie. First, it is not null then null during selection. But the first not nulled data is not appearing, its replacing with null. Found it using breakpoints).

Note: In this case, when switching the tab, the items get changed to
  the spinner selected items in the previous tab. And then it disappears
  and displaying the current items in the tab.

when selecting another value in the spinner in the last tab -items changed.

My view pager adapter class

```<code>public class StudentViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<StudentList> mFragmentList = new ArrayList<>();
    private final List<Clazz> mFragmentTitleList = new ArrayList<>();
    public StudentViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    public void addFragment(StudentList fragment,Clazz clazz){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(clazz);
    }
    @Override
    public Fragment getItem(int position) {
        return StudentList.newInstance(mFragmentTitleList.get(position));
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position).getName();
    }
}
</code>```

my RecyclerView adapter class

```<code>public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.MyViewHolder> implements View.OnClickListener {
    private List<Student> dataList;
    private Context context;
    private Clicker clicker;
    public PeopleAdapter(List<Student> data, Context context, Clicker clicker) {
        this.dataList = data;
        this.context = context;
        this.clicker = clicker;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.people_list_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Student data=dataList.get(position);
        holder.email.setText(data.getEmail());
        holder.name.setText(data.getName());
        holder.phone.setText(data.getPhone());
        Glide.with(context).load(Method.getImageUrl(MyConfiguration.STUDENT_IMAGE_URL,
                data.getStudentId())).asBitmap().into(holder.profilePic);
        holder.edit.setOnClickListener(this);
        holder.edit.setTag(position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @Override
    public void onClick(View v) {
        clicker.OnItemClicked((int) v.getTag(),null);
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.name)
        TextView name;
        @BindView(R.id.email)
        TextView email;
        @BindView(R.id.phone)
        TextView phone;
        @BindView(R.id.image)
        ImageView profilePic;
        @BindView(R.id.imageedit)
        ImageView edit;
    MyViewHolder(View view) {
        super(view);
        ButterKnife.bind(this,view);
    }
}

}
</code>```

tab fragments

```<code>    public class StudentList extends Fragment implements SectionChanger {
        @BindView(R.id.studentlist)
        RecyclerView mRecyclerview;
        CompositeDisposable disposable;
        private Unbinder unbinder;
        private Clazz clazz;
        private Requester requester;

        public StudentList() {
            StudentInformation.bindSectionChangeListener(this);
        }
        public static StudentList newInstance(Clazz clazz) {
            StudentList fragment=new StudentList();
            Bundle args = new Bundle();
            args.putSerializable(MyConfiguration.SECTIONS, clazz);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
            disposable.clear();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_student_list, container, false);
            unbinder = ButterKnife.bind(this, view);
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerview.setLayoutManager(mLayoutManager);
            initializeRetrofit();
            if (getArguments() != null) {
                clazz = (Clazz) getArguments().getSerializable(MyConfiguration.SECTIONS);
                loadStudentJson(clazz != null ? clazz.getClassId() : null,
                        clazz != null ? clazz.getSections().get(0).getSectionId() : null);
            }
            return view;
        }

        /**
         * Load students list
         */
        public void loadStudentJson(String class_id,String section_id) {

            disposable = new CompositeDisposable(requester.getStudentsInSection(class_id,section_id)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                            this::handleResponse,
                            this::handleError
                    )
            );
        }

        private void handleResponse(List<Student> list) {
            PeopleAdapter adapter=new PeopleAdapter(list, getActivity(),
                    (position, name) -> Toast.makeText(getActivity(), position, Toast.LENGTH_LONG).show());
            mRecyclerview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        private void handleError(Throwable error) {
            Toast.makeText(getActivity(), "Error " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void ChangeData(Section section) {
            loadStudentJson(section.getClassId(),section.getSectionId());
        }
        public void initializeRetrofit(){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            CookieHandler handler=new Cookies(getActivity());
            //ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .cookieJar(new JavaNetCookieJar(handler))
                    .build();

            requester = new Retrofit.Builder()
                    .baseUrl(MyConfiguration.BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(JacksonConverterFactory.create())
                    .client(client)
                    .build().create(Requester.class);
        }
    }
</code>```

Viewpager setup fragment

```<code>public class StudentInformation extends Fragment implements TabLayout.OnTabSelectedListener, AdapterView.OnItemSelectedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    CompositeDisposable disposable;
    List<Section> sectionsList=new ArrayList<>();
    private OnConnectingFragments mListener;
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.secSelector)
    Spinner spinner;
    @BindView(R.id.className)
    TextView className;
    private static SectionChanger sectionChanger;
    public StudentInformation() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StudentInformation.
     */
    // TODO: Rename and change types and number of parameters
    public static StudentInformation newInstance(String param1, String param2) {
        StudentInformation fragment = new StudentInformation();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        disposable.clear();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_student_information, container, false);
        unbinder = ButterKnife.bind(this, view);
        LoadDataAndSetupViewPager();
        //setupViewPager(viewPager);
        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.addOnTabSelectedListener(this);
        spinner.setOnItemSelectedListener(this);
//        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, MyConfiguration.CLASS_SECTIONS);
//        spinner.setAdapter(arrayAdapter);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Fragment fragment,String tag) {
        if (mListener != null) {
            mListener.onClickedMenu(fragment,tag);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnConnectingFragments) {
            mListener = (OnConnectingFragments) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    /*private void setupViewPager(ViewPager viewPager) {
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (String claz: MyConfiguration.CLASS)
            adapter.addFragment(new StudentList(), claz);
        viewPager.setAdapter(adapter);
    }*/
    @OnClick(R.id.add)
    public void OnClicked(LinearLayout view){
        onButtonPressed(new AddStudent(),"addStudent");
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        className.setText(String.format(getString(R.string.class_name), tab.getPosition()+1));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
    public void LoadDataAndSetupViewPager() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Requester requester=new Retrofit.Builder()
                .baseUrl(MyConfiguration.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build().create(Requester.class);
        disposable=new CompositeDisposable(requester.getClasses()    ////GETTING CLASSES////
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .flatMapIterable(clazzs -> clazzs)
                .flatMap(clazz -> requester.getDivision(clazz.getClassId())  ////GETTING SECTIONS////
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .flatMapIterable(sections -> sections)
                        .doOnNext(section -> {sectionsList.add(section);
                            Log.v("section_id",section.getSectionId());})
                        .takeLast(1)
                        .map(section -> clazz)
                )
                .doOnNext(clazz -> {clazz.setSections(sectionsList);
                    Log.v("List Size",sectionsList.size()+"");
                    sectionsList=new ArrayList<>();
                })
                .toList()
                .subscribe(this::SetupViewPager, throwable -> Log.e("retroerror",throwable.toString())));

    }
    public void SetupViewPager(List<Clazz> classList){
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (Clazz claz: classList){
            adapter.addFragment(new StudentList(), claz);
        }

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                List<Section>sections=classList.get(position).getSections();
                ArrayAdapter<Section> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, sections);
                spinner.setAdapter(arrayAdapter);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Section section= (Section) parent.getItemAtPosition(position);
                sectionChanger.ChangeData(section);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public static void bindSectionChangeListener(SectionChanger changer){
        sectionChanger=changer;
    }
}
</code>```

The question is: Why the data get unchanged when selecting options in the spinner sometimes? (look my cases)

答:
Check your StudentViewPagerAdapter

```<code> @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position).newInstance(mFragmentTitleList.get(position));
    }
</code>```

why do you call newInstance again?

Replace it with the following,
return mFragmentList.get(position);

Title: RecyclerView Items are not changing

Body:
I have a RecyclerView in a fragment which is repeating in TabLayout. I am having the problem of unchanged view in RecyclerView. I have a spinner on each tab. I want to change the data when spinner items get selected.

My cases:

when switching between tabs - items changed

when selecting another value in the spinner in the first tab -items not changed. (but data is changing in adapter class.Ie. First, it is not null then null during selection. But the first not nulled data is not appearing, its replacing with null. Found it using breakpoints).

Note: In this case, when switching the tab, the items get changed to
  the spinner selected items in the previous tab. And then it disappears
  and displaying the current items in the tab.

when selecting another value in the spinner in the last tab -items changed.

My view pager adapter class

public class StudentViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<StudentList> mFragmentList = new ArrayList<>();
    private final List<Clazz> mFragmentTitleList = new ArrayList<>();
    public StudentViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    public void addFragment(StudentList fragment,Clazz clazz){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(clazz);
    }
    @Override
    public Fragment getItem(int position) {
        return StudentList.newInstance(mFragmentTitleList.get(position));
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position).getName();
    }
}

my RecyclerView adapter class

public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.MyViewHolder> implements View.OnClickListener {
    private List<Student> dataList;
    private Context context;
    private Clicker clicker;
    public PeopleAdapter(List<Student> data, Context context, Clicker clicker) {
        this.dataList = data;
        this.context = context;
        this.clicker = clicker;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.people_list_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Student data=dataList.get(position);
        holder.email.setText(data.getEmail());
        holder.name.setText(data.getName());
        holder.phone.setText(data.getPhone());
        Glide.with(context).load(Method.getImageUrl(MyConfiguration.STUDENT_IMAGE_URL,
                data.getStudentId())).asBitmap().into(holder.profilePic);
        holder.edit.setOnClickListener(this);
        holder.edit.setTag(position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @Override
    public void onClick(View v) {
        clicker.OnItemClicked((int) v.getTag(),null);
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.name)
        TextView name;
        @BindView(R.id.email)
        TextView email;
        @BindView(R.id.phone)
        TextView phone;
        @BindView(R.id.image)
        ImageView profilePic;
        @BindView(R.id.imageedit)
        ImageView edit;
    MyViewHolder(View view) {
        super(view);
        ButterKnife.bind(this,view);
    }
}

}

tab fragments

    public class StudentList extends Fragment implements SectionChanger {
        @BindView(R.id.studentlist)
        RecyclerView mRecyclerview;
        CompositeDisposable disposable;
        private Unbinder unbinder;
        private Clazz clazz;
        private Requester requester;

        public StudentList() {
            StudentInformation.bindSectionChangeListener(this);
        }
        public static StudentList newInstance(Clazz clazz) {
            StudentList fragment=new StudentList();
            Bundle args = new Bundle();
            args.putSerializable(MyConfiguration.SECTIONS, clazz);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
            disposable.clear();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_student_list, container, false);
            unbinder = ButterKnife.bind(this, view);
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerview.setLayoutManager(mLayoutManager);
            initializeRetrofit();
            if (getArguments() != null) {
                clazz = (Clazz) getArguments().getSerializable(MyConfiguration.SECTIONS);
                loadStudentJson(clazz != null ? clazz.getClassId() : null,
                        clazz != null ? clazz.getSections().get(0).getSectionId() : null);
            }
            return view;
        }

        /**
         * Load students list
         */
        public void loadStudentJson(String class_id,String section_id) {

            disposable = new CompositeDisposable(requester.getStudentsInSection(class_id,section_id)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                            this::handleResponse,
                            this::handleError
                    )
            );
        }

        private void handleResponse(List<Student> list) {
            PeopleAdapter adapter=new PeopleAdapter(list, getActivity(),
                    (position, name) -> Toast.makeText(getActivity(), position, Toast.LENGTH_LONG).show());
            mRecyclerview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        private void handleError(Throwable error) {
            Toast.makeText(getActivity(), "Error " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void ChangeData(Section section) {
            loadStudentJson(section.getClassId(),section.getSectionId());
        }
        public void initializeRetrofit(){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            CookieHandler handler=new Cookies(getActivity());
            //ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .cookieJar(new JavaNetCookieJar(handler))
                    .build();

            requester = new Retrofit.Builder()
                    .baseUrl(MyConfiguration.BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(JacksonConverterFactory.create())
                    .client(client)
                    .build().create(Requester.class);
        }
    }

Viewpager setup fragment

public class StudentInformation extends Fragment implements TabLayout.OnTabSelectedListener, AdapterView.OnItemSelectedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    CompositeDisposable disposable;
    List
 sectionsList=new ArrayList<>();
    private OnConnectingFragments mListener;
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.secSelector)
    Spinner spinner;
    @BindView(R.id.className)
    TextView className;
    private static SectionChanger sectionChanger;
    public StudentInformation() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StudentInformation.
     */
    // TODO: Rename and change types and number of parameters
    public static StudentInformation newInstance(String param1, String param2) {
        StudentInformation fragment = new StudentInformation();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        disposable.clear();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_student_information, container, false);
        unbinder = ButterKnife.bind(this, view);
        LoadDataAndSetupViewPager();
        //setupViewPager(viewPager);
        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.addOnTabSelectedListener(this);
        spinner.setOnItemSelectedListener(this);
//        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, MyConfiguration.CLASS_SECTIONS);
//        spinner.setAdapter(arrayAdapter);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Fragment fragment,String tag) {
        if (mListener != null) {
            mListener.onClickedMenu(fragment,tag);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnConnectingFragments) {
            mListener = (OnConnectingFragments) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    /*private void setupViewPager(ViewPager viewPager) {
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (String claz: MyConfiguration.CLASS)
            adapter.addFragment(new StudentList(), claz);
        viewPager.setAdapter(adapter);
    }*/
    @OnClick(R.id.add)
    public void OnClicked(LinearLayout view){
        onButtonPressed(new AddStudent(),"addStudent");
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        className.setText(String.format(getString(R.string.class_name), tab.getPosition()+1));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
    public void LoadDataAndSetupViewPager() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Requester requester=new Retrofit.Builder()
                .baseUrl(MyConfiguration.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build().create(Requester.class);
        disposable=new CompositeDisposable(requester.getClasses()    ////GETTING CLASSES////
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .flatMapIterable(clazzs -> clazzs)
                .flatMap(clazz -> requester.getDivision(clazz.getClassId())  ////GETTING SECTIONS////
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .flatMapIterable(sections -> sections)
                        .doOnNext(section -> {sectionsList.add(section);
                            Log.v("section_id",section.getSectionId());})
                        .takeLast(1)
                        .map(section -> clazz)
                )
                .doOnNext(clazz -> {clazz.setSections(sectionsList);
                    Log.v("List Size",sectionsList.size()+"");
                    sectionsList=new ArrayList<>();
                })
                .toList()
                .subscribe(this::SetupViewPager, throwable -> Log.e("retroerror",throwable.toString())));

    }
    public void SetupViewPager(List<Clazz> classList){
        StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());
        //adapter.addFragment(new StudentList(),"exam");

        for (Clazz claz: classList){
            adapter.addFragment(new StudentList(), claz);
        }

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                List
sections=classList.get(position).getSections();
                ArrayAdapter
 arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, sections);
                spinner.setAdapter(arrayAdapter);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Section section= (Section) parent.getItemAtPosition(position);
                sectionChanger.ChangeData(section);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public static void bindSectionChangeListener(SectionChanger changer){
        sectionChanger=changer;
    }
}

The question is: Why the data get unchanged when selecting options in the spinner sometimes? (look my cases)

Body:
Check your StudentViewPagerAdapter

 @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position).newInstance(mFragmentTitleList.get(position));
    }

why do you call newInstance again?

Replace it with the following,
return mFragmentList.get(position);