问:
Problem with SELECT INTO using local variables
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable.  My DB platform is MySQL 5.1, but I don't think that should make a difference here.  Basically, what I want to do is:

```<code>SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
</code>```

I can't get past the first statement, though, as I get the error "Undeclared variable var_name".  I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line.  What am I doing wrong?

答:
You need to declare @var_name and then select into @var_name.  I don't know MySQL too well but try something like this:

```<code>declare @var_name varchar(100);
SELECT id INTO @var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
</code>```

Edit: Perhaps a better way to do it:

```<code>insert into table2 ('number')
select id
from table1
where some_column = 'something' LIMIT 1;
</code>```

This negates the need for a variable and will be a lot faster and easier to understand down the road.

OwnerDisplayName: sqook

Body:
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable.  My DB platform is MySQL 5.1, but I don't think that should make a difference here.  Basically, what I want to do is:

SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);

I can't get past the first statement, though, as I get the error "Undeclared variable var_name".  I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line.  What am I doing wrong?

LastEditorDisplayName: John MacIntyre

Body:
You need to declare @var_name and then select into @var_name.  I don't know MySQL too well but try something like this:

declare @var_name varchar(100);
SELECT id INTO @var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);

Edit: Perhaps a better way to do it:

insert into table2 ('number')
select id
from table1
where some_column = 'something' LIMIT 1;

This negates the need for a variable and will be a lot faster and easier to understand down the road.

OwnerDisplayName: Andrew Hare

LastEditorDisplayName: Andrew Hare


来源: stackexchange

问:
Python Multidimensional Array as a single List
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

```<code>[[0, 1], [2, 3]]
</code>```

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

```<code>[0, 1, 2, 3]
</code>```

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

```<code>def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex
</code>```

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

答:
Are you avoiding the obvious answer (i.e. [[1, 2], [3, 4]]) because of concerns about its performance?  If so and you're working with numberes, look at NumPy arrays.  The best solution would be to not reinvent your own wheel.

Edit:
If you do feel the need to do it your own way, you could follow a strided index scheme like NumPy, wihch might go something like this:

```<code>import operator
def product(lst):
    return reduce(operator.mul, lst, 1)

class MyArray(object):
    def __init__(self, shape, initval):
        self.shape = shape
        self.strides = [ product(shape[i+1:]) for i in xrange(len(shape)) ]
        self.data = [initval] * product(shape)

    def getindex(self, loc):
        return sum([ x*y for x, y in zip(self.strides, loc) ])

    def getloc(self, index):
        loc = tuple()
        for s in self.strides:
            i = index // s
            index = index % s
            loc += (i,)
        return loc
</code>```

To be used as:

```<code>arr = MyArray((3, 2), 0)
arr.getindex((2, 1))
  -> 5
arr.getloc(5)
  -> (2, 1)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

[[0, 1], [2, 3]]

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

[0, 1, 2, 3]

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

Body:
Are you avoiding the obvious answer (i.e. [[1, 2], [3, 4]]) because of concerns about its performance?  If so and you're working with numberes, look at NumPy arrays.  The best solution would be to not reinvent your own wheel.

Edit:
If you do feel the need to do it your own way, you could follow a strided index scheme like NumPy, wihch might go something like this:

import operator
def product(lst):
    return reduce(operator.mul, lst, 1)

class MyArray(object):
    def __init__(self, shape, initval):
        self.shape = shape
        self.strides = [ product(shape[i+1:]) for i in xrange(len(shape)) ]
        self.data = [initval] * product(shape)

    def getindex(self, loc):
        return sum([ x*y for x, y in zip(self.strides, loc) ])

    def getloc(self, index):
        loc = tuple()
        for s in self.strides:
            i = index // s
            index = index % s
            loc += (i,)
        return loc

To be used as:

arr = MyArray((3, 2), 0)
arr.getindex((2, 1))
  -> 5
arr.getloc(5)
  -> (2, 1)


问:
Node.js http.request Express multiple requests with single res.render
I have successfully figured out node.js/Express code for making a single http.request to my server. However, the next step is to make multiple requests which use the same res.render statement at the end.

Here is my successful working code:

```<code>module.exports = function (app) {
    // MODULES - INCLUDES
    var xml2js = require('xml2js');
    var parser = new xml2js.Parser();

    // FORM - SUBMIT - CUCMMAPPER
    app.post('/cucmmapper/submit', function (req, res) {

        // FORM - DATA COLLECTION
        var cucmpub = req.body.cucmpub;
        var cucmversion = req.body.cucmversion;
        var username = req.body.username;
        var password = req.body.password;

        // JS - VARIABLE DEFINITION
        var authentication = username + ":" + password;
        var soapreplyx = '';
        var cssx = '';
        var spacer = '-----';
        var rmline1 = '';
        var rmline2 = '';
        var rmline3 = '';
        var rmline4 = '';
        var rmbottomup1 = '';
        var rmbottomup2 = '';
        var rmbottomup3 = '';

        // HTTP.REQUEST - BUILD CALL
        var https = require("https");
        var headers = {
            'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
            'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
            'Content-Type': 'text/xml; charset=utf-8'
        };

        // SOAP - AXL CALL
        var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listCss sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '<description>?</description>' +
            '<clause>?</clause>' +
            '</returnedTags>' +
            '</ns:listCss>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // HTTP.REQUEST - OPTIONS
        var options = {
            host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
            port: 8443, // DEFAULT CISCO SSL PORT
            path: '/axl/', // AXL URL
            method: 'POST', // AXL REQUIREMENT OF POST
            headers: headers, // HEADER VAR
            rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
        };

        // HTTP.REQUEST - Doesn't seem to need this line, but it might be useful anyway for pooling?
        options.agent = new https.Agent(options);

        // HTTP.REQUEST - OPEN SESSION
        let soapRequest = https.request(options, soapResponse => {
            soapResponse.setEncoding('utf8');
            soapResponse.on('data', chunk => {
                soapreplyx += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1 = soapreplyx.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2 = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3 = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4 = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1 = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2 = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbed = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                // console.log(xmlscrubbed);
                // console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbed, function (err, result) {
                    var cssx = result['return']['css'];
                    //   console.log(cssx);
                    //   console.log(spacer);
                    res.render('cucmmapper-results.html', {
                        title: 'CUCM Toolbox',
                        cucmpub: cucmpub,
                        cssx: cssx,
                        soapreply: soapreplyx,
                        xmlscrubbed: xmlscrubbed
                    });
                });
            });
        });

        // SOAP - SEND AXL CALL
        soapRequest.write(soapBody);
        soapRequest.end();
    });
}
</code>```

My guess is that I have to setup several things to make this work:

Another "var soapBody" with my new request (I can do this).

Another "let soapRequest" (I'm good with this too).

Another "soapRequest.write" statement (Again, easy enough).

Split the "res.render" statement out of the specific "let soapRequest" statement and gather all the variable (this is where I'm stuck).

My guess is that I need to use async. However, I can't for the life of me wrap my head around how to get that "res.render" to work with async.

Here is the closest I can come to an answer. However, the "cssx" and "partitionsx" variable are not translated over to the "function complete". They both still show up as null.

```<code>module.exports = function (app) {

    // MODULES - INCLUDES
    var xml2js = require('xml2js');
    var parser = new xml2js.Parser();

    // FORM - SUBMIT - CUCMMAPPER
    app.post('/cucmmapper/submit', function (req, res) {

        // FORM - DATA COLLECTION
        var cucmpub = req.body.cucmpub;
        var cucmversion = req.body.cucmversion;
        var username = req.body.username;
        var password = req.body.password;

        // JS - VARIABLE DEFINITION - GLOBAL
        var authentication = username + ":" + password;
        var soapreplyx = '';
        var cssx = null;
        var spacer = '-----';
        var rmline1 = '';
        var rmline2 = '';
        var rmline3 = '';
        var rmline4 = '';
        var rmbottomup1 = '';
        var rmbottomup2 = '';
        var rmbottomup3 = '';
        var soapreplyp = '';
        var partitionsx = null;
        var rmline1p = '';
        var rmline2p = '';
        var rmline3p = '';
        var rmline4p = '';
        var rmbottomup1p = '';
        var rmbottomup2p = '';
        var rmbottomup3p = '';

        // HTTP.REQUEST - BUILD CALL - GLOBAL
        var https = require("https");
        var headers = {
            'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
            'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
            'Content-Type': 'text/xml; charset=utf-8'
        };

        // SOAP - AXL CALL - CSS
        var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listCss sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '<description>?</description>' +
            '<clause>?</clause>' +
            '</returnedTags>' +
            '</ns:listCss>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // SOAP - AXL CALL - PARTITIONS
        var soapBody2 = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listRpite{artotopm} sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '</returnedTags>' +
            '</ns:listRoutePartition>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // HTTP.REQUEST - OPTIONS - GLOBAL
        var options = {
            host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
            port: 8443, // DEFAULT CISCO SSL PORT
            path: '/axl/', // AXL URL
            method: 'POST', // AXL REQUIREMENT OF POST
            headers: headers, // HEADER VAR
            rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
        };

        // HTTP.REQUEST - GLOBAL (Doesn't seem to need this line, but it might be useful anyway for pooling?)
        options.agent = new https.Agent(options);

        // HTTP.REQUEST - OPEN SESSION - CSS
        var soapRequest = https.request(options, soapResponse => {
            soapResponse.setEncoding('utf8');
            soapResponse.on('data', chunk => {
                soapreplyx += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1 = soapreplyx.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2 = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3 = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4 = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1 = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2 = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbed = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                // console.log(xmlscrubbed);
                // console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbed, function (err, result) {
                    var cssx = result['return']['css'];
                    //   console.log(cssx);
                    //   console.log(spacer);
                    complete();
                });
            });
        });

        // SOAP - SEND AXL CALL - CSS
        soapRequest.write(soapBody);
        soapRequest.end();

        // SOAP - SEND AXL CALL - PARTITIONS
        var soapRequest2 = https.request(options, soapResponse2 => {
            soapResponse2.setEncoding('utf8');
            soapResponse2.on('data', chunk => {
                soapreplyp += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse2.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1p = soapreplyy.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2p = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3p = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4p = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1p = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2p = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbedp = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                console.log(xmlscrubbedp);
                console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbedp, function (err, result) {
                    var partitionsx = result['return']['css'];
                    //   console.log(partitionsx);
                    //   console.log(spacer);
                    complete();
                });
            });
        });
        // SOAP - SEND AXL CALL - PARTITIONS
        soapRequest2.write(soapBody2);
        soapRequest2.end();

        // PAGE - RENDER
        function complete() {
            if (cssx !== null && partitionsx !== null) {
                res.render('cucmmapper-results.html', {
                    title: 'CUCM Toolbox',
                    cucmpub: cucmpub,
                    cssx: cssx,
                    partitionsx: partitionsx,
                })
            } else {
                res.render('cucmerror.html', {
                    title: 'CUCM Toolbox',
                })
            }
        };
    });
}
</code>```

Any help or suggestions would be greatly appreciated.

答:
OK, so the thing to remember is that there is always one request mapped to one response in HTTP.  So you can't send multiple requests and expect to get just one response from that.

Instead, you need to have the server keep track of what's been posted (perhaps in a database on a production app), and respond to each request in turn.  One way might be to respond with partial documents, or respond with other codes that indicate the submission was accepted but that you need to send another request to push more info, that sort of thing.

But again, you can't strictly accept multiple requests without responding and then respond only after all requests are given.

ContentLicense: CC BY-SA 3.0

Body:
I have successfully figured out node.js/Express code for making a single http.request to my server. However, the next step is to make multiple requests which use the same res.render statement at the end.

Here is my successful working code:

module.exports = function (app) {
    // MODULES - INCLUDES
    var xml2js = require('xml2js');
    var parser = new xml2js.Parser();

    // FORM - SUBMIT - CUCMMAPPER
    app.post('/cucmmapper/submit', function (req, res) {

        // FORM - DATA COLLECTION
        var cucmpub = req.body.cucmpub;
        var cucmversion = req.body.cucmversion;
        var username = req.body.username;
        var password = req.body.password;

        // JS - VARIABLE DEFINITION
        var authentication = username + ":" + password;
        var soapreplyx = '';
        var cssx = '';
        var spacer = '-----';
        var rmline1 = '';
        var rmline2 = '';
        var rmline3 = '';
        var rmline4 = '';
        var rmbottomup1 = '';
        var rmbottomup2 = '';
        var rmbottomup3 = '';

        // HTTP.REQUEST - BUILD CALL
        var https = require("https");
        var headers = {
            'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
            'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
            'Content-Type': 'text/xml; charset=utf-8'
        };

        // SOAP - AXL CALL
        var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listCss sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '<description>?</description>' +
            '<clause>?</clause>' +
            '</returnedTags>' +
            '</ns:listCss>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // HTTP.REQUEST - OPTIONS
        var options = {
            host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
            port: 8443, // DEFAULT CISCO SSL PORT
            path: '/axl/', // AXL URL
            method: 'POST', // AXL REQUIREMENT OF POST
            headers: headers, // HEADER VAR
            rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
        };

        // HTTP.REQUEST - Doesn't seem to need this line, but it might be useful anyway for pooling?
        options.agent = new https.Agent(options);

        // HTTP.REQUEST - OPEN SESSION
        let soapRequest = https.request(options, soapResponse => {
            soapResponse.setEncoding('utf8');
            soapResponse.on('data', chunk => {
                soapreplyx += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1 = soapreplyx.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2 = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3 = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4 = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1 = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2 = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbed = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                // console.log(xmlscrubbed);
                // console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbed, function (err, result) {
                    var cssx = result['return']['css'];
                    //   console.log(cssx);
                    //   console.log(spacer);
                    res.render('cucmmapper-results.html', {
                        title: 'CUCM Toolbox',
                        cucmpub: cucmpub,
                        cssx: cssx,
                        soapreply: soapreplyx,
                        xmlscrubbed: xmlscrubbed
                    });
                });
            });
        });

        // SOAP - SEND AXL CALL
        soapRequest.write(soapBody);
        soapRequest.end();
    });
}

My guess is that I have to setup several things to make this work:

Another "var soapBody" with my new request (I can do this).

Another "let soapRequest" (I'm good with this too).

Another "soapRequest.write" statement (Again, easy enough).

Split the "res.render" statement out of the specific "let soapRequest" statement and gather all the variable (this is where I'm stuck).

My guess is that I need to use async. However, I can't for the life of me wrap my head around how to get that "res.render" to work with async.

Here is the closest I can come to an answer. However, the "cssx" and "partitionsx" variable are not translated over to the "function complete". They both still show up as null.

module.exports = function (app) {

    // MODULES - INCLUDES
    var xml2js = require('xml2js');
    var parser = new xml2js.Parser();

    // FORM - SUBMIT - CUCMMAPPER
    app.post('/cucmmapper/submit', function (req, res) {

        // FORM - DATA COLLECTION
        var cucmpub = req.body.cucmpub;
        var cucmversion = req.body.cucmversion;
        var username = req.body.username;
        var password = req.body.password;

        // JS - VARIABLE DEFINITION - GLOBAL
        var authentication = username + ":" + password;
        var soapreplyx = '';
        var cssx = null;
        var spacer = '-----';
        var rmline1 = '';
        var rmline2 = '';
        var rmline3 = '';
        var rmline4 = '';
        var rmbottomup1 = '';
        var rmbottomup2 = '';
        var rmbottomup3 = '';
        var soapreplyp = '';
        var partitionsx = null;
        var rmline1p = '';
        var rmline2p = '';
        var rmline3p = '';
        var rmline4p = '';
        var rmbottomup1p = '';
        var rmbottomup2p = '';
        var rmbottomup3p = '';

        // HTTP.REQUEST - BUILD CALL - GLOBAL
        var https = require("https");
        var headers = {
            'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
            'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
            'Content-Type': 'text/xml; charset=utf-8'
        };

        // SOAP - AXL CALL - CSS
        var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listCss sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '<description>?</description>' +
            '<clause>?</clause>' +
            '</returnedTags>' +
            '</ns:listCss>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // SOAP - AXL CALL - PARTITIONS
        var soapBody2 = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
            '<soapenv:Header/>' +
            '<soapenv:Body>' +
            '<ns:listRpite{artotopm} sequence="?">' +
            '<searchCriteria>' +
            '<name>%</name>' +
            '</searchCriteria>' +
            '<returnedTags uuid="?">' +
            '<name>?</name>' +
            '</returnedTags>' +
            '</ns:listRoutePartition>' +
            '</soapenv:Body>' +
            '</soapenv:Envelope>');

        // HTTP.REQUEST - OPTIONS - GLOBAL
        var options = {
            host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
            port: 8443, // DEFAULT CISCO SSL PORT
            path: '/axl/', // AXL URL
            method: 'POST', // AXL REQUIREMENT OF POST
            headers: headers, // HEADER VAR
            rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
        };

        // HTTP.REQUEST - GLOBAL (Doesn't seem to need this line, but it might be useful anyway for pooling?)
        options.agent = new https.Agent(options);

        // HTTP.REQUEST - OPEN SESSION - CSS
        var soapRequest = https.request(options, soapResponse => {
            soapResponse.setEncoding('utf8');
            soapResponse.on('data', chunk => {
                soapreplyx += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1 = soapreplyx.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2 = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3 = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4 = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1 = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2 = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbed = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                // console.log(xmlscrubbed);
                // console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbed, function (err, result) {
                    var cssx = result['return']['css'];
                    //   console.log(cssx);
                    //   console.log(spacer);
                    complete();
                });
            });
        });

        // SOAP - SEND AXL CALL - CSS
        soapRequest.write(soapBody);
        soapRequest.end();

        // SOAP - SEND AXL CALL - PARTITIONS
        var soapRequest2 = https.request(options, soapResponse2 => {
            soapResponse2.setEncoding('utf8');
            soapResponse2.on('data', chunk => {
                soapreplyp += chunk
            });
            // HTTP.REQUEST - RESULTS + RENDER
            soapResponse2.on('end', () => {

                // EDIT - SCRUB XML OUTPUT
                var rmline1p = soapreplyy.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                var rmline2p = rmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                var rmline3p = rmline2.replace(/<soapenv:Body>/g, '');
                var rmline4p = rmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                var rmbottomup1p = rmline4.replace(/<\/soapenv:Envelope>/g, '');
                var rmbottomup2p = rmbottomup1.replace(/<\/soapenv:Body>/g, '');
                var xmlscrubbedp = rmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
                console.log(xmlscrubbedp);
                console.log(spacer);

                // XML2JS - TESTING
                parser.parseString(xmlscrubbedp, function (err, result) {
                    var partitionsx = result['return']['css'];
                    //   console.log(partitionsx);
                    //   console.log(spacer);
                    complete();
                });
            });
        });
        // SOAP - SEND AXL CALL - PARTITIONS
        soapRequest2.write(soapBody2);
        soapRequest2.end();

        // PAGE - RENDER
        function complete() {
            if (cssx !== null && partitionsx !== null) {
                res.render('cucmmapper-results.html', {
                    title: 'CUCM Toolbox',
                    cucmpub: cucmpub,
                    cssx: cssx,
                    partitionsx: partitionsx,
                })
            } else {
                res.render('cucmerror.html', {
                    title: 'CUCM Toolbox',
                })
            }
        };
    });
}

Any help or suggestions would be greatly appreciated.


问:
How to install "test apk" on actual device with appium?
How can I install an app with "-t: Allow test APKs to be installed." using appium.

i am getting the following error:

```<code>MJSONWP] Encountered internal error running command: Error: Remote
install failed: pLocation:automatic, pLang: , pRegn:
pLocation(NoSIM):english_us, pLang: en, pRegn: US
pkg: /data/local/tmp/b388778c9058a24fd29dbe6b414a02e3.apk
Failure [INSTALL_FAILED_TEST_ONLY]
</code>```

答:
There is no problem with Appium itself, but adb install command failed.

Failure [INSTALL_FAILED_TEST_ONLY] is most likely caused by android:testOnly="true" in manifest xml file of your Android application.

You need to change this parameter value to false and rebuild project to get valid apk file.

Body:
How can I install an app with "-t: Allow test APKs to be installed." using appium.

i am getting the following error:

MJSONWP] Encountered internal error running command: Error: Remote
install failed: pLocation:automatic, pLang: , pRegn:
pLocation(NoSIM):english_us, pLang: en, pRegn: US
pkg: /data/local/tmp/b388778c9058a24fd29dbe6b414a02e3.apk
Failure [INSTALL_FAILED_TEST_ONLY]


问:
Could not find com.opentok.android:opentok-android-sdk
Do you have an issue with your tokbox maven's ?
Because since this morning i can't compile my project, i have this error :

Could not find any matches for com.opentok.android:opentok-android-sdk:2.8.+

also after upgrade sdk version to 2.12.1 it's same

The maven links are in 404 :
https://bintray.com/tokbox/maven/opentok-android-sdk
http://tokbox.bintray.com/maven

Thanks

答:
We’re currently having an issue with one of our providers so the OpenTok Android SDK is unavailable at: https://bintray.com/tokbox/maven/opentok-android-sdk.

Temporarily, you can access the OpenTok Android SDK at the following url: https://tokbox-telefonica.bintray.com/maven

We're working to resolve this immediately so I'll update this answer as we go further!

UPDATE 11/15/17 ~7:45 am PST:
We've restored the original URL: https://tokbox.bintray.com/maven/


问:
How can I see if a network connection changes state?
I am writing an application that checks if the computer is connected to one particular network or not, and does some magic for our users.

The application will run in the background and perform the check if the user requests it (menu in tray). I also want the application to automatically check and do magic if the user changes from wired to wireless, or disconnects and connects to a new network.

Is it possible to make it trigger when a network interface changes state?

答:
You should use System.Net.NetworkInformation

```<code> NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler((sender, e, ...otherParametersIfYouWant) => AvailabilityChangedCallback(sender, e, ...));
private void AvailabilityChangedCallback(object sender, NetworkAvailabilityEventArgs e)
    {
        if (e.IsAvailable)
        {
        //Internet Connection is available
        }
     }
</code>```

For other informations check this

Body:
You should use System.Net.NetworkInformation

 NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler((sender, e, ...otherParametersIfYouWant) => AvailabilityChangedCallback(sender, e, ...));
private void AvailabilityChangedCallback(object sender, NetworkAvailabilityEventArgs e)
    {
        if (e.IsAvailable)
        {
        //Internet Connection is available
        }
     }

For other informations check this


问:
Spring MVC returning 406 to controller test
I have the following project tree:

```<code>├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml
</code>```

I have the following test class :

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}
</code>```

I have the following PingController.java:

```<code>@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}
</code>```

I have the following SpringWebMvcInitializer.java:

```<code>@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}
</code>```

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

```<code>04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code>```

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?

答:
You can try adding a content type.
    this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON)).contentType(MediaType.APPLICATION_JSON))andExpect(status().isOk());

Body:
I have the following project tree:

├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml

I have the following test class :

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}

I have the following PingController.java:

@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}

I have the following SpringWebMvcInitializer.java:

@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?


问:
Is it possible to make a soap web service call in VB script from uft tool
I am new to web service.
I am trying to send a request and get response from a SOAP webservice from my uft code(VB script). How can I do this. When I try to find a solution, I m being shown how to test webservice. But here I am not testing webservice, it is a part of my flow.</p>

答:
Here is the vb script to call the soap service and get the response.</p>

```<code>Dim oXMLHTTP,result

'Request XML
strEnvelope="C:\request.xml"
url = "soap end point"
Set oXMLHTTP=CreateObject("MSXML2.XMLHTTP.4.0")
oXMLHTTP.Open "Post", url, false
oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXMLHTTP.setRequestHeader "Content-Type", "application/xml"
oXMLHTTP.send (strEnvelope)
result = oXMLHTTP.responseText

Set oXMLHTTP=Nothing
</code>```

Body:
Here is the vb script to call the soap service and get the response.

Dim oXMLHTTP,result

'Request XML
strEnvelope="C:\request.xml"
url = "soap end point"
Set oXMLHTTP=CreateObject("MSXML2.XMLHTTP.4.0")
oXMLHTTP.Open "Post", url, false
oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXMLHTTP.setRequestHeader "Content-Type", "application/xml"
oXMLHTTP.send (strEnvelope)
result = oXMLHTTP.responseText

Set oXMLHTTP=Nothing


问:
Fetch similar values from an Array in ruby
I have an array

```<code>sample_array = [10001567, 10001789, 2347800, 10001534, 64786592, 00000355]
output_array = [10001567, 10001789, 10001534]
</code>```

I need to fetch all the elements into a new array where the first 5 digits must be same in a given array. How to do this in ruby.

Body:
I have an array

sample_array = [10001567, 10001789, 2347800, 10001534, 64786592, 00000355]
output_array = [10001567, 10001789, 10001534]

I need to fetch all the elements into a new array where the first 5 digits must be same in a given array. How to do this in ruby.

Body:
sample_array = [10001567, 10001789, 2347800, 10001534, 64786592]
patterns = sample_array.group_by { |el| el.to_s.chars.first(5).join.to_i }
=> {10001=>[10001567, 10001789, 10001534], 23478=>[2347800], 64786=>[64786592]}

UPDATE

Selecting the pattern for this specific case

patterns.select{|_,v| v.size > 1}.values.flatten


问:
Why shouldn't you use import all in ES6
So I recently started learning react and noticed that all the documentation has imports that look like else:

```<code>import { Apples, Bananas, Oranges } from 'fruits';
</code>```

But while studying react I found that this syntax works just as well:

```<code>import * as Fruits from 'fruits';
</code>```

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.

答:
That depends upon what module bundler you're using. If you're using > webpack 2.0 as your bundler then it would affect the bundle size because :

```<code>import { Apples, Bananas, Oranges } from 'fruits';
</code>```

will only bring Apples, Bananas and Oranges from the file as webpack 2.0 uses tree-shaking algorithm for optimisation. Also, in that case, you need to take care that you don't do any default export in your file, instead you export const because named exports would suffice that.

```<code>import * as Fruits from 'fruits';
</code>```

would just bring everything declared in fruits file.

I found this great conversation with Dan Abramov on twitter and that should help you.

https://twitter.com/dan_abramov/status/927835086577430529

EDIT

In case of lodash, you'd probably want to use babel-lodash-plugin. If you'd use that then you won't have to do

```<code>import {isEmpty, isUndefined} from 'lodash';
</code>```

and you can do

```<code>import _ from 'lodash';
</code>```

as it doesn't bring the whole library for you.

Title: Why shouldn't you use import all in ES6

Body:
So I recently started learning react and noticed that all the documentation has imports that look like else:

import { Apples, Bananas, Oranges } from 'fruits';

But while studying react I found that this syntax works just as well:

import * as Fruits from 'fruits';

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.

Body:
That depends upon what module bundler you're using. If you're using > webpack 2.0 as your bundler then it would affect the bundle size because :

import { Apples, Bananas, Oranges } from 'fruits';

will only bring Apples, Bananas and Oranges from the file as webpack 2.0 uses tree-shaking algorithm for optimisation. Also, in that case, you need to take care that you don't do any default export in your file, instead you export const because named exports would suffice that.

import * as Fruits from 'fruits';

would just bring everything declared in fruits file.

I found this great conversation with Dan Abramov on twitter and that should help you.

https://twitter.com/dan_abramov/status/927835086577430529

EDIT

In case of lodash, you'd probably want to use babel-lodash-plugin. If you'd use that then you won't have to do

import {isEmpty, isUndefined} from 'lodash';

and you can do

import _ from 'lodash';

as it doesn't bring the whole library for you.


问:
How to retrieve an array from an AJAX call?
I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :

```<code>$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
                        });
</code>```

Here is the method that is called :

```<code><?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo $data; //returning the array
}
</code>```

Thanks

答:
You cant just echo an array (you can't, it an array not a simple value).

Luckily, there is a thing called JSON. In PHP you store all the information you want (in this case, your rows from the DB) in a large array and then you do echo json_encode($array);.

At the Javascript side you change the $.ajax to $.getJSON so that jQuery also understands that we're talking about JSON, et voila, you have a nice javascript version of your PHP array.

```<code>// I am not familiar with PDO, but something along these lines:
$allData = $req->fetchAll();
echo json_encode($allData); // Now you output a JSON version of the array
</code>```

And then javascript

```<code>$.getJSON(
    'http://localhost/Project/ajaxmethod.php',
    {action: this.title},
    function(response) {
        // And in 'response' you now have a ready to use JS object)
        console.log(response);
 });
</code>```

*You can also use $.ajax() if you really want to, just add a dataType: 'json

Body:
I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :

$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
                        });

Here is the method that is called :

<?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo $data; //returning the array
}

Thanks

Body:
You cant just echo an array (you can't, it an array not a simple value).

Luckily, there is a thing called JSON. In PHP you store all the information you want (in this case, your rows from the DB) in a large array and then you do echo json_encode($array);.

At the Javascript side you change the $.ajax to $.getJSON so that jQuery also understands that we're talking about JSON, et voila, you have a nice javascript version of your PHP array.

// I am not familiar with PDO, but something along these lines:
$allData = $req->fetchAll();
echo json_encode($allData); // Now you output a JSON version of the array

And then javascript

$.getJSON(
    'http://localhost/Project/ajaxmethod.php',
    {action: this.title},
    function(response) {
        // And in 'response' you now have a ready to use JS object)
        console.log(response);
 });

*You can also use $.ajax() if you really want to, just add a dataType: 'json


问:
bufferReader or InputStreamReader always throws exception
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

```
try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }
```

答:
Instead of doing this,

```<code>HscoreText.setText("IOException");
</code>```

You can do this.

```<code>HscoreText.setText(e.getMessage());
</code>```

to see the exception message. Are you saying that your code works outside of Android?

Try restarting Eclipse and the Emulator. Try using a different URL.

Body:
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }

Body:
Instead of doing this,

HscoreText.setText("IOException");

You can do this.

HscoreText.setText(e.getMessage());

to see the exception message. Are you saying that your code works outside of Android?

Try restarting Eclipse and the Emulator. Try using a different URL.


问:
not getting right data in my backend from client
I am trying to send data to my backend, but when it comes to backend it catches an expception thus returns error message.
  I am assuming this is becuase data format from client side is somehow different than what I expected.

I expcect my backend to receive json string(I have other function that takes jsong string to object later).

What am I doing it wrong? I am aware that I can create modelling class for my data from client in my backend, but I need to work it without them and it shoud work as data are all string from my client
  from client.

client

```<code>  //to backend
  callServer() {
    var data = JSON.stringify(test);
    //dispaly JSON like {"GradeA" : "23", "GradeB" : "45", "GradeC" : "22"}
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                        .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
      })
  }
</code>```

backend

```<code>public class testAPiController : ApiController
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public string test([FromBody] string body)
    {
        try
        {
            Log.Info(string.Format("data {0}", body));
            //convert to json object
            return json_object;
        }

        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return "error";
        }
    }
}
</code>```

Config

```<code>public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            // Web API configuration and services
            log4net.Config.XmlConfigurator.Configure();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "GET", id = RouteParameter.Optional }
            );

        }
    }
</code>```

Updated1

I don't get any error message, but return my body as null

Updated2

```<code> this.appService.http.post('http://localhost:2717/api/testAPi/test', "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}", {headers: headers})
</code>```

still not working with different format of the body while Postman works with it

答:
I am 99% sure it is caused by that you are defining that you are sending JSON (object) - your header shows that to WebAPI:

```<code>headers = new HttpHeaders().set('Content-Type', 'application/json');
</code>```

and this object is quite complex.
In Controller you are expecting simple string.

You should either:

Move JSON deserializing job to Controller by defining model in method prototype:

```<code>public string test([FromBody] YourClassResemblingJson body)
{
    ...
}
</code>```

Please look at more detiled information in this matter at: Post json data in body to web api

Or just send your JSON as properly formatted string. So JSON that originally looks like this:

```<code>{"body": "sampleBody"}
</code>```

should look like this:

```<code>"{\"body\": \"sampleBody\"}"
</code>```

Your code for this would look like this:

```<code>callServer() {
    var data = JSON.stringify(test);
    data = "\"" + data.replace("\"", "\\\"") + "\"";
    //display JSON like "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}"
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                    .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
     })
}
</code>```

In first approach you'll have body object filled with your data from JSON, and in the second approach you'll have correct string in your body variable.

Sorry for so much editing, but I wasn't sure about what exactly is your problem, so it took me some time to dig up into the WebAPI specifications.

Body:
I am trying to send data to my backend, but when it comes to backend it catches an expception thus returns error message.
  I am assuming this is becuase data format from client side is somehow different than what I expected.

I expcect my backend to receive json string(I have other function that takes jsong string to object later).

What am I doing it wrong? I am aware that I can create modelling class for my data from client in my backend, but I need to work it without them and it shoud work as data are all string from my client
  from client.

client

  //to backend
  callServer() {
    var data = JSON.stringify(test);
    //dispaly JSON like {"GradeA" : "23", "GradeB" : "45", "GradeC" : "22"}
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                        .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
      })
  }

backend

public class testAPiController : ApiController
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public string test([FromBody] string body)
    {
        try
        {
            Log.Info(string.Format("data {0}", body));
            //convert to json object
            return json_object;
        }

        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return "error";
        }
    }
}

Config

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            // Web API configuration and services
            log4net.Config.XmlConfigurator.Configure();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "GET", id = RouteParameter.Optional }
            );

        }
    }

Updated1

I don't get any error message, but return my body as null

Updated2

 this.appService.http.post('http://localhost:2717/api/testAPi/test', "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}", {headers: headers})

still not working with different format of the body while Postman works with it

Body:
I am 99% sure it is caused by that you are defining that you are sending JSON (object) - your header shows that to WebAPI:

headers = new HttpHeaders().set('Content-Type', 'application/json');

and this object is quite complex.
In Controller you are expecting simple string.

You should either:

Move JSON deserializing job to Controller by defining model in method prototype:

public string test([FromBody] YourClassResemblingJson body)
{
    ...
}

Please look at more detiled information in this matter at: Post json data in body to web api

Or just send your JSON as properly formatted string. So JSON that originally looks like this:

{"body": "sampleBody"}

should look like this:

"{\"body\": \"sampleBody\"}"

Your code for this would look like this:

callServer() {
    var data = JSON.stringify(test);
    data = "\"" + data.replace("\"", "\\\"") + "\"";
    //display JSON like "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}"
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                    .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
     })
}

In first approach you'll have body object filled with your data from JSON, and in the second approach you'll have correct string in your body variable.

Sorry for so much editing, but I wasn't sure about what exactly is your problem, so it took me some time to dig up into the WebAPI specifications.


问:
Include list_route methods in Django REST framework's API root
I'm using the Django REST framework, and I have a view set with an extra list route method. How can I get that method's URL included in the API root page?

Here's a simplified version of my view set:

```<code>class BookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (permissions.IsAuthenticated, )

    @list_route(methods=['get'])
    def featured(self, request):
        queryset = self.filter_queryset(self.get_queryset()).filter(featured=True)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
</code>```

I register the view set in urls.py:

```<code>router = DefaultRouter()
router.register('books', BookViewSet)
urlpatterns = patterns(
    url(r'^api/', include(router.urls), name='api_home'),
    #...
    )
</code>```

The URL for books/featured is routed properly, but when I go to http://localhost:8000/api, I only see this:

```<code>HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, HEAD, OPTIONS

{
    "books": "http://localhost:8000/api/books/"
}
</code>```

How can I get an entry added for something like this?

```<code>"book-featured-list": "http://localhost:8000/api/books/featured"
</code>```

答:
I use this solution based on likeon's answer:</p>

```<code>class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self, api_urls=None):
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        api_root_dict['books/featured'] = 'book-featured'

        return self.APIRootView.as_view(api_root_dict=api_root_dict)
</code>```

Body:
I'm using the Django REST framework, and I have a view set with an extra list route method. How can I get that method's URL included in the API root page?

Here's a simplified version of my view set:

class BookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (permissions.IsAuthenticated, )

    @list_route(methods=['get'])
    def featured(self, request):
        queryset = self.filter_queryset(self.get_queryset()).filter(featured=True)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

I register the view set in urls.py:

router = DefaultRouter()
router.register('books', BookViewSet)
urlpatterns = patterns(
    url(r'^api/', include(router.urls), name='api_home'),
    #...
    )

The URL for books/featured is routed properly, but when I go to http://localhost:8000/api, I only see this:

HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, HEAD, OPTIONS

{
    "books": "http://localhost:8000/api/books/"
}

How can I get an entry added for something like this?

"book-featured-list": "http://localhost:8000/api/books/featured"

Body:
I use this solution based on likeon's answer:

class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self, api_urls=None):
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        api_root_dict['books/featured'] = 'book-featured'

        return self.APIRootView.as_view(api_root_dict=api_root_dict)


问:
Error: clientWidth is not declared configurable in http://localhost:9877node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 4410)
I am trying to mock ElementRef properties while unit testing my angular component and it give me the below error

```<code>Error: clientWidth is not declared configurable in http://localhost:9877node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 4410)
</code>```

I am getting the error when try to mock the property of native element of an element as below

```<code>const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
div.triggerEventHandler('mouseover', null);
fixture.detectChanges();
expect(component.tooltip.isOpen()).toBeFalsy();
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
</code>```

spyOnProperty is creating that error.

答: clientWidth and scrollWidth are readonly properties of javascript and Its not possible to set value using SpyOn. So you need to use other way by calling other part of the application to set these kind of read only properties.

Body:
I am trying to mock ElementRef properties while unit testing my angular component and it give me the below error

Error: clientWidth is not declared configurable in http://localhost:9877node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 4410)

I am getting the error when try to mock the property of native element of an element as below

const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
div.triggerEventHandler('mouseover', null);
fixture.detectChanges();
expect(component.tooltip.isOpen()).toBeFalsy();
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);

spyOnProperty is creating that error.


问:
Getting the values of textboxes in Javascript
I have this html code:

```<code><table border="" cellpadding="3" cellspacing="0" id="mytable">

<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
</code>```

How do I get the values of "song" and "artist"? I have tried:

```<code>var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
</code>```

but I keep getting "undefined" even when there is text inside the textbox

答:
```<code>var song   = document.getElementsByName("song").value;
var artist = document.getElementsByName("artist").value;
</code>```

Body:
I have this html code:

Song:	 <input type="text" name="song" maxlength="64" size="48" />

Artist:	 <input type="text" name="artist" maxlength="16" size="48" />

How do I get the values of "song" and "artist"? I have tried:

var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);

but I keep getting "undefined" even when there is text inside the textbox


问:
Error retrieving instanceType for base - LDAP Search
I am connecting to AD Server from my application using LDAP. I got successfully authenticated but when I search for an user it throws an exception with LDAP Error code 32 in acl_read: instanceType for base.

```<code>javax.naming.NameNotFoundException: [LDAP: error code 32 - acl_read: Error retrieving instanceType for base. at ../source4/dsdb/samdb/ldb_modules/acl_read.c:362]
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.searchAux(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.c_search(Unknown Source)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(Unknown Source)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
at javax.naming.directory.InitialDirContext.search(Unknown Source)
</code>```

I have verified the baseDN, domain name and port, they are correct and we are able to connect to it.

I got the query string from logs and I verified the same in custom search in AD Browser. It seems to be working fine and giving back the results.

```<code>Query from Logs: (&(objectClass=user)(objectCategory=person)(|(|(sAMAccountname=*MSUser1*)(givenName=*MSUser1*)(sn=*MSUser1*))))
</code>```

Not sure what is going wrong here. Can some help me in identifying and fixing this issue.

Thanks

答:
Issue is with the baseDN itself. We have configured the LDAP rightly but somewhere in the code there is a property file which is overwriting the baseDN we had in settings. It was really tough to identify because it is not documented anywhere and we had to decompile all class files to get to the details of that file.

Along with that we modified our TOP_OU and USERS_OU and DN_PREFIX, then it started pulling all the users.

```<code>TOP_LEVEL_OU_OR_GROUP_DN=DC=awssiladev,DC=mycomp,DC=com
USER_OU_OR_GROUP_DN=CN=Users,DC=awssiladev,DC=mycomp,DC=com
DN_PREFIX=CN=
</code>```

Body:
I am connecting to AD Server from my application using LDAP. I got successfully authenticated but when I search for an user it throws an exception with LDAP Error code 32 in acl_read: instanceType for base.

javax.naming.NameNotFoundException: [LDAP: error code 32 - acl_read: Error retrieving instanceType for base. at ../source4/dsdb/samdb/ldb_modules/acl_read.c:362]
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.searchAux(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.c_search(Unknown Source)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(Unknown Source)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
at javax.naming.directory.InitialDirContext.search(Unknown Source)

I have verified the baseDN, domain name and port, they are correct and we are able to connect to it.

I got the query string from logs and I verified the same in custom search in AD Browser. It seems to be working fine and giving back the results.

Query from Logs: (&(objectClass=user)(objectCategory=person)(|(|(sAMAccountname=*MSUser1*)(givenName=*MSUser1*)(sn=*MSUser1*))))

Not sure what is going wrong here. Can some help me in identifying and fixing this issue.

Thanks

Body:
Issue is with the baseDN itself. We have configured the LDAP rightly but somewhere in the code there is a property file which is overwriting the baseDN we had in settings. It was really tough to identify because it is not documented anywhere and we had to decompile all class files to get to the details of that file.

Along with that we modified our TOP_OU and USERS_OU and DN_PREFIX, then it started pulling all the users.

TOP_LEVEL_OU_OR_GROUP_DN=DC=awssiladev,DC=mycomp,DC=com
USER_OU_OR_GROUP_DN=CN=Users,DC=awssiladev,DC=mycomp,DC=com
DN_PREFIX=CN=


问:
Fill vector with sequence
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

```<code>sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
</code>```

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

答:
In sekv you currently pass 2.. 4 ..6, use seq_along

```<code>   sekv <- seq(from = 1, to = 20, by = 2)
    test <- c()
    for (j in seq_along(sekv)) {
      test[j] = j
    }
     test
</code>```

Title: Fill vector with sequence

Body:
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

Body:
In sekv you currently pass 2.. 4 ..6, use seq_along

   sekv <- seq(from = 1, to = 20, by = 2)
    test <- c()
    for (j in seq_along(sekv)) {
      test[j] = j
    }
     test


问:
Gradle Project Sync Failed Android Studio 3.0 (JDK 9.0.1)
I tried all solutions to fix it, but nothing has succeeded. (Turned gradle to "offline work", deleted .gradle files, invalidated and restarted. I also removed the jdk-android studio completely and installed again.)

Here is the problem's screenshot:
Android Studio 3.0 Gradle Sync Problem

Here is my java version

and here is the system/log file:

答:
I uninstalled Android Studio completely and reinstall 3 times. In every step I clicked on Gradle Sync error messages and installed all missing files. 3rd time installation has succeeded with get rid of gradle sync problem with installing missing files correctly. I don't know how and why it has not been successful 1st and 2nd time installation. Anyway, it's done.

Note: Before that I have tried all of answers. Thanks a lot.

Succeeded


问:
Entity Framework inherited property as 'contained query'
I have this table:

```<code>[Table(Name = "Faxes")]
public class FaxRecord
{
     [Column(Name = "CompletedDate")]
     string CompletedDate { get; set; }

     // other columns...
}
</code>```

Is it possible to add a new property IsFinished to FaxRecord such that:

IsFinished = CompletedDate==null

IsFinished may be used to query the "Faxes" sql table. (i.e. it may be used as an expression, for example calling DataContext.GetTable<FaxRecord>().Where(fax => fax.IsFinished).ToList() would return all the records where CompletedDate == null.

The relevant use case of this is that perhaps I would like FaxRecord to inherit from some interface for maintaining faxes, which has a property IsFinished rather than CompletedDate.

Thanks

答:
Yes, it is:</p>

```<code>[Column(Name = "IsFinished")]
public bool IsFinished => string.IsNullOrEmpty(CompletedDate);
</code>```

Body:
I have this table:

[Table(Name = "Faxes")]
public class FaxRecord
{
     [Column(Name = "CompletedDate")]
     string CompletedDate { get; set; }

     // other columns...
}

Is it possible to add a new property IsFinished to FaxRecord such that:

IsFinished = CompletedDate==null

IsFinished may be used to query the "Faxes" sql table. (i.e. it may be used as an expression, for example calling DataContext.GetTable<FaxRecord>().Where(fax => fax.IsFinished).ToList() would return all the records where CompletedDate == null.

The relevant use case of this is that perhaps I would like FaxRecord to inherit from some interface for maintaining faxes, which has a property IsFinished rather than CompletedDate.

Thanks

Body:
Yes, it is:

[Column(Name = "IsFinished")]
public bool IsFinished => string.IsNullOrEmpty(CompletedDate);


问:
Check all numbers are equal
What is the best way to check that all numbers in the array (or list) are equal?

I think the solution as a loop that seek for the first unequal element ist maybe efficient, but not so elegant or readable. Any solutions in one line?

答:
Any solution to this problem must run in Ω(n) time and make Ω(n) comparisons, since if this isn't the case for some sufficiently large array you wouldn't be able to look at all the elements to check that they have the same value.

Doing a linear scan of the array looking for any values different from the first one is perhaps the absolute best way to solve this problem.  It makes a total of (n - 1) comparisons, which asymptotically matches the lower bound, and is both elegant and easy to implement.

Title: Check all numbers are equal


问:
Tooltip doesn't let me type text when it is appeared. IDEA's editor
I am working with Itellij IDEA (2017.2.4). I am not sure whether the reason is new version of IDEA, but I started to face it after new version installed.

When I type some code in editor and Tooltip is shown (it can be inspection or just parameters of method shown ect.) I cannot type new symbols until pressing ESCAPE button, it is not useful for me. Before updating the IDEA there was behavior when user types new code, tooltip is hidden without ESCAPE pressing. It was made hidden by any key pressed.

Actually maybe I just change some setting property unconsciously, if yes - what is the property needed to be restored to default?

How to make it hidden not by ESCAPE but by any button?

In next image I pictured the moment when only ESCAPE key can be pressed.

答: Check Tooltip initial delay(ms) option under Appearance in Idea settings.


问:
How to use SQL Joins and Selects to get results from a third table that matches the first two?
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

```<code>Select * from 3rdTable where City='' AND State='';
</code>```

Result from Join is like

```<code> - City | State
 - A    | B
 - C    | D
 - E    | F
</code>```

Example Result if only 1 row of the 3rd table matches

```<code> - C    |  D
</code>```

How can this be done?

答:
Be sure about the joins, we have inner join, Left join, right join and outer join; maybe knowing the difference can help you to answer your question.
and also the code is not clear :)</p>

Body:
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

Select * from 3rdTable where City='' AND State='';

Result from Join is like

 - City | State
 - A    | B
 - C    | D
 - E    | F

Example Result if only 1 row of the 3rd table matches

 - C    |  D

How can this be done?


问:
Automatic restart of SolR after Elastic Beanstalk deployment
I have a RoR application on AWS.
My app is using SolR for the search engine, but after each deployment, the app is unable to index again. So I have to reset permissions and restart Solr manually with:

```<code>chmod 777 -R /solr /tmp /log
RAILS_ENV=production rake sunspot:solr:stop # or I kill the processus if it doesn't work :D
RAILS_ENV=production rake sunspot:solr:start
RAILS_ENV=production rake sunspot:reindex
</code>```

Now i'm trying to setup it as an eb extension to automate the deployment.
Here is what I tried in my .ebextensions/deploy.config:

```<code>container_commands:
  1_change_permissions:
    command: chmod 700 .ebextensions/setup.sh
  2_restart_solr:
    command: bash .ebextensions/setup.sh
</code>```

And here is the setup.sh script:

```<code>#!/bin/bash
chmod 777 -R solr/ log/ tmp/
RAILS_ENV=production rake sunspot:solr:restart
</code>```

The result is the deployment doesn't fail but, only the permissions are changed correctly, and the solr service is running but when I try to index something, it fails (the querying works fine).

I also tried to stop the server before the app is deployed by adding a commands block in my .ebextensions/deploy.config (and I changed my sh script to start the service instead of restart) :

```<code>commands:
  1_stop_solr:
    command: cd /var/app/current & RAILS_ENV=production rake sunspot:solr:stop
</code>```

I got this error (I don't know from where it is executed):

[2015-06-25T09:51:35.510Z] INFO  [13207] - [CMD-AppDeploy/AppDeployStage0/EbExtensionPreBuild/Infra-EmbeddedPreBuild/prebuild_0_My_First_Elastic_Beanstalk_Application/Command 1_stop_solr] : Activity execution failed, because: rake aborted!
  couldn't find HOME environment -- expanding `~'

EDIT 1 (following jay's comment):
The indexation process is done when I save the objects.

Here is an example for an entity (and where it fails) :

```<code>class Document < ActiveRecord::Base

  # .....

  # SolR entity
  searchable do
    text :title, :description, :tags
    integer :user_id
  end

  # .....

end
</code>```

**EDIT 2: **

James' answer doesn't fix the problem but,
I realize that manually on my EC2 instance, i can just run the 2 following lines :

```<code>chmod 777 -R solr/ tmp/ log/
RAILS_ENV=production rake sunspot:reindex"
</code>```

I tried to use James' link to create a post-deployment script, and the chmod works well but when I add the reindex command into the file, the deployment fails with this error :

```<code>[2015-07-07T16:26:25.509Z] INFO  [20402] - [CMD-AppDeploy/AppDeployStage1/AppDeployPostHook/99_restart_delayed_job.sh] : Activity execution failed, because: rake aborted!
Could not find rake-10.4.2 in any of the sources
/var/app/current/config/boot.rb:3:in `<top (required)>'
/var/app/current/config/application.rb:1:in `<top (required)>'
/var/app/current/Rakefile:4:in `<top (required)>'
</code>```

Also, if i try to run the command manually (after the post-deployment script chmod), it fails with 500 errors on each item to reindex. So i need to kill the solr server, start and then reindex.

It's really painful :)

答:
I know this is an old question but I have written an ebextensions script that seems to work well for this case. Hopefully this will help if people are still encountering this issue.</p>

```<code>commands:
    000_sudo:
        command: sudo su
    001_cd_to_app:
        command: cd /var/app/current
    002_rm_solr:
        command: rm -rf solr/
    003_start_solr:
        command: bundle exec rails sunspot:solr:start RAILS_ENV=production
    004_reindex_solr:
        command: bundle exec rails sunspot:solr:reindex RAILS_ENV=production
</code>```

Body:
I have a RoR application on AWS.
My app is using SolR for the search engine, but after each deployment, the app is unable to index again. So I have to reset permissions and restart Solr manually with:

chmod 777 -R /solr /tmp /log
RAILS_ENV=production rake sunspot:solr:stop # or I kill the processus if it doesn't work :D
RAILS_ENV=production rake sunspot:solr:start
RAILS_ENV=production rake sunspot:reindex

Now i'm trying to setup it as an eb extension to automate the deployment.
Here is what I tried in my .ebextensions/deploy.config:

container_commands:
  1_change_permissions:
    command: chmod 700 .ebextensions/setup.sh
  2_restart_solr:
    command: bash .ebextensions/setup.sh

And here is the setup.sh script:

#!/bin/bash
chmod 777 -R solr/ log/ tmp/
RAILS_ENV=production rake sunspot:solr:restart

The result is the deployment doesn't fail but, only the permissions are changed correctly, and the solr service is running but when I try to index something, it fails (the querying works fine).

I also tried to stop the server before the app is deployed by adding a commands block in my .ebextensions/deploy.config (and I changed my sh script to start the service instead of restart) :

commands:
  1_stop_solr:
    command: cd /var/app/current & RAILS_ENV=production rake sunspot:solr:stop

I got this error (I don't know from where it is executed):

[2015-06-25T09:51:35.510Z] INFO  [13207] - [CMD-AppDeploy/AppDeployStage0/EbExtensionPreBuild/Infra-EmbeddedPreBuild/prebuild_0_My_First_Elastic_Beanstalk_Application/Command 1_stop_solr] : Activity execution failed, because: rake aborted!
  couldn't find HOME environment -- expanding `~'

EDIT 1 (following jay's comment):
The indexation process is done when I save the objects.

Here is an example for an entity (and where it fails) :

class Document < ActiveRecord::Base

  # .....

  # SolR entity
  searchable do
    text :title, :description, :tags
    integer :user_id
  end

  # .....

end

**EDIT 2: **

James' answer doesn't fix the problem but,
I realize that manually on my EC2 instance, i can just run the 2 following lines :

chmod 777 -R solr/ tmp/ log/
RAILS_ENV=production rake sunspot:reindex"

I tried to use James' link to create a post-deployment script, and the chmod works well but when I add the reindex command into the file, the deployment fails with this error :

[2015-07-07T16:26:25.509Z] INFO  [20402] - [CMD-AppDeploy/AppDeployStage1/AppDeployPostHook/99_restart_delayed_job.sh] : Activity execution failed, because: rake aborted!
Could not find rake-10.4.2 in any of the sources
/var/app/current/config/boot.rb:3:in `<top (required)>'
/var/app/current/config/application.rb:1:in `<top (required)>'
/var/app/current/Rakefile:4:in `<top (required)>'

Also, if i try to run the command manually (after the post-deployment script chmod), it fails with 500 errors on each item to reindex. So i need to kill the solr server, start and then reindex.

It's really painful :)

Body:
I know this is an old question but I have written an ebextensions script that seems to work well for this case. Hopefully this will help if people are still encountering this issue.

commands:
    000_sudo:
        command: sudo su
    001_cd_to_app:
        command: cd /var/app/current
    002_rm_solr:
        command: rm -rf solr/
    003_start_solr:
        command: bundle exec rails sunspot:solr:start RAILS_ENV=production
    004_reindex_solr:
        command: bundle exec rails sunspot:solr:reindex RAILS_ENV=production


问:
syntax error on line 15, col 2: ` socket: /tmp/mysql.sock'
Hello World ( stackoverflow ) !

I started up my server, and I'm getting this :

```<code>Started GET "/demo/hello" for 127.0.0.1 at Tue Jan 18 16:42:42 -0500 2011

ArgumentError (syntax error on line 15, col 2: `  socket: /tmp/mysql.sock'):
</code>```

My database.yml

```<code>socket: /tmp/mysql.sock
</code>```

Those match.. so I checked my sockets in mysql..

```<code>    mysql> show variables like 'socket';
    +---------------+-----------------+
    | Variable_name | Value           |
    +---------------+-----------------+
    | socket        | /tmp/mysql.sock |
    +---------------+-----------------+
    1 row in set (0.00 sec)
</code>```

So it's the right sockets...maybe its permissions?

```<code>mysql -u root -ppassword -h localhost my_database
</code>```

Logs in, no problems.

I'm using the following:

mysql -v = 5.1.54
rails -v = 3.0.3
ruby -v = 1.8.7

Stumped! Any ideas what I may be missing?

答: This means there is a yaml syntax error. Usually it's a stray tab (make sure you don't have any tabs in that area of the yaml file -- delete all the whitespace and enter spaces just to be sure). If that's not the problem, it could be antoher syntax issue (if so, please paste your whole yaml file -- masking any sensitive information of course).</p>

Body:
Hello World ( stackoverflow ) !

I started up my server, and I'm getting this :

Started GET "/demo/hello" for 127.0.0.1 at Tue Jan 18 16:42:42 -0500 2011

ArgumentError (syntax error on line 15, col 2: `  socket: /tmp/mysql.sock'):

My database.yml

socket: /tmp/mysql.sock

Those match.. so I checked my sockets in mysql..

    mysql> show variables like 'socket';
    +---------------+-----------------+
    | Variable_name | Value           |
    +---------------+-----------------+
    | socket        | /tmp/mysql.sock |
    +---------------+-----------------+
    1 row in set (0.00 sec)

So it's the right sockets...maybe its permissions?

mysql -u root -ppassword -h localhost my_database

Logs in, no problems.

I'm using the following:

mysql -v = 5.1.54
rails -v = 3.0.3
ruby -v = 1.8.7

Stumped! Any ideas what I may be missing?


问:
the procedure entry point __gxx_personality_v0 could not be located
Editor's Note: Error messages similar to "The procedure error point _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEC1EPKcRKS3_ could not be located in the dynamic link library libstdc++-6.dll" have the same cause and the same solutions apply.

I keep getting this error if I want to run my Irrlicht C++ Console Application in Windows:

the procedure entry point __gxx_personality_v0 could not be located in the dynamic link library libstdc++-6.dll

I am using CodeBlocks v12.11 with MinGW and the Irrlicht v1.8 engine. I set it up correctly. On my computer there is also a Qt installed with MinGW. Is it possible that there is a conflict?

This is the source code:

```<code>#include <irrlicht.h>

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

int main() {
    IrrlichtDevice *device = createDevice( video::EDT_OPENGL);

    if (!device)
        return 1;

    IVideoDriver* driver = device->getVideoDriver();
    ISceneManager* smgr = device->getSceneManager();
    IGUIEnvironment* guienv = device->getGUIEnvironment();

    guienv->addStaticText(L"Hello World", core::recti(10, 10, 100, 30));
    device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");

    while(device->run()) {
        driver->beginScene(true, true, SColor(250, 190, 1, 2));
        smgr->drawAll();
        guienv->drawAll();
        driver->endScene();
    }

    device->drop();
    return 0;
}
</code>```

I configured the Compiler to C:\CodeBlocks\MinGW.
Every file (there are some shown in the Settings) is located under bin, except make.exe. Is that normal?

The Auto-detect button also suggests the path above.

答:
These errors are caused by mismatched DLLs.

For the messages in the question it is an incorrect version of libstdc++-6.dll , but you can see the message referring to other DLLs that were built with various versions of gcc for Windows; and even mentioning the .exe file being run.

The specific changes here are:

basic_string|char_traits... - for C++11 there was a breaking ABI change to std::string

__gxx_personality_v0 - I believe this has to do with which exception implementation is in use (gcc for Windows can use various of Dwarf2, Win32-SEH, SJLJ etc.)

You will see this message if an application compiled by one flavour of compiler links to a DLL compiled by a different flavour.

To see a list of found DLLs for an executable, you can open the executable in Dependency Walker and enable the "Full Paths" option. Another way is to use ldd if you have Cygwin or similar installed.

The most usual culprit is libstdc++-6.dll. Unfortunately the ABI change wasn't coupled with a change in version number of libstdc++; and it's not the default behaviour for the exception mode to appear in the filename.  (You can change these things if building MinGW yourself).

I would recommend checking every DLL found by Dependency Walker and making sure it finds the ones from the same build of MinGW that you built your executable with. libgcc-s-*.dll is another one to look out for.

In fact I would recommend not having any of these DLLs on the system path. For development I load a PATH to the DLLs for the same compiler I'm compiling with; and for deployment I bundle the DLLs in the same directory as each executable,  because the runtime DLL search always checks that directory first. Then there is no chance of finding an old DLL that happens to be on a system search path.

(Update 2019 These days I tend to use static linking, because deploying a larger file is less of a problem than getting stuck in DLL-hell).

See also:

What is __gxx_personality_v0 for?

Another suggestion to fix the problem is to use static linking so that your binary does not depend on these DLLs in the first place.

Body:
Editor's Note: Error messages similar to "The procedure error point _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEC1EPKcRKS3_ could not be located in the dynamic link library libstdc++-6.dll" have the same cause and the same solutions apply.

I keep getting this error if I want to run my Irrlicht C++ Console Application in Windows:

the procedure entry point __gxx_personality_v0 could not be located in the dynamic link library libstdc++-6.dll

I am using CodeBlocks v12.11 with MinGW and the Irrlicht v1.8 engine. I set it up correctly. On my computer there is also a Qt installed with MinGW. Is it possible that there is a conflict?

This is the source code:

#include <irrlicht.h>

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

int main() {
    IrrlichtDevice *device = createDevice( video::EDT_OPENGL);

    if (!device)
        return 1;

    IVideoDriver* driver = device->getVideoDriver();
    ISceneManager* smgr = device->getSceneManager();
    IGUIEnvironment* guienv = device->getGUIEnvironment();

    guienv->addStaticText(L"Hello World", core::recti(10, 10, 100, 30));
    device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");

    while(device->run()) {
        driver->beginScene(true, true, SColor(250, 190, 1, 2));
        smgr->drawAll();
        guienv->drawAll();
        driver->endScene();
    }

    device->drop();
    return 0;
}

I configured the Compiler to C:\CodeBlocks\MinGW.
Every file (there are some shown in the Settings) is located under bin, except make.exe. Is that normal?

The Auto-detect button also suggests the path above.

ContentLicense: CC BY-SA 4.0