问:
NodeJS Cannot find module 'io' ( socket.io with express 4.15.3)
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

```<code>Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)
</code>```

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

```<code>let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
</code>```

client.js

```<code>$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('<li>').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('<span class="username"/>')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('<span class="messageBody">')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('<li class="message"/>')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('<div/>').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});
</code>```

index.ejs

```<code><% include partials/header %>
    <h1><%= title %></h1>
    <ul class="pages">
    <li class="chat page">
      <div class="chatArea">
        <ul class="messages"></ul>
      </div>
      <input class="inputMessage" placeholder="Type here..."/>
    </li>
    <li class="login page">
      <div class="form">
        <h3 class="title">What's your nickname?</h3>
        <input class="usernameInput" type="text" maxlength="14" />
      </div>
    </li>
  </ul>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="/javascript/socket.io.js"></script>
    <script src="/javascript/client.js"></script>
<% include partials/footer %>
</code>```

package.json

```<code>{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}
</code>```

答:
I find my bug.
I removed this code

```<code>app.listen(3000, () => {
    console.log('server started on port 3000....');
});
</code>```

and added this

```<code>server.listen(3000);
</code>```

after this

```<code>var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
</code>```

thanks to @Curious for helping and great answer
socket.io - can't get it to work, having 404's on some kind of polling call

Body:
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});

client.js

$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('
').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('
')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('
').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});

index.ejs

<% include partials/header %>

<%= title %>

      <input class="inputMessage" placeholder="Type here..."/>

What's your nickname?

        <input class="usernameInput" type="text" maxlength="14" />

<% include partials/footer %>

package.json

{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}

Body:
I find my bug.
I removed this code

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

and added this

server.listen(3000);

after this

var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

thanks to @Curious for helping and great answer
socket.io - can't get it to work, having 404's on some kind of polling call


来源: stackexchange

问:
How to convert comma separated string values into a List<string> using asp.net mvc5
want to convert comma separated string values into a List

have tried

```<code>public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}
</code>```

答:
Check this out:</p>

```<code>public ActionResult Index()
{
      //Your original string
      string yourCommaDelimitedString = "TN,KA,KL";

      //Use the String.Split() method to break the string into an array containing all of your values and then
      //convert it to a List using the Enumerable.ToList() method
      List<string> yourValues = yourCommaDelimitedString.Split(',').ToList();

      //Add your values to the ViewData to be bound to a DropDown
      ViewData["Options"] = new SelectList(yourValues);

      return View();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
want to convert comma separated string values into a List

have tried

public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}

Body:
Check this out:

public ActionResult Index()
{
      //Your original string
      string yourCommaDelimitedString = "TN,KA,KL";

      //Use the String.Split() method to break the string into an array containing all of your values and then
      //convert it to a List using the Enumerable.ToList() method
      List<string> yourValues = yourCommaDelimitedString.Split(',').ToList();

      //Add your values to the ViewData to be bound to a DropDown
      ViewData["Options"] = new SelectList(yourValues);

      return View();
}


问:
SQL Server Catch exception and continue
Ive follow procedure:

```<code>alter procedure sp_insert_cities
(
    @txt_nome_cidade varchar(300),
    @txt_nome_estado varchar(150) = null,
    @txt_pais varchar(150) = null,
    @int_id_cidade int output
)
as
begin
            //Here an exception may occur
            insert into tb_cidades values(
            @txt_nome_cidade,
            @txt_nome_estado,
            @txt_pais)

            set @int_id_cidade = @@identity

            //Here i want to catch exception and continue executing the proc
            if(@@error <> 0)
            begin
            select @int_id_cidade = int_id_cidade
            from tb_cidades
            where
            txt_nome_cidade = @txt_nome_cidade
            end
</code>```

After if(@@error <> 0) line,i want to continue executing code even if there are any errors,but SQL throws an exception to my application and the code inside IF condition will not executed.

Any ideas?

答:
```<code>BEGIN TRY
       insert into tb_cidades values(
            @txt_nome_cidade,
            @txt_nome_estado,
            @txt_pais)

            set @int_id_cidade = @@identity
END TRY

BEGIN CATCH
           select @int_id_cidade = int_id_cidade
            from tb_cidades
            where
            txt_nome_cidade = @txt_nome_cidade
END CATCH
</code>```

Title: SQL Server Catch exception and continue

Body:
Ive follow procedure:

alter procedure sp_insert_cities
(
    @txt_nome_cidade varchar(300),
    @txt_nome_estado varchar(150) = null,
    @txt_pais varchar(150) = null,
    @int_id_cidade int output
)
as
begin
            //Here an exception may occur
            insert into tb_cidades values(
            @txt_nome_cidade,
            @txt_nome_estado,
            @txt_pais)

            set @int_id_cidade = @@identity

            //Here i want to catch exception and continue executing the proc
            if(@@error <> 0)
            begin
            select @int_id_cidade = int_id_cidade
            from tb_cidades
            where
            txt_nome_cidade = @txt_nome_cidade
            end

After if(@@error <> 0) line,i want to continue executing code even if there are any errors,but SQL throws an exception to my application and the code inside IF condition will not executed.

Any ideas?

ContentLicense: CC BY-SA 2.5


问:
Exclude from brace expansion
I know that

```<code>echo {1..10}
</code>```

do

```<code>1 2 3 4 5 6 7 8 9 10
</code>```

but i do not want 6 and 7. Is it possible to exclude it?

答:
It can be done with

```<code>echo {1..5} {8..10}
</code>```

but One more solution I found:

```<code>echo {{1..5},{8..10}}
</code>```

Title: Exclude from brace expansion

Body:
I know that

echo {1..10}

do

1 2 3 4 5 6 7 8 9 10

but i do not want 6 and 7. Is it possible to exclude it?

Body:
It can be done with

echo {1..5} {8..10}

but One more solution I found:

echo {{1..5},{8..10}}


问:
Getting R rJava running on OSX El Capitan
I have been reading various solutions for the last 24 hours. They don't work for me.

I was trying to get a package glmulti installed in R. It wanted rJava.

That needed a version 6 (or is it 1.6) of Java, which was found as javaforosx 2015-001. I installed it. The instructions then suggested to reconfigure R using the command sudo R CMD javareconf, I ran into an error:

```<code>Java interpreter : /usr/bin/java
Java version     : 1.6.0_65
Java home path   : /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Java compiler    : /usr/bin/javac
Java headers gen.: /usr/bin/javah
Java archive tool: /usr/bin/jar
System Java on macOS

trying to compile and link a JNI program
detected JNI cpp flags    : -I/System/Library/Frameworks/JavaVM.framework/Headers
detected JNI linker flags : -framework JavaVM
clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/System/Library/Frameworks/JavaVM.framework/Headers -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include    -fPIC  -Wall -mtune=core2 -g -O2  -c conftest.c -o conftest.o
conftest.c:1:10: fatal error: 'jni.h' file not found
#include <jni.h>
</code>```

There are a lot of pages suggesting what to do but nothing works for me.

I looked at the suggestions from
http://conjugateprior.org/2014/12/r-java8-osx/
and thought that perhaps I should use java 8 from Oracle. Installed that as well.

What was odd was that after installation of java 8, the Java Control Panel on the System Preferences page said that I have java 1.8.0_121, and the path given was
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

But if I do terminal command /usr/libexec/java_home I get

```<code>/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
</code>```

and if I do /usr/libexec/java_home -v 1.8 I get

```<code>Unable to find any JVMs matching version "1.8".
/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
</code>```

Other people claim that this command should have given the 1.8.0 path.

The test web page from Oracle claims that I do have 1.8.0 installed.
The command java -version claims that I am running

```<code>java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-468-11M4833)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-468, mixed mode)
</code>```

After all this, the first problem seems to be how to get a hold of jni.h?

If you need any more information, just ask.

答:
Take a look here:

http://www.owsiak.org/?p=3671

you can find there quite detailed explanation on how to deal with R, Java and rJava on macOS.

There are some steps you have to take to make the whole process go smooth.

Have fun with R and JNI!

Body:
I have been reading various solutions for the last 24 hours. They don't work for me.

I was trying to get a package glmulti installed in R. It wanted rJava.

That needed a version 6 (or is it 1.6) of Java, which was found as javaforosx 2015-001. I installed it. The instructions then suggested to reconfigure R using the command sudo R CMD javareconf, I ran into an error:

Java interpreter : /usr/bin/java
Java version     : 1.6.0_65
Java home path   : /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Java compiler    : /usr/bin/javac
Java headers gen.: /usr/bin/javah
Java archive tool: /usr/bin/jar
System Java on macOS

trying to compile and link a JNI program
detected JNI cpp flags    : -I/System/Library/Frameworks/JavaVM.framework/Headers
detected JNI linker flags : -framework JavaVM
clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/System/Library/Frameworks/JavaVM.framework/Headers -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include    -fPIC  -Wall -mtune=core2 -g -O2  -c conftest.c -o conftest.o
conftest.c:1:10: fatal error: 'jni.h' file not found
#include <jni.h>

There are a lot of pages suggesting what to do but nothing works for me.

I looked at the suggestions from
http://conjugateprior.org/2014/12/r-java8-osx/
and thought that perhaps I should use java 8 from Oracle. Installed that as well.

What was odd was that after installation of java 8, the Java Control Panel on the System Preferences page said that I have java 1.8.0_121, and the path given was
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

But if I do terminal command /usr/libexec/java_home I get

/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

and if I do /usr/libexec/java_home -v 1.8 I get

Unable to find any JVMs matching version "1.8".
/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

Other people claim that this command should have given the 1.8.0 path.

The test web page from Oracle claims that I do have 1.8.0 installed.
The command java -version claims that I am running

java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-468-11M4833)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-468, mixed mode)

After all this, the first problem seems to be how to get a hold of jni.h?

If you need any more information, just ask.


问:
Displaying current and previous pay period in SQL (based on an imported table)
I need to display the current AND last pay periods based on an imported table for biweekly pay dates. The table looks something like this:

```<code>2017-03-23 00:00:00 2017-04-06 00:00:00
2017-04-07 00:00:00 2017-04-20 00:00:00
2017-04-21 00:00:00 2017-05-06 00:00:00
2017-05-07 00:00:00 2017-05-20 00:00:00
2017-05-21 00:00:00 2017-06-05 00:00:00
2017-06-06 00:00:00 2017-06-22 00:00:00
2017-06-23 00:00:00 2017-07-06 00:00:00
2017-07-07 00:00:00 2017-07-21 00:00:00
</code>```

This code:

```<code>     SELECT *
     FROM
       table1
     WHERE
       (start_date <= now()  AND end_date >= now())
</code>```

Displays:

```<code>2017-06-06 00:00:00 2017-06-22 00:00:00
</code>```

How can I display the previous pay period?
Such as:

```<code>2017-05-21 00:00:00 2017-06-05 00:00:00
</code>```

This code just doesn't even look right, but I tried it anyways:

```<code>SELECT start_date,
CASE
    WHEN start_date = now() THEN    start_date = now() - 1
    WHEN end_date = now() THEN start_date = now() - 1
END
FROM table1;
</code>```

I know there is a way to use CASE WHEN but for some reason, I cannot get the syntax right using now() since I want it to be dynamic and not a static date.

答:
try this

To get the current and previous pay period

```<code>SELECT start_date,
end_date
FROM table1
where start_date < now()
ORDER BY start_date desc
LIMIT 2;
</code>```

Body:
I need to display the current AND last pay periods based on an imported table for biweekly pay dates. The table looks something like this:

2017-03-23 00:00:00 2017-04-06 00:00:00
2017-04-07 00:00:00 2017-04-20 00:00:00
2017-04-21 00:00:00 2017-05-06 00:00:00
2017-05-07 00:00:00 2017-05-20 00:00:00
2017-05-21 00:00:00 2017-06-05 00:00:00
2017-06-06 00:00:00 2017-06-22 00:00:00
2017-06-23 00:00:00 2017-07-06 00:00:00
2017-07-07 00:00:00 2017-07-21 00:00:00

This code:

     SELECT *
     FROM
       table1
     WHERE
       (start_date <= now()  AND end_date >= now())

Displays:

2017-06-06 00:00:00 2017-06-22 00:00:00

How can I display the previous pay period?
Such as:

2017-05-21 00:00:00 2017-06-05 00:00:00

This code just doesn't even look right, but I tried it anyways:

SELECT start_date,
CASE
    WHEN start_date = now() THEN    start_date = now() - 1
    WHEN end_date = now() THEN start_date = now() - 1
END
FROM table1;

I know there is a way to use CASE WHEN but for some reason, I cannot get the syntax right using now() since I want it to be dynamic and not a static date.

Body:
try this

To get the current and previous pay period

SELECT start_date,
end_date
FROM table1
where start_date < now()
ORDER BY start_date desc
LIMIT 2;


问:
Gson multiple Serialized name same type
I have a class:

```<code>public void results{

@SerializedName("object1")
@Expose
private Object1 object1;

@SerializedName("object2")
@Expose
private Object2 object2;

@SerializedName("object3")
@Expose
private Object3 object3;

@SerializedName("object4")
@Expose
private Object4 object4;

@SerializedName("object5")
@Expose
private Object5 object5;

}
</code>```

In essence, all the objects are the same (have same fields and everything else), and the only reason that they are different is because of the json structure. (don't have control over the json structure).

Does anybody know anyway the Gson can be configured to parse an output:

If Serialized name equals "object1", "object2", "object3", "object4", "object5", create an object of Object1 and add them to a list of Object1?

Thank you

答:
Ended up using this code:</p>

```<code>public void results{

@SerializedName("object1")
@Expose
private Object1 object1;

@SerializedName("object2")
@Expose
private Object1 object2;

@SerializedName("object3")
@Expose
private Object1 object3;

@SerializedName("object4")
@Expose
private Object1 object4;

@SerializedName("object5")
@Expose
private Object1 object5;

}
</code>```

Title: Gson multiple Serialized name same type

Body:
I have a class:

public void results{

@SerializedName("object1")
@Expose
private Object1 object1;

@SerializedName("object2")
@Expose
private Object2 object2;

@SerializedName("object3")
@Expose
private Object3 object3;

@SerializedName("object4")
@Expose
private Object4 object4;

@SerializedName("object5")
@Expose
private Object5 object5;

}

In essence, all the objects are the same (have same fields and everything else), and the only reason that they are different is because of the json structure. (don't have control over the json structure).

Does anybody know anyway the Gson can be configured to parse an output:

If Serialized name equals "object1", "object2", "object3", "object4", "object5", create an object of Object1 and add them to a list of Object1?

Thank you

Body:
Ended up using this code:

public void results{

@SerializedName("object1")
@Expose
private Object1 object1;

@SerializedName("object2")
@Expose
private Object1 object2;

@SerializedName("object3")
@Expose
private Object1 object3;

@SerializedName("object4")
@Expose
private Object1 object4;

@SerializedName("object5")
@Expose
private Object1 object5;

}


问:
How to create auto increment IDs in Cassandra
We know that it is easy to create auto increment IDs in SQL databases, is there a good solution for it in Cassandra? The IDs should be for key or column name.</p>

答:
I think IMHO expecting Cassandra to provide an auto-incrementing field is WRONG

Cassandra is a elegant decentralised database, hence expecting it to provide a auto-incrmenting field is, taxing and defeats the original purpose, because this value has to be then maintained in a central place

Hence, don't make any solution which DB based to get a auto-incrementing number

Instead generate the ID in the code or service in your app, which can keep generating random unique IDs and use that to apply on your data model, this way the objective & benefit of Cassandra will not be defeated

ContentLicense: CC BY-SA 4.0


问:
python struct module packing and unpacking return values
I am using struct module for serializing the data to send the data over socket. I observed that struct.pack(frmt, value1, ...) returns a string of the value 1 in two bytes hexadecimal format. Why does it return only in two bytes format? There should be some reason. Maybe I am missing something while understanding struct class.

Thanks in advance.

答:
Read the documentation of the python struct module

If you concern about the size of the packed result read this


问:
flink sql window api
I tried to use flink sql window api:
https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/table_api.html#group-windows

```<code>StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);

// ingest a DataStream from an external source
DataStream<Tuple3<Long, String, Integer>> ds = env.addSource(...);
// register the DataStream as table "Orders"
tableEnv.registerDataStream("Orders", ds, "user, product, amount");

// compute SUM(amount) per day (in event-time)
Table result1 = tableEnv.sql(
  "SELECT user, " +
  "  TUMBLE_START(rowtime(), INTERVAL '1' DAY) as wStart,  " +
  "  SUM(amount) FROM Orders " +
  "GROUP BY TUMBLE(rowtime(), INTERVAL '1' DAY), user");
</code>```

show the error:

No match found for function signature rowtime()

Please give me a more detail example about flink-sql-window api with rowtime.Thx.

答:
At the moment the docs are a bit out of sync, but the community is working on it in a separate branch. Flink 1.3 introduces so called "time attributes" in order to access, express, and work with time more explicitly in the future.

You can find more information in the current documentation draft. Some examples how to use the time attributes in a table program can be found here.

Title: flink sql window api

Body:
I tried to use flink sql window api:
https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/table_api.html#group-windows

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);

// ingest a DataStream from an external source
DataStream<Tuple3<Long, String, Integer>> ds = env.addSource(...);
// register the DataStream as table "Orders"
tableEnv.registerDataStream("Orders", ds, "user, product, amount");

// compute SUM(amount) per day (in event-time)
Table result1 = tableEnv.sql(
  "SELECT user, " +
  "  TUMBLE_START(rowtime(), INTERVAL '1' DAY) as wStart,  " +
  "  SUM(amount) FROM Orders " +
  "GROUP BY TUMBLE(rowtime(), INTERVAL '1' DAY), user");

show the error:

No match found for function signature rowtime()

Please give me a more detail example about flink-sql-window api with rowtime.Thx.


问:
navigator.geolocation.getCurrentPosition not working with onClick
I'm having a strange issue that I can get the geolocation (immediately) inside the componentDidMount() function but when I click the button and execute geolocateMe() I get a PositionError after 5 seconds.

Anyone has an idea how to make navigator.geolocation.getCurrentPosition() work with an onClick trigger?

Using Chrome 59 and I allowed my application to "Track your location".

```<code>import React, { Component } from 'react';

export default class GetGeolocation extends Component {

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  geolocateMe() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  render() {
    return (
      <button onClick={() => this.geolocateMe()}>Geolocate me</button>
    );
  }
}
</code>```

First visit

console log

Position {coords: Coordinates, timestamp: 1496902322562}

Click on button

console log  (after 5 seconds)

PositionError {code: 3, message: "Timeout expired"}

EDIT

navigator.geolocation.watchPosition() is aso being used inside a higher component.

答:
Found the issue.

Inside a higher component I was using navigator.geolocation.watchPosition() and this seems to block navigator.geolocation.getCurrentPosition(). The first getCurrentPosition() inside componentDidMount() was probably executed successfully because of being faster than watchPosition().

Removing watchPosition() from the higher component made the onClick function geolocateMe() work as expected.

Body:
I'm having a strange issue that I can get the geolocation (immediately) inside the componentDidMount() function but when I click the button and execute geolocateMe() I get a PositionError after 5 seconds.

Anyone has an idea how to make navigator.geolocation.getCurrentPosition() work with an onClick trigger?

Using Chrome 59 and I allowed my application to "Track your location".

import React, { Component } from 'react';

export default class GetGeolocation extends Component {

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  geolocateMe() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  render() {
    return (
      <button onClick={() => this.geolocateMe()}>Geolocate me</button>
    );
  }
}

First visit

console log

Position {coords: Coordinates, timestamp: 1496902322562}

Click on button

console log  (after 5 seconds)

PositionError {code: 3, message: "Timeout expired"}

EDIT

navigator.geolocation.watchPosition() is aso being used inside a higher component.


问:
Export variable from within while loop
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

```<code>var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done
</code>```

答:
The idea is right, just use the declare variable to create variables on the fly. Also avoid using un-quoted variable expansion(for i in ${var}) for looping. Use a proper array syntax as

```<code>var=("ahs" "tcs" "amq" "tos")

for i in "${var[@]}"; do
    declare ${i}_log="/var/tmp/pmp_${i}_log"
    export "${i}_log"
done
</code>```

As a side note for good practice, always specify the interpreter to run your script. It could be #!/bin/bash or #!/bin/sh or best do it by #!/usr/bin/env bash

Title: Export variable from within while loop

Body:
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done

Body:
The idea is right, just use the declare variable to create variables on the fly. Also avoid using un-quoted variable expansion(for i in ${var}) for looping. Use a proper array syntax as

var=("ahs" "tcs" "amq" "tos")

for i in "${var[@]}"; do
    declare ${i}_log="/var/tmp/pmp_${i}_log"
    export "${i}_log"
done

As a side note for good practice, always specify the interpreter to run your script. It could be #!/bin/bash or #!/bin/sh or best do it by #!/usr/bin/env bash


问:
How should I provide help for a related set of functions?
I built tfs.el to allow developers to do TFS things (checkout, checkin, etc) from within emacs.

There are 13 interactive commands in the tfs package, like tfs/checkout,  tfs/rename, tfs/diff, and so on, and I'd like to be able to provide help on all of them in a single place. An overview of all the available functions.

What's the "emacs way" of doing that?  I thought of defining an additional function, like tfs/help , that would invoke describe-function-1 on each of the tfs functions, and then present all that in a TFS-Help buffer.

Is there a better way?

答:
Well, there are many "Emacs way"s.

The most polished would be to write an info page, see the page "Info for Experts", which basically says to use Texinfo and convert that into an info page.  You can be as verbose as you want there, and the user can search, use hyperlinks, etc.  The user can easily get there via C-h F tfs/checkout.

Another way some folks seem to do it is to write short documentation strings for each of the commands, ending with "see documentation for tfs-mode for details" and put all the common documentation in the docstring for tfs-mode.

Another way some packages document things is with a big comment at the top of the tfs.el file.

Take your pick, they all have trade-offs.


问:
sublime text3 How to sort folders on Sidebar by "Last modified" and not alphabetically?
Anyone help me for this.

I always wish to work with sublime text 3 by creating project,
And include folders on it like this,

This problem is every time I create a new folder for new website but it's goes to mixed in the whole folder, I've to bother to find among the folders.

I would like to show at the top/first, could you tell me if there anyway for this please ?

答:
No, changing the sort order in the sidebar is not currently possible (as at build 3133).

There is an open feature request for the sidebar sort order here:

https://github.com/SublimeTextIssues/Core/issues/328


问:
How can I stop the alpha-premultiplication with canvas imageData?
Is there a way to stop the premultiplication of the alpha channel for canvas data, or  a workaround?

I want to generate an image (in this case some random rgba values) and save the canvas as an image.

During the second step, I want to compare the original image with the generated image using the imageData, however this won't work due to the premultiplication of the alpha channel of my rgba pixels in the generated image.

The example

```<code>function drawImage(ctx) {
    var img = ctx.createImageData(canvas.width,canvas.height);

        for (var i=img.data.length;i-=4;) {
                img.data[i] = Math.floor(Math.random() * 255);
                img.data[i+1] = Math.floor(Math.random() * 255);
                img.data[i+2] = Math.floor(Math.random() * 255);
                img.data[i+3] = Math.floor(Math.random() * 255);
        }

        ctx.putImageData(img, 0, 0);
            // our image data we just set
        console.log(img.data);
            // the image data we just placed onto the canvas
        console.log(ctx.getImageData(0,0,canvas.width, canvas.height).data);
}
</code>```

In the console, you will find two console.log outputs. The first before the premultiplication, and the second after the premultiplication. These two outputs are different, some values being off by 3 or more. This only happens when there is partial transparency involved (the alpha being set to anything other than 255).

Is there a way to get the same output? Any ideas about this problem? Any ideas how to create something like a workaround for this problem?

Thank you in advance!

答:
Well this is still a bummer...

I supposed if you're using it in a texture for webgl you could just pass it as a uniform byte array

Body:
Is there a way to stop the premultiplication of the alpha channel for canvas data, or  a workaround?

I want to generate an image (in this case some random rgba values) and save the canvas as an image.

During the second step, I want to compare the original image with the generated image using the imageData, however this won't work due to the premultiplication of the alpha channel of my rgba pixels in the generated image.

The example

function drawImage(ctx) {
    var img = ctx.createImageData(canvas.width,canvas.height);

        for (var i=img.data.length;i-=4;) {
                img.data[i] = Math.floor(Math.random() * 255);
                img.data[i+1] = Math.floor(Math.random() * 255);
                img.data[i+2] = Math.floor(Math.random() * 255);
                img.data[i+3] = Math.floor(Math.random() * 255);
        }

        ctx.putImageData(img, 0, 0);
            // our image data we just set
        console.log(img.data);
            // the image data we just placed onto the canvas
        console.log(ctx.getImageData(0,0,canvas.width, canvas.height).data);
}

In the console, you will find two console.log outputs. The first before the premultiplication, and the second after the premultiplication. These two outputs are different, some values being off by 3 or more. This only happens when there is partial transparency involved (the alpha being set to anything other than 255).

Is there a way to get the same output? Any ideas about this problem? Any ideas how to create something like a workaround for this problem?

Thank you in advance!


问:
LinearLayout only show first item
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

here is the result when i change position of Button and ImageView

and

答:
you can try this using weight attribute in image and button

```<code><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:orientation="horizontal">

<android.support.v7.widget.AppCompatImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/qrCode_imageView"
    android:layout_weight="1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<android.support.v7.widget.AppCompatButton
    android:id="@+id/generate_code_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@string/generate_code"
    android:layout_marginRight="@dimen/de_btn_padding"
    android:layout_marginLeft="@dimen/de_btn_padding"/>
</code>```

Title: LinearLayout only show first item

Body:
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

here is the result when i change position of Button and ImageView

and

Body:
you can try this using weight attribute in image and button

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:orientation="horizontal">

<android.support.v7.widget.AppCompatImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/qrCode_imageView"
    android:layout_weight="1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<android.support.v7.widget.AppCompatButton
    android:id="@+id/generate_code_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@string/generate_code"
    android:layout_marginRight="@dimen/de_btn_padding"
    android:layout_marginLeft="@dimen/de_btn_padding"/>


问:
AJAX Contact form doesn't work correctly
I have a form:

```<code><form id="main-contact-form" name="contact-form" action="sendemail.php" method="post">
    <div class="form-group">
        <input type="text" name="name" class="form-control" required="required" placeholder="Name">
    </div>
    <div class="form-group">
        <input type="email" name="email" class="form-control" required="required" placeholder="Email">
    </div>
    <div class="form-group">
        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
    </div>
    <div class="form-group">
        <input type="submit" name="submit" class="btn btn-submit" value="Send">
    </div>
</form>
</code>```

sendememail.php is:

```<code><?php

$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);

$to = "email@email.com";
$sub = "New message from site";

$message = "New message\n
Name: $name
Email: $email";

$from  = "From: $name <$name> \r\n";

mail($to, $sub, $message, $from);
return;

?>
</code>```

javascript is:

```<code>var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Sending...</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p class="text-success">Thanks for you message!</p>').delay(3000).fadeOut();
    });
});
</code>```

The problem: it sends a message to email, but without input fields. Their value are empty. I tried to do that without JS, and it's sending every field correctly.

答:
Improved ajax request:</p>

```<code>var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Sending...</p>').fadeIn() );
        },
        // by default method is `GET`, set `POST` explicitly
        method: "POST",
        // provide data that you need in a `data` property
        // there can be many ways to collect your data
        // `serialize` is the simplest method for this case
        data: form.serialize()
    }).done(function(data){
        form_status.html('<p class="text-success">Thanks for you message!</p>').delay(3000).fadeOut();
    });
});
</code>```

Body:
I have a form:

<form id="main-contact-form" name="contact-form" action="sendemail.php" method="post">

        <input type="text" name="name" class="form-control" required="required" placeholder="Name">

        <input type="email" name="email" class="form-control" required="required" placeholder="Email">

        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>

        <input type="submit" name="submit" class="btn btn-submit" value="Send">

</form>

sendememail.php is:

<?php

$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);

$to = "email@email.com";
$sub = "New message from site";

$message = "New message\n
Name: $name
Email: $email";

$from  = "From: $name <$name> \r\n";

mail($to, $sub, $message, $from);
return;

?>

javascript is:

var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('

');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('
 Sending...
').fadeIn() );
        }
    }).done(function(data){
        form_status.html('
Thanks for you message!
').delay(3000).fadeOut();
    });
});

The problem: it sends a message to email, but without input fields. Their value are empty. I tried to do that without JS, and it's sending every field correctly.

Body:
Improved ajax request:

var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Sending...</p>').fadeIn() );
        },
        // by default method is `GET`, set `POST` explicitly
        method: "POST",
        // provide data that you need in a `data` property
        // there can be many ways to collect your data
        // `serialize` is the simplest method for this case
        data: form.serialize()
    }).done(function(data){
        form_status.html('<p class="text-success">Thanks for you message!</p>').delay(3000).fadeOut();
    });
});


问:
JQuery Version and Editing Tool Tips
I am using a tooltip edit script that includes the following:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="http://static.tumblr.com/iuw14ew/VSQma1786/jquery.style-my-tooltips.js"></script>

<script>
    (function($){
        $(document).ready(function(){
            $("a[title]").style_my_tooltips({
                tip_follows_cursor: true,
                tip_delay_time: 90,
                tip_fade_speed: 600,
                attribute: "title"
            });
        });
    })(jQuery);
</script>
</code>```

But, due to another script I am using, I need to use this version of jQuery:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</code>```

Trying to use the 2.1.4 breaks the tooltips style. Help? I am super super new to jQuery and Javascript.

答:
As @Ali said in his comment, you can use jQuery's noConflict function.

By default, jQuery uses $ as a shorthand function name. Using jQuery.noConflict() you can bind this to something else.

This means, as shown in the linked answer, you can do the following:

For version 1.7, you can do the following:

Now, instead of $(document).ready() you can use jQ(document).ready() to access jQuery 1.7 functions.

jQuery 2.1.4 will still be accessible through $.

Do note that jQuery 1.7 is 6 years old, and might be obsolete. Consider looking for a more up-to-date version of the Tooltip library you're using.

Bootstrap has the functionality you're looking for!

Title: JQuery Version and Editing Tool Tips

Body:
I am using a tooltip edit script that includes the following:

But, due to another script I am using, I need to use this version of jQuery:

Trying to use the 2.1.4 breaks the tooltips style. Help? I am super super new to jQuery and Javascript.

Body:
As @Ali said in his comment, you can use jQuery's noConflict function.

By default, jQuery uses $ as a shorthand function name. Using jQuery.noConflict() you can bind this to something else.

This means, as shown in the linked answer, you can do the following:

For version 1.7, you can do the following:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

<script type="text/javascript">
   var jQ = $.noConflict(true);
</script>

Now, instead of $(document).ready() you can use jQ(document).ready() to access jQuery 1.7 functions.

jQuery 2.1.4 will still be accessible through $.

Do note that jQuery 1.7 is 6 years old, and might be obsolete. Consider looking for a more up-to-date version of the Tooltip library you're using.

Bootstrap has the functionality you're looking for!


问:
Inserting a confirmation before deleting item from database using php and javascript
Adding a confirmation before deleting item from database. I have a search.php page where users can search throught the items which are listed in table, near each item there is a delete icon.  The delete icon calls a php function "deleteItem($id)" located in deleteItem.php.

Without any confirmation all is working fine. I call the function using the below:-

```<code><a href="deleteItem.php?id='.$id.'">Delete Icon</a>
</code>```

To add a confirmation before delete I am using a javascript function which is located in the head of the search.php and is show below:-

```<code><script type="text/javascript">
   function confirmDelete(id){
      if(confirm("Are you sure you want to delete this item?")){
          window.location = "deleteItem.php?id="+id;
   }else{
          // abort message ... //
      }
</script>
</code>```

I am using an onclick event to call the confirmDelete function as follows:-

```<code><a href="" onclick="confirmDelete('.$id.')">Delete Icon</a>
</code>```

Following some time trying to fix the issue it seems that the php page deleteItem.php?id="+id is never executed.  How can I call the deleteItem function located in the deleteItem.php file using window.location or any other method from the javascript function?

答:
You have to print php variable for getting in javascript :</p>

```<code><a href="" onclick="confirmDelete(<?php echo $id; ?>)">Delete Icon</a>
</code>```

Body:
Adding a confirmation before deleting item from database. I have a search.php page where users can search throught the items which are listed in table, near each item there is a delete icon.  The delete icon calls a php function "deleteItem($id)" located in deleteItem.php.

Without any confirmation all is working fine. I call the function using the below:-

Delete Icon

To add a confirmation before delete I am using a javascript function which is located in the head of the search.php and is show below:-

I am using an onclick event to call the confirmDelete function as follows:-

Delete Icon

Following some time trying to fix the issue it seems that the php page deleteItem.php?id="+id is never executed.  How can I call the deleteItem function located in the deleteItem.php file using window.location or any other method from the javascript function?

Body:
You have to print php variable for getting in javascript :

<a href="" onclick="confirmDelete(<?php echo $id; ?>)">Delete Icon</a>


问:
Angular2 - Set A Different Color to an element Depending On Value
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

```<code>.red {
    color: red;
}

.green {
    color: green;
}
</code>```

XXX.component.css

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>
</code>```

答:
You need to modify your logic to have double quotes and ngModel proportion value

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{red : proportion != '100', green: proportion === '100'}">{{username}}</span></p>
</code>```

Hope it helps!!

Body:
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

.red {
    color: red;
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">

hello {{proportion}}

Body:
You need to modify your logic to have double quotes and ngModel proportion value

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{red : proportion != '100', green: proportion === '100'}">{{username}}</span></p>

Hope it helps!!


问:
How to change the value of the drop-down on change event?
I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:

```<code>$("select#code").on("change", function () {
         getNameFunc($(this).val())
});

$("select#empName").on("change", function () {
         getCodeFunc($(this).val())
});

function getNameFunc(value) {
   $.ajax({
        url: '@Url.Action("getName", "Employees")',
        data: { id: value },
        cache: false,
        type: "GET",
        success: function (data) {
               $("#empName").val(data.Name);
        }
    });
}

function getCodeFunc(value) {
     $.ajax({
          url: '@Url.Action("getCode", "Employees")',
          data: { id: value },
          cache: false,
          type: "GET",
          success: function (data) {
               $("#code").val(data.Code);
          }
    });
}
</code>```

My drop-down list:

```<code>@Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
@Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })
</code>```

In alert function, I am getting expected value but the problem is displaying it in to drop-down list.

答:
Simple , Try it , Let me assume selects render as , this is dummy test , best approch you must save value = EmpID

Emp Name dropdown

```<code><select id="name">
<option value="EmpID1"> Name 1 </option>
<option value="EmpID2"> Name 2 </option>
</select>
</code>```

Emp Code dropdown

```<code><select id="code">
 <option value="EmpID1"> Code 1 </option>
 <option value="EmpID2"> Code 2 </option>
 </select>
</code>```

Inside your ajax , if you want change/load name front the of the dropdown then

Value set by value

```<code>  $('#name').val(data.EmpID1)

Similarly reverse

$('#code').val(data.EmpID1)
</code>```

Value set by text / name

```<code>$('#name option:selected').text(data.Name)
</code>```

Body:
I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:

$("select#code").on("change", function () {
         getNameFunc($(this).val())
});

$("select#empName").on("change", function () {
         getCodeFunc($(this).val())
});

function getNameFunc(value) {
   $.ajax({
        url: '@Url.Action("getName", "Employees")',
        data: { id: value },
        cache: false,
        type: "GET",
        success: function (data) {
               $("#empName").val(data.Name);
        }
    });
}

function getCodeFunc(value) {
     $.ajax({
          url: '@Url.Action("getCode", "Employees")',
          data: { id: value },
          cache: false,
          type: "GET",
          success: function (data) {
               $("#code").val(data.Code);
          }
    });
}

My drop-down list:

@Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
@Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })

In alert function, I am getting expected value but the problem is displaying it in to drop-down list.

Body:
Simple , Try it , Let me assume selects render as , this is dummy test , best approch you must save value = EmpID

Emp Name dropdown

<select id="name">
<option value="EmpID1"> Name 1 </option>
<option value="EmpID2"> Name 2 </option>
</select>

Emp Code dropdown

<select id="code">
 <option value="EmpID1"> Code 1 </option>
 <option value="EmpID2"> Code 2 </option>
 </select>

Inside your ajax , if you want change/load name front the of the dropdown then

Value set by value

  $('#name').val(data.EmpID1)

Similarly reverse

$('#code').val(data.EmpID1)

Value set by text / name

$('#name option:selected').text(data.Name)


问:
Type class pattern vs implicit class
I have a hard time understanding the difference in use cases between teh type class pattern and the implicit class in Scala. What makes it confusing for me is that they both provide ad hoc polimorphism in Scala.

My question is. Are they solving the same problem or is there a clear difference in use cases?

答:
There is a difference.

Implicit classes are usually used to provide extension methods to existing types:

```<code>implicit class IntExt(val x: Int) extends AnyVal {
  def squared: Int = x * x
}

10.squared shouldEqual 1000
</code>```

They do not actually provide an ad-hoc polymorphism; it's just an ability to define new methods on existing types.

Type classes, on the other hand, depend on another implicit mechanism (implicit parameters vs implicit conversions in case of implicit classes), and they are a mechanism of ad-hoc polymorphism:

```<code>trait Show[T] {
  def show(x: T): String
}

implicit val intHexShow: Show[Int] = new Show[Int] {
  override def show(x: Int): String = Integer.toHexString(x)
}

implicit val stringReverseShow: Show[String] = new Show[String] {
  override def show(x: String): String = x.reverse
}

def showPrint[T](value: T)(implicit s: Show[T]): Unit = {
  println(s.show(value))
}

showPrint(12)  // prints "c"
showPrint("hello")  // prints "olleh"
</code>```

Since the function with the respective implicit parameter accepts the "behavior" defined in a type class implementation for a particular type as a parameter, it is indeed a case of ad-hoc polymorphism. Type classes are used for lots of things in Scala: JSON encoding/decoding, functional structures like monads and applicatives, type-polymorphic functions, to name a few. Almost everywhere when you need to add new behavior to existing types in a generic way, you will encounter a type class.

Title: Type class pattern vs implicit class

Body:
There is a difference.

Implicit classes are usually used to provide extension methods to existing types:

implicit class IntExt(val x: Int) extends AnyVal {
  def squared: Int = x * x
}

10.squared shouldEqual 1000

They do not actually provide an ad-hoc polymorphism; it's just an ability to define new methods on existing types.

Type classes, on the other hand, depend on another implicit mechanism (implicit parameters vs implicit conversions in case of implicit classes), and they are a mechanism of ad-hoc polymorphism:

trait Show[T] {
  def show(x: T): String
}

implicit val intHexShow: Show[Int] = new Show[Int] {
  override def show(x: Int): String = Integer.toHexString(x)
}

implicit val stringReverseShow: Show[String] = new Show[String] {
  override def show(x: String): String = x.reverse
}

def showPrint[T](value: T)(implicit s: Show[T]): Unit = {
  println(s.show(value))
}

showPrint(12)  // prints "c"
showPrint("hello")  // prints "olleh"

Since the function with the respective implicit parameter accepts the "behavior" defined in a type class implementation for a particular type as a parameter, it is indeed a case of ad-hoc polymorphism. Type classes are used for lots of things in Scala: JSON encoding/decoding, functional structures like monads and applicatives, type-polymorphic functions, to name a few. Almost everywhere when you need to add new behavior to existing types in a generic way, you will encounter a type class.


问:
How to make an xml tree with tagged data in python
I am figuring out the way how I can convert my data in tags to XML file.
example:-

```<code><DEG>degree_name1</DEG> <STR>degree_stream</STR> <COLL>college studied </COLL> , <LOC>location of college</LOC> <LOC>Chennai</LOC> <YEAR>2014</YEAR> <PER>60</PER> <12TH>12th</12TH> <COLL>Higher Secondary School</COLL> , <LOC>Thirupur</LOC> State board Mar <YEAR>2011</YEAR> <PER>78.58</PER> <10TH>10th</10TH> <COLL>Chinna Samy Ammal Higher Sec</COLL>. School , <LOC>Thirupur</LOC> State board Mar <YEAR>2009</YEAR> <PER>85.6</PER>
</code>```

Is there any good pythons library from which I can format this in the nested format like below:-

```<code>degree1
   degree1 stream
   degree1 college
   degree1 location
   degree1 percentage
   degree1 year
degree2
   degree2 stream
   degree2 college
   degree2 location
   degree2 percentage
   degree2 year
</code>```

答: I recommend lxml. It is easy to use, results in readable code, and has a first-class tutorial: http://lxml.de/tutorial.html .

Body:
I am figuring out the way how I can convert my data in tags to XML file.
example:-

<DEG>degree_name1</DEG> <STR>degree_stream</STR> <COLL>college studied </COLL> , <LOC>location of college</LOC> <LOC>Chennai</LOC> <YEAR>2014</YEAR> <PER>60</PER> <12TH>12th</12TH> <COLL>Higher Secondary School</COLL> , <LOC>Thirupur</LOC> State board Mar <YEAR>2011</YEAR> <PER>78.58</PER> <10TH>10th</10TH> <COLL>Chinna Samy Ammal Higher Sec</COLL>. School , <LOC>Thirupur</LOC> State board Mar <YEAR>2009</YEAR> <PER>85.6</PER>

Is there any good pythons library from which I can format this in the nested format like below:-

degree1
   degree1 stream
   degree1 college
   degree1 location
   degree1 percentage
   degree1 year
degree2
   degree2 stream
   degree2 college
   degree2 location
   degree2 percentage
   degree2 year


问:
Reading a AppKey value from web.config in clientside js SPA
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.

Code for clarity:

```<code>define([], function () {
    var serviceBaseUrl = 'http://localhost/Service/api/';
    var portalPortalUrl = 'http://localhost/Portal';
});
</code>```

And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.

What I want:

To store them in Web.config file so I can have different configuration for debug and release modes.

I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.

I have only found solutions using ASP.NET ConfigurationManager like so:

```<code> function ReadConfigurationSettings()
 {
     var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
     alert(k);
 }
</code>```

Or, for Razor:

```<code>@System.Configuration.ConfigurationManager.AppSettings["myKey"]
</code>```

It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.

If needed, here is my project structure:

```<code>- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
</code>```

答:
Adding to satpal, for SPA application such as angular js

For SPA's, such as angular you can use below code in your index.html as

```<code> <script type="text/javascript" src='/Controller/config'></script>
</code>```

Body:
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.

Code for clarity:

define([], function () {
    var serviceBaseUrl = 'http://localhost/Service/api/';
    var portalPortalUrl = 'http://localhost/Portal';
});

And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.

What I want:

To store them in Web.config file so I can have different configuration for debug and release modes.

I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.

I have only found solutions using ASP.NET ConfigurationManager like so:

 function ReadConfigurationSettings()
 {
     var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
     alert(k);
 }

Or, for Razor:

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.

If needed, here is my project structure:

- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config

Body:
Adding to satpal, for SPA application such as angular js

For SPA's, such as angular you can use below code in your index.html as

 <script type="text/javascript" src='/Controller/config'></script>


问:
Change the layout view on the click of the Item
The app has been designed with the help of RecyclerView in which the Linear Layout which contain the progress bar.

I want to change the view when item is been clicked, and when item has been clicked then that item which is been clicked should look big in same position as compared to another item. On click, suppose I get number 20 then progress bar color should change up to 20% different color and remaining should be in different color.

Main.xml

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="1dp"
        android:layout_marginTop="16dp"
        android:scrollbars="vertical" />
</code>```

list.xml

```<code><LinearLayout
    android:id="@+id/llDevice"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:orientation="vertical"
    android:gravity="center_horizontal|center_vertical"
    android:visibility="visible">

    <ProgressBar
        android:id="@+id/pbBatteryStatus"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="10dp"
        android:layout_gravity="center"
        android:indeterminateOnly="false"
        android:max="100"
        android:progressDrawable="@drawable/border_progressbar"/>

</LinearLayout>
</code>```

border_progressbar.xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dp" />
        <gradient
            android:centerColor="@color/ripple_grey"
            android:endColor="@color/ripple_grey"
            android:startColor="@color/ripple_grey" />
    </shape>
</item>

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners android:radius="5dp" />
            <gradient
                android:endColor="@color/ripple_errorMsg"
                android:startColor="@color/ripple_color" />
        </shape>
    </clip>
</item>

</layer-list>
</code>```

How can I resolve this issue?

答:
You have to define a flag in your model

```<code>boolean clicked = false;
</code>```

then when an item clicked in your list you should change it's clicked status

```<code>model.clicked = !model.clicked;
</code>```

then in onBindViewHolder with a simple if and else you can change the view of items with true clicked status

```<code>    @Override
public void onBindViewHolder(ViewHolder holder, int position) {
      Model model = models.get(position);
      if(model.clicked){}
      else{}
}
</code>```

Body:
The app has been designed with the help of RecyclerView in which the Linear Layout which contain the progress bar.

I want to change the view when item is been clicked, and when item has been clicked then that item which is been clicked should look big in same position as compared to another item. On click, suppose I get number 20 then progress bar color should change up to 20% different color and remaining should be in different color.

Main.xml

<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="1dp"
        android:layout_marginTop="16dp"
        android:scrollbars="vertical" />

list.xml

<LinearLayout
    android:id="@+id/llDevice"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:orientation="vertical"
    android:gravity="center_horizontal|center_vertical"
    android:visibility="visible">

    <ProgressBar
        android:id="@+id/pbBatteryStatus"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="10dp"
        android:layout_gravity="center"
        android:indeterminateOnly="false"
        android:max="100"
        android:progressDrawable="@drawable/border_progressbar"/>

</LinearLayout>

border_progressbar.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dp" />
        <gradient
            android:centerColor="@color/ripple_grey"
            android:endColor="@color/ripple_grey"
            android:startColor="@color/ripple_grey" />
    </shape>
</item>

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners android:radius="5dp" />
            <gradient
                android:endColor="@color/ripple_errorMsg"
                android:startColor="@color/ripple_color" />
        </shape>
    </clip>
</item>

</layer-list>

How can I resolve this issue?

Body:
You have to define a flag in your model

boolean clicked = false;

then when an item clicked in your list you should change it's clicked status

model.clicked = !model.clicked;

then in onBindViewHolder with a simple if and else you can change the view of items with true clicked status

    @Override
public void onBindViewHolder(ViewHolder holder, int position) {
      Model model = models.get(position);
      if(model.clicked){}
      else{}
}


问:
How to change URL from this ?name=title to ../title
I have a script, which automatically add a URL for every row I insert into database with php.

This is, how it works:

```<code>if (isset($_GET['name']) )
  $title = $_GET['name'];

 <Code to select and echo data from database here>
</code>```

So, if I insert a row named "UserA", then a URL will be created like this:

```<code>example.com/users/?name=UserA
</code>```

I want to remove "?name="and make the URL like: example.com/users/UserA

答:
Try adding this to your .htaccess

RewriteEngine On
RewriteRule /users/(.*)$ /users/name=$1

If you manage the server yourself, be sure to enable mod_rewrite.

Body:
I have a script, which automatically add a URL for every row I insert into database with php.

This is, how it works:

if (isset($_GET['name']) )
  $title = $_GET['name'];

So, if I insert a row named "UserA", then a URL will be created like this:

example.com/users/?name=UserA

I want to remove "?name="and make the URL like: example.com/users/UserA