问:
NodeJS - SQL Server connection closed
I'm trying to call a register stored procedure from SQL Server. I'm using NodeJS with the mssql package. I got most of the code from the mssql Npm documentation. But it still doesn't work.

The code basically tries to initiate a ConnectionPool as a read the last update renamed connection to ConnectionPool, create a new request, introduce the parameters and the execute the stored procedure. I have it this way because I need to change the connection variable to another database every once in a while.

The error I get is:

ConnectionError: Connection is closed.

My code:

```<code>const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario, callback) {

  var connection = new sql.ConnectionPool(config);
  var request = new sql.Request(connection);
  request.input('input_parameter', sql.VARCHAR(25), pUserName);
  request.input('input_parameter', sql.VARCHAR(16), pPassword);
  request.input('input_parameter', sql.VARCHAR(25), pNombre);
  request.input('input_parameter', sql.VARCHAR(50), pApellidos);
  request.input('input_parameter', sql.Int, pFK_TipoUsuario);

  request.execute('RegistrarUsuario', (err, result)=>{
    if(err){
      console.log(err);
    }
    else{
      console.log(result);
    }
  });
};
</code>```

答:
There is this async version of implementation. Check if this serves your purpose</p>

```<code>const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = async function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario) {

    try {

        let connection = await sql.connect(config)

        let result = await connection.request()
            .input('input_parameter', sql.VARCHAR(25), pUserName);
            .input('input_parameter', sql.VARCHAR(16), pPassword);
            .input('input_parameter', sql.VARCHAR(25), pNombre);
            .input('input_parameter', sql.VARCHAR(50), pApellidos);
            .input('input_parameter', sql.Int, pFK_TipoUsuario);
            .execute('RegistrarUsuario');

        return result;
    } catch (err) {
        console.log(err); // ... error checks
    }

};

sql.on('error', err => {
    // ... error handler
})
</code>```

Title: NodeJS - SQL Server connection closed

Body:
I'm trying to call a register stored procedure from SQL Server. I'm using NodeJS with the mssql package. I got most of the code from the mssql Npm documentation. But it still doesn't work.

The code basically tries to initiate a ConnectionPool as a read the last update renamed connection to ConnectionPool, create a new request, introduce the parameters and the execute the stored procedure. I have it this way because I need to change the connection variable to another database every once in a while.

The error I get is:

ConnectionError: Connection is closed.

My code:

const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario, callback) {

  var connection = new sql.ConnectionPool(config);
  var request = new sql.Request(connection);
  request.input('input_parameter', sql.VARCHAR(25), pUserName);
  request.input('input_parameter', sql.VARCHAR(16), pPassword);
  request.input('input_parameter', sql.VARCHAR(25), pNombre);
  request.input('input_parameter', sql.VARCHAR(50), pApellidos);
  request.input('input_parameter', sql.Int, pFK_TipoUsuario);

  request.execute('RegistrarUsuario', (err, result)=>{
    if(err){
      console.log(err);
    }
    else{
      console.log(result);
    }
  });
};

Body:
There is this async version of implementation. Check if this serves your purpose

const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = async function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario) {

    try {

        let connection = await sql.connect(config)

        let result = await connection.request()
            .input('input_parameter', sql.VARCHAR(25), pUserName);
            .input('input_parameter', sql.VARCHAR(16), pPassword);
            .input('input_parameter', sql.VARCHAR(25), pNombre);
            .input('input_parameter', sql.VARCHAR(50), pApellidos);
            .input('input_parameter', sql.Int, pFK_TipoUsuario);
            .execute('RegistrarUsuario');

        return result;
    } catch (err) {
        console.log(err); // ... error checks
    }

};

sql.on('error', err => {
    // ... error handler
})


来源: stackexchange

问:
Google Actions Home control sync response not accepted
For the following Google Assistant Home automation sync request, my backend responses for certain accounts works. But some accounts it fails and I have no clue whatsoever.

```<code>{
    "requestId": "XXXXXXXXXXXX",
    "inputs": [{
        "intent": "action.devices.SYNC"
    }]
 }
</code>```

How do I debug why a SYNC request has failed? Is there a console or log where I can see what went wrong.

Everything looks just fine. Similar response for some other accounts of my user base works, where as for this user's response it always doesn't work.

Not working Response:

In this instance, its failing for the following SYNC response.

[{
  "payload": {
    "devices": [{
      "id": "7e-f2-ca-ab-40-34-34-95:1:1",
      "name": {
        "name": "Air Conditioner"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:2:1",
      "name": {
        "name": "Office Hooter"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:5:1",
      "name": {
        "name": "Office Motion"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:2",
      "name": {
        "name": "DOOR SENSOR"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:1",
      "name": {
        "name": "Blue Lamp"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:2",
      "name": {
        "name": "Green Lamp"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:3",
      "name": {
        "name": "Side Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:1",
      "name": {
        "name": "Front Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:2",
      "name": {
        "name": "Outdoor Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:3",
      "name": {
        "name": "Front Dimmer"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:1",
      "name": {
        "name": "Extra Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:2",
      "name": {
        "name": "Central Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:3",
      "name": {
        "name": "Fan"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:1",
      "name": {
        "name": "Key Ring"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:2",
      "name": {
        "name": "Office Door"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:1",
      "name": {
        "name": "Blue LED"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:2",
      "name": {
        "name": "Work Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:3",
      "name": {
        "name": "Dimmer Back"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:2",
      "name": {
        "name": "Door Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:3:1",
      "name": {
        "name": "Plug"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:1",
      "name": {
        "name": "Curtain Up"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:2",
      "name": {
        "name": "Curtain Down"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:3",
      "name": {
        "name": "Regulator"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "27465191118001134545448968013",
      "name": {
        "name": "Darkness"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27465189752942073090942148334",
      "name": {
        "name": "Everything"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27507709627159036391184182205",
      "name": {
        "name": "Mood Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27514704337364024105847592198",
      "name": {
        "name": "White Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27576295525515559712639822299",
      "name": {
        "name": "Office Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }]
  },
  "requestId": "4881304563722779302"
}]

Whereas for the following SYNC response, it works.

[{
  "payload": {
    "devices": [{
      "id": "21-0b-c9-87-db-70-b6-83:1:1",
      "name": {
        "name": "Serial Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:2:1",
      "name": {
        "name": "Water Heater"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:10:1",
      "name": {
        "name": "Panic Alarm"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:11:1",
      "name": {
        "name": "Hall Motion Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:2",
      "name": {
        "name": "Primary Door"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:4",
      "name": {},
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:1",
      "name": {
        "name": "Car Keys"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:2",
      "name": {
        "name": "Door Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:1",
      "name": {
        "name": "Dummy"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:2",
      "name": {
        "name": "All Out"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:3",
      "name": {
        "name": "Bed Room Fan"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:1",
      "name": {
        "name": "Hall Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:2",
      "name": {
        "name": "Night Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:3",
      "name": {
        "name": "Fan"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:1",
      "name": {
        "name": "Exhaust"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:2",
      "name": {
        "name": "kitchen Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:3",
      "name": {
        "name": "Balcony Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "name": {
        "name": "Good Night"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }]
  },
  "requestId": "13733611394224717847"
}]

答: Google has released a smart home sync response validator tool. Use this tool to validate the sync response that is sent to the Google Assistant.</p>

ContentLicense: CC BY-SA 3.0

Body:
For the following Google Assistant Home automation sync request, my backend responses for certain accounts works. But some accounts it fails and I have no clue whatsoever.

{
    "requestId": "XXXXXXXXXXXX",
    "inputs": [{
        "intent": "action.devices.SYNC"
    }]
 }

How do I debug why a SYNC request has failed? Is there a console or log where I can see what went wrong.

Everything looks just fine. Similar response for some other accounts of my user base works, where as for this user's response it always doesn't work.

Not working Response:

In this instance, its failing for the following SYNC response.

[{
  "payload": {
    "devices": [{
      "id": "7e-f2-ca-ab-40-34-34-95:1:1",
      "name": {
        "name": "Air Conditioner"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:2:1",
      "name": {
        "name": "Office Hooter"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:5:1",
      "name": {
        "name": "Office Motion"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:2",
      "name": {
        "name": "DOOR SENSOR"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:11:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:1",
      "name": {
        "name": "Blue Lamp"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:2",
      "name": {
        "name": "Green Lamp"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:14:3",
      "name": {
        "name": "Side Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:1",
      "name": {
        "name": "Front Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:2",
      "name": {
        "name": "Outdoor Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:15:3",
      "name": {
        "name": "Front Dimmer"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:1",
      "name": {
        "name": "Extra Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:2",
      "name": {
        "name": "Central Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:17:3",
      "name": {
        "name": "Fan"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:1",
      "name": {
        "name": "Key Ring"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:2",
      "name": {
        "name": "Office Door"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:19:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:1",
      "name": {
        "name": "Blue LED"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:2",
      "name": {
        "name": "Work Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:6:3",
      "name": {
        "name": "Dimmer Back"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:2",
      "name": {
        "name": "Door Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:4:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:3:1",
      "name": {
        "name": "Plug"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:1",
      "name": {
        "name": "Curtain Up"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:2",
      "name": {
        "name": "Curtain Down"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "7e-f2-ca-ab-40-34-34-95:7:3",
      "name": {
        "name": "Regulator"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "27465191118001134545448968013",
      "name": {
        "name": "Darkness"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27465189752942073090942148334",
      "name": {
        "name": "Everything"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27507709627159036391184182205",
      "name": {
        "name": "Mood Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27514704337364024105847592198",
      "name": {
        "name": "White Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }, {
      "id": "27576295525515559712639822299",
      "name": {
        "name": "Office Lights"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }]
  },
  "requestId": "4881304563722779302"
}]

Whereas for the following SYNC response, it works.

[{
  "payload": {
    "devices": [{
      "id": "21-0b-c9-87-db-70-b6-83:1:1",
      "name": {
        "name": "Serial Lights"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:2:1",
      "name": {
        "name": "Water Heater"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.OUTLET",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:10:1",
      "name": {
        "name": "Panic Alarm"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:11:1",
      "name": {
        "name": "Hall Motion Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:1",
      "name": {
        "name": "Buzzer"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:2",
      "name": {
        "name": "Primary Door"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:16:4",
      "name": {},
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:1",
      "name": {
        "name": "Car Keys"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:2",
      "name": {
        "name": "Door Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:6:4",
      "name": {
        "name": "Presence Sensor"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:1",
      "name": {
        "name": "Dummy"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:2",
      "name": {
        "name": "All Out"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:3:3",
      "name": {
        "name": "Bed Room Fan"
      },
      "traits": ["action.devices.traits.OnOff", "action.devices.traits.Brightness"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:1",
      "name": {
        "name": "Hall Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:2",
      "name": {
        "name": "Night Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:5:3",
      "name": {
        "name": "Fan"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:1",
      "name": {
        "name": "Exhaust"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:2",
      "name": {
        "name": "kitchen Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "id": "21-0b-c9-87-db-70-b6-83:8:3",
      "name": {
        "name": "Balcony Light"
      },
      "traits": ["action.devices.traits.OnOff"],
      "type": "action.devices.types.SWITCH",
      "willReportState": false
    }, {
      "name": {
        "name": "Good Night"
      },
      "traits": ["action.devices.traits.Scene"],
      "type": "action.devices.types.SCENE",
      "willReportState": false
    }]
  },
  "requestId": "13733611394224717847"
}]


问:
UIDatePicker not showing up in UITextField. Swift 3
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

答:
add below line in your viewDidload,

```<code>   pickerView5.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
</code>```

and replace your datePickerValueChanged with below,

```<code> func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"   // or whatever date format you want
    whenTextField.text = dateFormatter.string(from: sender.date)
}
</code>```

That's it!

Body:
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}

Body:
add below line in your viewDidload,

   pickerView5.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)

and replace your datePickerValueChanged with below,

 func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"   // or whatever date format you want
    whenTextField.text = dateFormatter.string(from: sender.date)
}

That's it!


问:
select from two mysql tables where column value is similar and id is retrieved from previous page
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

```<code>$a=$_POST['home_id']
</code>```

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

```<code>    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a <br/> ";
         echo " $bc2 <br/>";
        ?>
</code>```

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

```<code>  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";
</code>```

答:
You need inner join to use:</p>

```<code>   " SELECT t_office.home_id,t_office.case_no,t_office.name FROM tbl_office
    t_office INNER JOIN tbl_home t_home ON t_office.case_no = t_home.case_no;
    where t_office.case_no ='$a'";
</code>```

Body:
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

$a=$_POST['home_id']

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a
 ";
         echo " $bc2
";
        ?>

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";

Body:
You need inner join to use:

   " SELECT t_office.home_id,t_office.case_no,t_office.name FROM tbl_office
    t_office INNER JOIN tbl_home t_home ON t_office.case_no = t_home.case_no;
    where t_office.case_no ='$a'";


问:
Is there a way to figure out what is using a Linux kernel module?
If I load a kernel module and list the loaded modules with lsmod, I can get the "use count" of the module (number of other modules with a reference to the module). Is there a way to figure out what is using a module, though?

The issue is that a module I am developing insists its use count is 1 and thus I cannot use rmmod to unload it, but its "by" column is empty. This means that every time I want to re-compile and re-load the module, I have to reboot the machine (or, at least, I can't figure out any other way to unload it).

答: You might try lsof or fuser.

OwnerDisplayName: mipadi

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mipadi

Body: You might try lsof or fuser.

OwnerDisplayName: jedihawk

LastEditorDisplayName: jedihawk


问:
Add a class to parent and ancestors if the item have active class
Say that if I have code that looks something like below, and like to add show class to parent and ancestors.

```<code>// The last `nav-item` have `active` classs
<div class="nested-group nested-item show">
  <div class="nested-item show">
    <div class="nested-item show">
      <div class="nested-item show">
        <a class="nav-item active" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>

// The last `nav-item` doesn't have `active` class
<div class="nested-group nested-item">
  <div class="nested-item">
    <div class="nested-item">
      <div class="nested-item">
        <a class="nav-item" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>
</code>```

答:
You can use .parents() method to target all the parent/ancestors with nested-item class.

$('.active.nav-item').parents('.nested-item').addClass('show');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nested-group nested-item ">
  <div class="nested-item ">
    <div class="nested-item ">
      <div class="nested-item ">
        Lorem
        Ipsum
      </div>
    </div>
  </div>
</div></code>```

Body:
Say that if I have code that looks something like below, and like to add show class to parent and ancestors.

// The last `nav-item` have `active` classs

        Lorem
        Ipsum

// The last `nav-item` doesn't have `active` class

        Lorem
        Ipsum

Body:
You can use .parents() method to target all the parent/ancestors with nested-item class.

$('.active.nav-item').parents('.nested-item').addClass('show');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nested-group nested-item ">
  <div class="nested-item ">
    <div class="nested-item ">
      <div class="nested-item ">
        <a class="nav-item active" href="#">Lorem</a>
        <a class="nav-item" href="#">Ipsum</a>
      </div>
    </div>
  </div>
</div>


问:
Swift iOS: Set Gradient Background To A UITextView?
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

```<code>extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}
</code>```

Here where I assign gradient to the text view:

```<code>        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt
</code>```

Here are the colors in the Constants class:

```<code>    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}
</code>```

I always get white background when using the gradient method. Appreciate any suggestions.

答:
i think you forget location

```<code>extension UIView
{
   func setGradient(startColor:UIColor,endColor:UIColor)
    {
        let gradient:CAGradientLayer = CAGradientLayer()
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
     }
}
</code>```

use

```<code>txtView.setGradient(startColor: UIColor.blue, endColor: UIColor.green)
</code>```

Output:

Body:
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

Here where I assign gradient to the text view:

        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt

Here are the colors in the Constants class:

    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}

I always get white background when using the gradient method. Appreciate any suggestions.

Body:
i think you forget location

extension UIView
{
   func setGradient(startColor:UIColor,endColor:UIColor)
    {
        let gradient:CAGradientLayer = CAGradientLayer()
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
     }
}

use

txtView.setGradient(startColor: UIColor.blue, endColor: UIColor.green)

Output:


问:
Message: 'chromedriver' executable needs to be in PATH
So, I am using OS X  El Capitan with  Eclipse (Neo) and Python.  I am wrote some Python with Selenium scripts.

These scripts were working fine.

Then I upgraded from OSX Sierra to El Capitan

Note: this is about the only major change
  that I did to my setup.

When I tried to run the same scripts, now, I get the

Message: chromedriver executable needs to be in PATH

As far I can tell chromedriver IS on my PATH.

Now, I can only make my scripts work if I hard copy the path to my chrome driver, which is not the most elegant way to do things, as we all know.

Has anyone else has/had this issue?  Thoughts on any configuration with my Eclipse + Python.

My Eclipse and Python project screen shot

my PYTHONPATH screen shot

答:
I dont know about python. But the implementation for the webdriver should be same irrespective of the language. Here you have called the chrome webdriver, but have you defined the path for chromedriver.exe in you code? For example, in java it looks like this

```<code>System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-3.4.0/chromedriver.exe");
driver = new ChromeDriver();
</code>```

The error you are getting is referring to the chromedriver.exe not the python environment.

Python Solution from Google documentation:

```<code>import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
</code>```

Body:
I dont know about python. But the implementation for the webdriver should be same irrespective of the language. Here you have called the chrome webdriver, but have you defined the path for chromedriver.exe in you code? For example, in java it looks like this

System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-3.4.0/chromedriver.exe");
driver = new ChromeDriver();

The error you are getting is referring to the chromedriver.exe not the python environment.

Python Solution from Google documentation:

import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()


问:
how to add jquery datetime picker with laravel project?

$(function() {
  $('.datetimepicker1').datetimepicker({
    language: 'pt-BR'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well">
  <div id="datetimepicker1" class="input-append date">
    <input data-format="dd/MM/yyyy hh:mm:ss" type="text">
    </input>
    <span class="add-on">
              <i data-time-icon="icon-time" data-date-icon="icon-
              calendar">
              </i>
              </span>
  </div>
</div></code>```

This is my blade view.But onclicking the inputfiled it displays nothing.Even the icons were not displayed.

答:
As the documetation of the jquery datetime picker mention over here https://jqueryui.com/datepicker/

You need to add the jquery-ui.js along with the jquery-ui.css. So your correct working code would be like this as showing in this fiddle

$(function() {
  $('#datetimepicker1').datepicker({
    language: 'pt-BR'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="well">
  <div  class="input-append date" id="datetimepicker1">
    <input data-format="dd/MM/yyyy hh:mm:ss"  type="text" />
    <span class="add-on">
              <i data-time-icon="icon-time" data-date-icon="icon-
              calendar">
              </i>
              </span>
  </div>
</div></code>```

Body:
$(function() {
  $('.datetimepicker1').datetimepicker({
    language: 'pt-BR'
  });
});

    <input data-format="dd/MM/yyyy hh:mm:ss" type="text">
    </input>

This is my blade view.But onclicking the inputfiled it displays nothing.Even the icons were not displayed.

Body:
As the documetation of the jquery datetime picker mention over here https://jqueryui.com/datepicker/

You need to add the jquery-ui.js along with the jquery-ui.css. So your correct working code would be like this as showing in this fiddle

$(function() {
  $('#datetimepicker1').datepicker({
    language: 'pt-BR'
  });
});

<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="well">
  <div  class="input-append date" id="datetimepicker1">
    <input data-format="dd/MM/yyyy hh:mm:ss"  type="text" />
    <span class="add-on">
              <i data-time-icon="icon-time" data-date-icon="icon-
              calendar">
              </i>
              </span>
  </div>
</div>


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
What would catch the exception and handle it? Let's assume that the run method could throw a checked exception. Then you could write code like this:

```<code>Thread myThread = new Thread(aRunnable);
try{
    myThread.start();
}
catch(Exception e){
   e.printStackTrace();
}
//do other stuff
</code>```

BUT once you call myThread.start, the new thread is started in the background and the current thread continues and exits the try-catch and does other stuff. So if myThread did throw an exception later on, you can't catch it!

What you need to do is deal with the exception within the run method and then probably have a way of notifying another object that this thread failed.

Body:
What would catch the exception and handle it? Let's assume that the run method could throw a checked exception. Then you could write code like this:

Thread myThread = new Thread(aRunnable);
try{
    myThread.start();
}
catch(Exception e){
   e.printStackTrace();
}
//do other stuff

BUT once you call myThread.start, the new thread is started in the background and the current thread continues and exits the try-catch and does other stuff. So if myThread did throw an exception later on, you can't catch it!

What you need to do is deal with the exception within the run method and then probably have a way of notifying another object that this thread failed.


问:
Create a table in mysql
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.</p>

```<code> CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));
</code>```

答:
```<code>CREATE TABLE `movie` (
  `title` VARCHAR(100),
  `year` INT(11),
  `length` INT(11),
  `inColor` BIT(1),
  `studioName` VARCHAR(50),
  `producerC#` INT(11),
  PRIMARY KEY (`title`)
)
</code>```

Title: Create a table in mysql

Body:
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.

 CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));


问:
How to remove a part of all strings in an array in javascript?
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.

答:
From your question, it's not clear if the array is a string array

If it is a string array you can do:

ES6+: gUser.map((user)=>{return user.split("CAR.")[1]})

ES5: gUser.map(function(user){return user.split("CAR.")[1]});


答:
You can use map to access each string in array then use replace. Use a regex to match string before '.' and replace only the first match, like this:

  var gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001'];

  var gUserModified = gUser.map(function(v){
        return v.replace(/[^\.]+\./, '');
  });
  console.log(gUserModified);```

Title: How to remove a part of all strings in an array in javascript?

Body:
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.


问:
post array inside json object in retrofit?
I m working with retrofit  and sending to request to server via post method i am getting response currectly  for this json see this is post i m sending to server .

adreess class for post i m using this object

```<code>{
     "years":"1855",
     "months":"6",
     "skills":1
}
</code>```

now  i have to implement array inside object in skills how to post this

```<code>{
    "years":"1",
    "months":"6",
    "skills":["1","2","3"],
}
</code>```

how to get array inside object in retrofit
i m using interface like this

```<code>Call<AddressResponce> address(@Body Adreess adreess);
</code>```

答:
Roughly it would look like this:

RequestBody class should have an array to hold that Skills list

```<code>class RequestBody {
   int years;
   int months;
   int[] skills;
}

@POST(“url”)
Call<AddressResponce> address(@Body RequestBody requestbody);
</code>```

See if it works.

ContentLicense: CC BY-SA 4.0

Body:
I m working with retrofit  and sending to request to server via post method i am getting response currectly  for this json see this is post i m sending to server .

adreess class for post i m using this object

{
     "years":"1855",
     "months":"6",
     "skills":1
}

now  i have to implement array inside object in skills how to post this

{
    "years":"1",
    "months":"6",
    "skills":["1","2","3"],
}

how to get array inside object in retrofit
i m using interface like this

Call<AddressResponce> address(@Body Adreess adreess);

Body:
Roughly it would look like this:

RequestBody class should have an array to hold that Skills list

class RequestBody {
   int years;
   int months;
   int[] skills;
}

@POST(“url”)
Call<AddressResponce> address(@Body RequestBody requestbody);

See if it works.


问:
Getting values querying from same table with LINQ
I have a table like this:

```<code>+----+--------+----------+---------+-------------+
| ID | Codigo |  Nombre  | PadreID | CatalogosID |
+----+--------+----------+---------+-------------+
|  2 | KNW    | KENWORTH |       0 | MAR         |
|  3 | VLV    | VOLVO    |       0 | MAR         |
|  4 | T60    | T600     |       2 | MOD         |
|  5 | T68    | T680     |       2 | MOD         |
|  6 | T88    | T880     |       2 | MOD         |
|  7 | M43    | VNM 430  |       3 | MOD         |
+----+--------+----------+---------+-------------+
</code>```

First I want to get a list of parameter I received so in LINQ I do something like:

```<code>var cr = _pService.Listar().Where(x => x.CatalogosID == Catalogo)
</code>```

Supposing Catalogo = MOD so it get values with ID is 4,5,6,7

Once I get them I want to get values where PadreID = ID so I should receive as finall result only values with ID 2 and 3

How can I do this Query with LINQ? Can someone help me there? I think it´s a self join, but joins with LINQ are very confusing

答:
How do you want to get rows with ID = 2 and ID = 3 if their CatalogosID isn't "MOD". Also, there aren't any rows where PadreID = ID. Please review your post and question.

EDIT

var idsWithMod = _p.service.Where(p => p.CatalogosID = Catalogo).Select(p => p.PadreID).ToList();

var result = _pservice.Where(p => idsWithMod.IndexOf(p.ID) != -1).ToList();
I wrote it in two queries to be more clear. If you want, you can combine them.

Body:
I have a table like this:

+----+--------+----------+---------+-------------+
| ID | Codigo |  Nombre  | PadreID | CatalogosID |
+----+--------+----------+---------+-------------+
|  2 | KNW    | KENWORTH |       0 | MAR         |
|  3 | VLV    | VOLVO    |       0 | MAR         |
|  4 | T60    | T600     |       2 | MOD         |
|  5 | T68    | T680     |       2 | MOD         |
|  6 | T88    | T880     |       2 | MOD         |
|  7 | M43    | VNM 430  |       3 | MOD         |
+----+--------+----------+---------+-------------+

First I want to get a list of parameter I received so in LINQ I do something like:

var cr = _pService.Listar().Where(x => x.CatalogosID == Catalogo)

Supposing Catalogo = MOD so it get values with ID is 4,5,6,7

Once I get them I want to get values where PadreID = ID so I should receive as finall result only values with ID 2 and 3

How can I do this Query with LINQ? Can someone help me there? I think it´s a self join, but joins with LINQ are very confusing


问:
Can't change attribute of input tag using Javascript
I have an <input> tag which I would like to change programmatically. The input don't have inner text, it save its values on aria attributes.

So, here is the <input>:

```<code><input type="text" id="foo" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="1">
</code>```

Consider that we save the tag to the following bla variable:

```<code>var bla = document.getElementById("foo");
</code>```

Below is a list of commands I tried using. But none of them worked.

bla.value = 2;

bla.value = "2";

bla.setAttribute("aria-valuenow",2);

bla.setAttribute("aria-valuenow","2");

Any ideas why? The id of the element is unique, I checked it.
I am working on somebody's else code. Could it be possible that other developers changed the behavior of the <input>?

答:
As pointed out my other users, please use unique Id while naming the id of an element. Below is the solution to your problem using setAttribue().

var input = document.getElementById("input");
input.setAttribute("aria-valuenow",2); // To set attribute to input element
console.log(input.hasAttribute('aria-valuenow')) // To check if input has the mentioned attribute
console.log(input.getAttribute('aria-valuenow')); // To access the value of the attribute```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="2"></code>```

Body:
I have an <input> tag which I would like to change programmatically. The input don't have inner text, it save its values on aria attributes.

So, here is the <input>:

<input type="text" id="foo" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="1">

Consider that we save the tag to the following bla variable:

var bla = document.getElementById("foo");

Below is a list of commands I tried using. But none of them worked.

bla.value = 2;

bla.value = "2";

bla.setAttribute("aria-valuenow",2);

bla.setAttribute("aria-valuenow","2");

Any ideas why? The id of the element is unique, I checked it.
I am working on somebody's else code. Could it be possible that other developers changed the behavior of the <input>?

Body:
As pointed out my other users, please use unique Id while naming the id of an element. Below is the solution to your problem using setAttribue().

var input = document.getElementById("input");
input.setAttribute("aria-valuenow",2); // To set attribute to input element
console.log(input.hasAttribute('aria-valuenow')) // To check if input has the mentioned attribute
console.log(input.getAttribute('aria-valuenow')); // To access the value of the attribute

<input type="text" id="input" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="2">


问:
Count the records with the same difference of two date columns Rails
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

```<code>start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07
</code>```

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

答:
Try code:</p>

```<code>diff = []

Model.select{|d| diff << (u.end_date - u.start_date).to_i }

max = diff.uniq.max_by{ |i| diff.count(i) }

result = Model.where("end_date - start_date = ?", max.to_s)

puts result
</code>```

Body:
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

Body:
Try code:

diff = []

Model.select{|d| diff << (u.end_date - u.start_date).to_i }

max = diff.uniq.max_by{ |i| diff.count(i) }

result = Model.where("end_date - start_date = ?", max.to_s)

puts result


问:
Get database connection from a connection pool
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

```<code>public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}
</code>```

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.

答:
The method I have used in the past is to create a singleton class that holds the datasource

E.g.

```<code>public class DatabaseConnectionManager {

    DataSource ds;

    public void init() {
        InitialContext initialContext = new InitialContext();
        ds = (javax.sql.DataSource)initialContext.lookup("jdbc/mysqldb");
    }

    public Connection getConnection() {
        if(ds == null) init();

        return ds.getConnection();
    }
}
</code>```

This means that you have a shared reference to your datasource, taking away the jndi lookup overhead.

Body:
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.

Body:
The method I have used in the past is to create a singleton class that holds the datasource

E.g.

public class DatabaseConnectionManager {

    DataSource ds;

    public void init() {
        InitialContext initialContext = new InitialContext();
        ds = (javax.sql.DataSource)initialContext.lookup("jdbc/mysqldb");
    }

    public Connection getConnection() {
        if(ds == null) init();

        return ds.getConnection();
    }
}

This means that you have a shared reference to your datasource, taking away the jndi lookup overhead.


问:
tensorflow porting to android devices
I have a question about tensorflow porting to android devices. When I was in centos, using bazel compiler generated apk file, suggesting the following error:

ERROR: /data/tensorflow-master/WORKSPACE:37:1: syntax error at 'tf_workspace': expected,
ERROR: /data/tensorflow-master/WORKSPACE:44:1: non-keyword arg after keyword arg.
ERROR: error loading package 'external': Failed to parse WORKSPACE file.
INFO: Elapsed time: 0.242s

The following is the 37-44 line of the WORKSPACE file:

Please add all new TensorFlow dependencies in workspace.bzl.

37 tf_workspace ()

38

39 new_http_archive (

40 name = "inception5h",

41 build_file = "models.BUILD",

42 url = "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip",

43 sha256 = "d13569f6a98159de37e92e9c8ec4dae8f674fbf475f69fe6199b514f756d4364"

44)

I ask you have encountered similar problems? please help me.

答:
I was facing the same problem, this is how I fixed it:</p>

```<code># Uncomment and update the paths in these entries to build the Android demo.
android_sdk_repository(
    name = "androidsdk",
    api_level = 24,
#    # Ensure that you have the build_tools_version below installed in the
#    # SDK manager as it updates periodically.
    build_tools_version = "25.0.3",
#    # Replace with path to Android SDK on your system
    path = "/home/yours/Android/Sdk/",
) #my mistake #) --> )
#
# Android NDK r12b is recommended (higher may cause issues with Bazel)
android_ndk_repository(
    name="androidndk",
    path="/home/yours/android-ndk-r12b/",
#    # This needs to be 14 or higher to compile TensorFlow.
#    # Note that the NDK version is not the API level.
    api_level=14)
</code>```

Title: tensorflow porting to android devices

Body:
I was facing the same problem, this is how I fixed it:

# Uncomment and update the paths in these entries to build the Android demo.
android_sdk_repository(
    name = "androidsdk",
    api_level = 24,
#    # Ensure that you have the build_tools_version below installed in the
#    # SDK manager as it updates periodically.
    build_tools_version = "25.0.3",
#    # Replace with path to Android SDK on your system
    path = "/home/yours/Android/Sdk/",
) #my mistake #) --> )
#
# Android NDK r12b is recommended (higher may cause issues with Bazel)
android_ndk_repository(
    name="androidndk",
    path="/home/yours/android-ndk-r12b/",
#    # This needs to be 14 or higher to compile TensorFlow.
#    # Note that the NDK version is not the API level.
    api_level=14)


问:
Ranking Scores given an array of objectives by value in Javascript
```<code>/*
Given an array of objects: ID|userName|totalScore|competitionRank,
number ID
string userName
number totalScore
number competitionRank
all competitionRanks are set to NULL
give each score a ranking in descending order
*/
</code>```

I am currently not sure if this will pass all edge cases. Also, this seems to be the fastest I can do this, any help on improvements would be awesome. It passed for the test cases I could think of. Any help will be appreciated.

//Initialize data structure
var playerScores = [
  {
    "ID": 1,
    "userName": "person1",
    "totalScore": 230,
    "competitionRank": null
  },{
    "ID": 2,
    "userName": "person2",
    "totalScore": 220,
    "competitionRank": null
  },{
    "ID":3,
    "userName": "person3",
    "totalScore": 250,
    "competitionRank": null
  },{
    "ID":4,
    "userName": "person4",
    "totalScore": 230,
    "competitionRank": null
  },{
    "ID": 5,
    "userName": "person5",
    "totalScore": 250,
    "competitionRank": null
  }
];

playerScores.sort(function(a,b){
  return b.totalScore - a.totalScore;
});

var numTies = 0;
playerScores[0].rank = 1;
for (i = 1; i < playerScores.length; i++){
  if (playerScores[i].totalScore === playerScores[i-1].totalScore){
    numTies++;
    playerScores[i].rank = playerScores[i-1].rank;
  }
  else{
    playerScores[i].rank = i+numTies;
    numTies = 0;
  }
 }

console.log(playerScores);```

答:
I believe in your current code i + numTies should actually be i + numTies + 1, because the array indices (i) are zero-based but the ranks start at 1 (for the test data in the question this didn't cause a problem because the only non-tied item was last).

But you don't need the numTies variable at all because a non-tied element's rank will always be the same as its position within the array (+1).

Also, the line before your for loop that does the first item will give an error if the array is empty, so you should test for that. And use var to declare i:

var playerScores = [
  { "ID": 1, "userName": "person1", "totalScore": 230, "competitionRank": null },
  { "ID": 2, "userName": "person2", "totalScore": 220, "competitionRank": null },
  { "ID": 3, "userName": "person3", "totalScore": 250, "competitionRank": null },
  { "ID": 4, "userName": "person4", "totalScore": 230, "competitionRank": null },
  { "ID": 5, "userName": "person5", "totalScore": 250, "competitionRank": null }
];

playerScores.sort(function(a,b){ return b.totalScore - a.totalScore; });

if (playerScores[0]) playerScores[0].rank = 1;
for (var i = 1; i < playerScores.length; i++) {
  if (playerScores[i].totalScore === playerScores[i-1].totalScore) {
    playerScores[i].rank = playerScores[i-1].rank;
  } else {
    playerScores[i].rank = i + 1;
  }
}

console.log(playerScores);```
</div>
</div>
</p>

<p>If you start the loop from 0 rather than 1, and test for the first element inside the loop, that gives you the option of restructuring the code to use an array iteration function rather than a <code>for</code> loop - which would be slower to execute but (arguably) easier to read.</p>

<p>For variety, I've used a ternary operator instead of an <code>if/else</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var playerScores = [
  { "ID": 1, "userName": "person1", "totalScore": 230, "competitionRank": null },
  { "ID": 2, "userName": "person2", "totalScore": 220, "competitionRank": null },
  { "ID": 3, "userName": "person3", "totalScore": 250, "competitionRank": null },
  { "ID": 4, "userName": "person4", "totalScore": 230, "competitionRank": null },
  { "ID": 5, "userName": "person5", "totalScore": 250, "competitionRank": null }
];

playerScores.sort(function(a,b){ return b.totalScore - a.totalScore; });

playerScores.forEach(function(player, i, arr) {
  player.rank = i === 0 || player.totalScore != arr[i-1].totalScore
              ? i + 1
              : arr[i-1].rank;
});

console.log(playerScores);</code>```

Body:
/*
Given an array of objects: ID|userName|totalScore|competitionRank,
number ID
string userName
number totalScore
number competitionRank
all competitionRanks are set to NULL
give each score a ranking in descending order
*/

I am currently not sure if this will pass all edge cases. Also, this seems to be the fastest I can do this, any help on improvements would be awesome. It passed for the test cases I could think of. Any help will be appreciated.

//Initialize data structure
var playerScores = [
  {
    "ID": 1,
    "userName": "person1",
    "totalScore": 230,
    "competitionRank": null
  },{
    "ID": 2,
    "userName": "person2",
    "totalScore": 220,
    "competitionRank": null
  },{
    "ID":3,
    "userName": "person3",
    "totalScore": 250,
    "competitionRank": null
  },{
    "ID":4,
    "userName": "person4",
    "totalScore": 230,
    "competitionRank": null
  },{
    "ID": 5,
    "userName": "person5",
    "totalScore": 250,
    "competitionRank": null
  }
];

playerScores.sort(function(a,b){
  return b.totalScore - a.totalScore;
});

var numTies = 0;
playerScores[0].rank = 1;
for (i = 1; i < playerScores.length; i++){
  if (playerScores[i].totalScore === playerScores[i-1].totalScore){
    numTies++;
    playerScores[i].rank = playerScores[i-1].rank;
  }
  else{
    playerScores[i].rank = i+numTies;
    numTies = 0;
  }
 }

console.log(playerScores);

Body:
I believe in your current code i + numTies should actually be i + numTies + 1, because the array indices (i) are zero-based but the ranks start at 1 (for the test data in the question this didn't cause a problem because the only non-tied item was last).

But you don't need the numTies variable at all because a non-tied element's rank will always be the same as its position within the array (+1).

Also, the line before your for loop that does the first item will give an error if the array is empty, so you should test for that. And use var to declare i:

var playerScores = [
  { "ID": 1, "userName": "person1", "totalScore": 230, "competitionRank": null },
  { "ID": 2, "userName": "person2", "totalScore": 220, "competitionRank": null },
  { "ID": 3, "userName": "person3", "totalScore": 250, "competitionRank": null },
  { "ID": 4, "userName": "person4", "totalScore": 230, "competitionRank": null },
  { "ID": 5, "userName": "person5", "totalScore": 250, "competitionRank": null }
];

playerScores.sort(function(a,b){ return b.totalScore - a.totalScore; });

if (playerScores[0]) playerScores[0].rank = 1;
for (var i = 1; i < playerScores.length; i++) {
  if (playerScores[i].totalScore === playerScores[i-1].totalScore) {
    playerScores[i].rank = playerScores[i-1].rank;
  } else {
    playerScores[i].rank = i + 1;
  }
}

console.log(playerScores);

If you start the loop from 0 rather than 1, and test for the first element inside the loop, that gives you the option of restructuring the code to use an array iteration function rather than a for loop - which would be slower to execute but (arguably) easier to read.

For variety, I've used a ternary operator instead of an if/else:

var playerScores = [
  { "ID": 1, "userName": "person1", "totalScore": 230, "competitionRank": null },
  { "ID": 2, "userName": "person2", "totalScore": 220, "competitionRank": null },
  { "ID": 3, "userName": "person3", "totalScore": 250, "competitionRank": null },
  { "ID": 4, "userName": "person4", "totalScore": 230, "competitionRank": null },
  { "ID": 5, "userName": "person5", "totalScore": 250, "competitionRank": null }
];

playerScores.sort(function(a,b){ return b.totalScore - a.totalScore; });

playerScores.forEach(function(player, i, arr) {
  player.rank = i === 0 || player.totalScore != arr[i-1].totalScore
              ? i + 1
              : arr[i-1].rank;
});

console.log(playerScores);


问:
Angular 4 NgOnInitReference Error
I'm trying to open a new page upon the page startup but I keep getting a

Reference Error: Window not defined.

I've only started working with TypeScript and Angular4 recently, so I'm not so sure which one of the two this problem really falls under.

```<code>export class HomeComponent implements OnInit {

testCall: Window;

constructor() {
  this.testCall = new Window();
  this.testCall.open(
    "https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

ngOnInit(): void {
  console.log("function read");

  window.open("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}
</code>```

Even if I use the this.testCall.open inside the OnInit(), I'll only get a Reference Error, but on the open method.

I know it's a simple page open when the first page opens but its been a week already and I really have no idea how to do this in the typescript/angular4 setup.

答:
Okay apparently window does not exist the server, which is why ngOnInit() and constructor() throws an error when I try to put the "window.open" there

```<code>import { Component, PLATFORM_ID, Inject, OnInit } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

export class HomeComponent {
submitted: boolean = false;

constructor(@Inject(PLATFORM_ID) private platformId: Object) {

}

ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
        window.open("URL");
    }
}
}
</code>```

This worked perfectly for me.

Title: Angular 4 NgOnInitReference Error

Body:
I'm trying to open a new page upon the page startup but I keep getting a

Reference Error: Window not defined.

I've only started working with TypeScript and Angular4 recently, so I'm not so sure which one of the two this problem really falls under.

export class HomeComponent implements OnInit {

testCall: Window;

constructor() {
  this.testCall = new Window();
  this.testCall.open(
    "https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

ngOnInit(): void {
  console.log("function read");

  window.open("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

Even if I use the this.testCall.open inside the OnInit(), I'll only get a Reference Error, but on the open method.

I know it's a simple page open when the first page opens but its been a week already and I really have no idea how to do this in the typescript/angular4 setup.

Body:
Okay apparently window does not exist the server, which is why ngOnInit() and constructor() throws an error when I try to put the "window.open" there

import { Component, PLATFORM_ID, Inject, OnInit } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

export class HomeComponent {
submitted: boolean = false;

constructor(@Inject(PLATFORM_ID) private platformId: Object) {

}

ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
        window.open("URL");
    }
}
}

This worked perfectly for me.


问:
Double quotes in c# doesn't allow multiline
e.g.

```<code>string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";
</code>```

I need to make it as for readability:

```<code> string str = "
 {
   \"aps\":
         {
             \"alert\":\"" + title + "" + message + "\"
         }
 }";
</code>```

How to achieve this, please suggest.

答:
If you really need to do this in a string literal, I'd use a verbatim string literal (the @ prefix). In verbatim string literals you need to use "" to represent a double quote. I'd suggest using interpolated string literals too, to make the embedding of title and message cleaner. That does mean you need to double the {{ and }} though. So you'd have:

```<code>string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
   ""aps"":
   {{
       ""alert"":""{title}{message}""
   }}
}}";
Console.WriteLine(str);
</code>```

Output:

```<code>{
   "aps":
   {
       "alert":"This is the title: (Message)"
   }
}
</code>```

However, this is still more fragile than simply building up JSON using a JSON API - if the title or message contain quotes for example, you'll end up with invalid JSON. I'd just use Json.NET, for example:

```<code>string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
    ["aps"] = new JObject
    {
        ["alert"] = title + message
    }
};
Console.WriteLine(json.ToString());
</code>```

That's much cleaner IMO, as well as being more robust.

Body:
e.g.

string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";

I need to make it as for readability:

 string str = "
 {
   \"aps\":
         {
             \"alert\":\"" + title + "" + message + "\"
         }
 }";

How to achieve this, please suggest.

Body:
If you really need to do this in a string literal, I'd use a verbatim string literal (the @ prefix). In verbatim string literals you need to use "" to represent a double quote. I'd suggest using interpolated string literals too, to make the embedding of title and message cleaner. That does mean you need to double the {{ and }} though. So you'd have:

string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
   ""aps"":
   {{
       ""alert"":""{title}{message}""
   }}
}}";
Console.WriteLine(str);

Output:

{
   "aps":
   {
       "alert":"This is the title: (Message)"
   }
}

However, this is still more fragile than simply building up JSON using a JSON API - if the title or message contain quotes for example, you'll end up with invalid JSON. I'd just use Json.NET, for example:

string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
    ["aps"] = new JObject
    {
        ["alert"] = title + message
    }
};
Console.WriteLine(json.ToString());

That's much cleaner IMO, as well as being more robust.


问:
Get substring within a string
I come to find some guidance on accomplishing the following:

I have a variable with content like this:

```<code>varname = asdfiuytgy12$gggsy22.oihbcxew
</code>```

or

```<code>varname = oiujedc$thisisit.oiju
</code>```

which $ and . are exactly my partters and I need to get what is within them so gggsy22 or thisisit.

I need to use batch to create a simple bat file. I hope someone can provide some guidance.

Edit - (from comment section)

Actually a friend of mine helped and it did work but with a quite amount of lines:

```<code>Set "sstr=$"
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos1=%pos%"
Set "sstr=."
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos2=%pos%"
set /a "pos2=%pos2%-%pos1%-1"
call set env=%%nameVar:~%pos1%,%pos2%%%
</code>```

答:
The following works in nearly any situation. The only thing that could break the code is if the string contains a quote " followed by a poison character like &, |, etc.

```<code>@echo off
setlocal
set "str=oiujedc$thisisit.oiju"

:: Verify string exists and has the proper format
echo "%str%"|findstr "\$.*\." >nul || (echo Value not found & exit /b)

:: Extract the value
:: The extra "x" is needed in case there is no character between $ and .,
:: in which case the result should be No Value (result variable not defined)
for /f "delims=." %%A in ("x%str:*$=%") do set "val=%%A"
set "val=%val:~1%"

:: Show the result
echo value = "%val%"
</code>```

A bullet proof variant can be made by incorporating delayed expansion.

Title: Get substring within a string

Body:
I come to find some guidance on accomplishing the following:

I have a variable with content like this:

varname = asdfiuytgy12$gggsy22.oihbcxew

or

varname = oiujedc$thisisit.oiju

which $ and . are exactly my partters and I need to get what is within them so gggsy22 or thisisit.

I need to use batch to create a simple bat file. I hope someone can provide some guidance.

Edit - (from comment section)

Actually a friend of mine helped and it did work but with a quite amount of lines:

Set "sstr=$"
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos1=%pos%"
Set "sstr=."
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos2=%pos%"
set /a "pos2=%pos2%-%pos1%-1"
call set env=%%nameVar:~%pos1%,%pos2%%%

Body:
The following works in nearly any situation. The only thing that could break the code is if the string contains a quote " followed by a poison character like &, |, etc.

@echo off
setlocal
set "str=oiujedc$thisisit.oiju"

:: Verify string exists and has the proper format
echo "%str%"|findstr "\$.*\." >nul || (echo Value not found & exit /b)

:: Extract the value
:: The extra "x" is needed in case there is no character between $ and .,
:: in which case the result should be No Value (result variable not defined)
for /f "delims=." %%A in ("x%str:*$=%") do set "val=%%A"
set "val=%val:~1%"

:: Show the result
echo value = "%val%"

A bullet proof variant can be made by incorporating delayed expansion.


答:
Can you try this?

Create a calculated field "Geo" with this definition
IFNULL(STR([Lat]),"")+ ","+IFNULL(STR([Long],"")

Move this field in "size" mark using Count([Geo])

Hope this should give you the desired result.

Title: Tableau: How to display size as the number of records for the same lat,long

Body:
On the same (lat,long) on a Tableau-Desktop map, I want the size of a dot  to be proportional to the number of records at that location. I tried count/sum(Number of Records) built-in tableau measure, I created a SeqId and tried count(SeqId) for Size, neither worked. Here is a sample of my data, as you can see:
(44.92810490,-74.89186500) has one Record
(44.69948730,-73.45291240) has five Records
(44.72143010,-73.72375280) has 10 records
I would like the point to be proportional to the number of records at that location.   Help is Much appreciated
Musa
Seq Id,Census,Gender,Lat,Long
1,1860,F,44.92810490,-74.89186500
2,1870,M,44.69948730,-73.45291240
3,1870,F,44.69948730,-73.45291240
4,1870,M,44.69948730,-73.45291240
5,1870,F,44.69948730,-73.45291240
6,1870,F,44.69948730,-73.45291240
7,1870,M,44.72143010,-73.72375280
8,1870,M,44.72143010,-73.72375280
9,1870,M,44.72143010,-73.72375280
10,1870,M,44.72143010,-73.72375280
11,1870,M,44.72143010,-73.72375280
12,1870,M,44.72143010,-73.72375280
13,1870,M,44.72143010,-73.72375280
14,1870,M,44.72143010,-73.72375280
15,1870,M,44.72143010,-73.72375280
16,1870,M,44.72143010,-73.72375280


问:
How to perform Zoom and onClick Action on Image View Using Android
I have a image view which is zoomed and when we zoom and click on image i want to get color of image how is it possible</p>

答:
@Talha_Sheikh918 please check it,

Use this library this will help you to fulfill your requirements

https://github.com/chrisbanes/PhotoView

use like this way

your_activity.xml

```<code><com.github.chrisbanes.photoview.PhotoView
    android:id="@+id/photo_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

YourActivity.java

```<code>PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setImageResource(R.drawable.image);
</code>```

Features

Out of the box zooming, using multi-touch and double-tap.

Scrolling, with smooth scrolling fling.

Works perfectly when used in a scrolling parent (such as ViewPager).

Allows the application to be notified when the displayed Matrix has changed.

Useful for when you need to update your UI based on the current zoom/scroll position.

Allows the application to be notified when the user taps on the Photo.

Edit

If you want to get color of pointed pixel.

```<code>PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);

Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();

imageView.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event){
        int x = (int)event.getX();
        int y = (int)event.getY();
        int pixel = bitmap.getPixel(x,y);

        //the pixel data
        int redValue = Color.red(pixel);
        int blueValue = Color.blue(pixel);
        int greenValue = Color.green(pixel);

        return false;
        }
   });
</code>```

Body:
@Talha_Sheikh918 please check it,

Use this library this will help you to fulfill your requirements

https://github.com/chrisbanes/PhotoView

use like this way

your_activity.xml

<com.github.chrisbanes.photoview.PhotoView
    android:id="@+id/photo_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

YourActivity.java

PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setImageResource(R.drawable.image);

Features

Out of the box zooming, using multi-touch and double-tap.

Scrolling, with smooth scrolling fling.

Works perfectly when used in a scrolling parent (such as ViewPager).

Allows the application to be notified when the displayed Matrix has changed.

Useful for when you need to update your UI based on the current zoom/scroll position.

Allows the application to be notified when the user taps on the Photo.

Edit

If you want to get color of pointed pixel.

PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);

Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();

imageView.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event){
        int x = (int)event.getX();
        int y = (int)event.getY();
        int pixel = bitmap.getPixel(x,y);

        //the pixel data
        int redValue = Color.red(pixel);
        int blueValue = Color.blue(pixel);
        int greenValue = Color.green(pixel);

        return false;
        }
   });