问:
Why can't a class member's name be the same as one of its nested classes?
Or why is the following impossible:

```<code>class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}
</code>```

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

答:
My answer approaches the question from a slightly different perspective, compared to the other questions. Of the following two statements in a C# language specification:

```<code>The same identifier may not be used in different definitions within one scope
</code>```

and

```<code>The same identifier may not be used in different definitions within one scope, unless it is probably impossible for any ambiguity to arise when the identifier is used
</code>```

, the first is much simpler.

Simplicity is a key goal in language design, because simpler languages are easier for compiler and interpreter authors to implement, easier for tools to generate and manipulate, easier for beginners to learn, and easier for programmers to understand. When considering any language feature, the complexity that that feature adds to the language should be considered as a negative, and must therefore be balanced by an at least equal measure of usefulness. As you stated yourself, allowing this would add no real functionality (as it is so easy to work around), so there was no compelling reason to further complicate the C# spec by including it.

Body:
Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

Body:
My answer approaches the question from a slightly different perspective, compared to the other questions. Of the following two statements in a C# language specification:

The same identifier may not be used in different definitions within one scope

and

The same identifier may not be used in different definitions within one scope, unless it is probably impossible for any ambiguity to arise when the identifier is used

, the first is much simpler.

Simplicity is a key goal in language design, because simpler languages are easier for compiler and interpreter authors to implement, easier for tools to generate and manipulate, easier for beginners to learn, and easier for programmers to understand. When considering any language feature, the complexity that that feature adds to the language should be considered as a negative, and must therefore be balanced by an at least equal measure of usefulness. As you stated yourself, allowing this would add no real functionality (as it is so easy to work around), so there was no compelling reason to further complicate the C# spec by including it.


来源: stackexchange

问:
Joining 2 large relations in Rascal
I'm trying to join two relations in Rascal, much like a SQL join, with the following code:

```<code>rel[loc,loc,loc] methodInvocationsWithClass = {arround 40000 tuples};
rel[loc,loc] declaredClassHierarchy = {around 20000 tuples};

{ <from,to,class,super> | <from,to,class> <- methodInvocationsWithClass, <sub,super> <- declaredClassHierarchy, class == sub };
</code>```

While this does exactly what I need it appears it only works well on small relations and doesn't scale well.

Is there perhaps a more efficient alternative way to accomplish this?

答: Indeed, we have the join keyword for this. Also lots of other useful relational operations are supported. Either by keywords or functions inside the Relation module.</p>

ContentLicense: CC BY-SA 3.0

Title: Joining 2 large relations in Rascal

Body:
I'm trying to join two relations in Rascal, much like a SQL join, with the following code:

rel[loc,loc,loc] methodInvocationsWithClass = {arround 40000 tuples};
rel[loc,loc] declaredClassHierarchy = {around 20000 tuples};

{ <from,to,class,super> | <from,to,class> <- methodInvocationsWithClass,  <- declaredClassHierarchy, class == sub };

While this does exactly what I need it appears it only works well on small relations and doesn't scale well.

Is there perhaps a more efficient alternative way to accomplish this?


问:
Select non empty elements of list in Python
Given:

```<code>a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)
</code>```

How can I get a string using all the non empty elements of the list ?

Desired output:

```<code>'aaa,ccc,eee'
</code>```

答:
The shortest thing you can do is

```<code>','.join(filter(None, mytuple))
</code>```

(I renamed list to mytuple in oder to not shadow the builtin list.)

Body:
Given:

a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)

How can I get a string using all the non empty elements of the list ?

Desired output:

'aaa,ccc,eee'

Body:
The shortest thing you can do is

','.join(filter(None, mytuple))

(I renamed list to mytuple in oder to not shadow the builtin list.)


问:
Logging into macos from linux and exporting display
I'm running macos sierra and for some reason I can't get the following to work on sierra.

I want to ssh in to my macos machine from a linux desktop, export my display back, and run either chrome or safari on my linux display.

I have xquartz installed and sshd_config set up correctly. I successfully get a DISPLAY variable set which proves xauth is working, however, when I launch Chrome or Safari it is displayed on the macos desktop.

I've had this working on every version of macos until sierra.

Thanks for any help

答:
You don't need to have xquartz installed for this direction of X forwarding. What you need however are applications that use the X protocol for displaying themselves. Your Mac's Chrome or Safari do not use it.

Mac does not use X server, and has its own API for dealing with windows and rendering on screen. Most applications you have installed (including Chrome and Safari) are using this API and know nothing about X11 and will ignore the DISPLAY variable. Only some special applications (typically those ported from Linux) use X11 on Mac and those render using xqartz (for example xterm or inkscape). Those are the only applications for which you can use X forwarding from Mac to Linux.

I doubt there is a working build of Chrome/Chromium for Mac that uses X11 and I am certain there is not one of Safari. I would recommend using VNC to get remote desktop from Mac to Linux.


问:
Bandpass FIR filter labview
I am trying to make a bandpass FIR filter in Labview. I have created two sine waves (one with freq = 1Hz, amplitude = 1 and the second with freq=50, amplitude = 0.1) that I added together.

And now I want to create a bandpass filter to filter out the 50Hz signal (I know that its possible use just low pass filter, but I need to use bandpass filter). I set the low cutoff freq to 0.01 and high cutoff freq to 3, but the result is witout any change.

On top of that when I change the parameters I get no change.

When I use the butterworth filter I get the result that I am looking for.

This is my code:

What am I missing?

答:
You say you need to use a Bandpass filter, but in your VI you are using a Bandstop filter. Not sure which of the two is the error. Just as a recap:

Lowpass filter passes anything below the set freq.

Highpass filter passes anything above the set freq.

Bandpass filter passes anything between the set freq.

Bandstop filter passes everything except the part between the set
freq.

The Butterworth part has nothing to do with high, low  or bandpass but with how fast the fall-off is after the set frequency.

See the image for a working vi and results.

Hope this helps.

Title: Bandpass FIR filter labview


问:
Reliably tracking changes made by Hibernate
I'm using a PostUpdateEventListener registered via

```<code>registry.appendListeners(EventType.POST_COMMIT_UPDATE, listener)
</code>```

and a few other listeners in order to track changes made by Hibernate. This works perfectly, however, I see a problem there:

Let's say, for tracking some amount by id, I simply execute

```<code> amountByIdConcurrentMap.put(id, amount);
</code>```

on every POST_COMMIT_UPDATE (let's ignore other operations). The problem is that this call happens some time after the commit. So with two commits  writing the same entity shortly one after the other, I can receive the events in the wrong order, ending up with the older amount stored.

Is this really possible or are the operations synchronized somehow?

Is there a way how to prevent or at least detect such situation?

答:
No, there are no ordering guarantees, so you'll have to take care to ensure proper synchronization manually.

If the real problem you are solving is caching of entity state and if it is suitable to use second-level cache for the entity in question, then you would get everything out of the box by enabling the L2 cache.

Otherwise, instead of updating the map from the update listeners directly, you could submit tasks to an Executor or messaging system that would asynchronously start a new transaction and select for update the amount for the given id from the database. Then update the map in the same transaction while holding the corresponding row lock in the db, so that map updates for the same id are done serially.

Body:
I'm using a PostUpdateEventListener registered via

registry.appendListeners(EventType.POST_COMMIT_UPDATE, listener)

and a few other listeners in order to track changes made by Hibernate. This works perfectly, however, I see a problem there:

Let's say, for tracking some amount by id, I simply execute

 amountByIdConcurrentMap.put(id, amount);

on every POST_COMMIT_UPDATE (let's ignore other operations). The problem is that this call happens some time after the commit. So with two commits  writing the same entity shortly one after the other, I can receive the events in the wrong order, ending up with the older amount stored.

Is this really possible or are the operations synchronized somehow?

Is there a way how to prevent or at least detect such situation?


问:
Adding new datasources to an existing .rrd
I have a .rrd db which is collecting data from a temperature gauge. Now I have a second gauge so I'd like to add this new gauge to the existing .rrd database. I tried many times with the "rrdtool tune" command, but after that I run a "rrdtool info" on my database, and I see that there's not the last data source (another gauge) that I tried to insert.

How can I do this?

答:
I just checked, and I see I'm using RRDTOOL 1.4 so I would not have problems. Anyway, the fact is that I used this command:

```<code>/usr/bin/rrdtool tune TEMPCucina.rrd DS:METEOTEMPEXT:GAUGE:1200:U:U RRA:AVERAGE:0.5:1:180000
</code>```

I got this back from the computer:

```<code>DS[TEMPCucina] typ: GAUGE   hbt: 1200   min: nan    max: nan
</code>```

But it seems that I'm not able to write into TEMPCucina.rrd
And if I try to perform the following command:

```<code>rrdtool info TEMPCucina.rrd
</code>```

I just get the following, and it seems that no new gauge has been created

```<code>filename = "TEMPCucina.rrd"
rrd_version = "0003"
step = 60
last_update = 1510780261
header_size = 556
ds[TEMPCucina].index = 0
ds[TEMPCucina].type = "GAUGE"
ds[TEMPCucina].minimal_heartbeat = 1200
ds[TEMPCucina].min = NaN
ds[TEMPCucina].max = NaN
ds[TEMPCucina].last_ds = "18"
ds[TEMPCucina].value = 1,8000000000e+01
ds[TEMPCucina].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].rows = 30000
rra[0].cur_row = 1304
rra[0].pdp_per_row = 1
rra[0].xff = 0,0000000000e+00
rra[0].cdp_prep[0].value = NaN
rra[0].cdp_prep[0].unknown_datapoints = 0
</code>```

(when I try to write I get this, but I don't know how to proceed at this point)

```<code>ERROR: TEMPCucina.rrd: illegal attempt to update using time 1510780527 when last update time is 1510780527 (minimum one second step)
</code>```

Body:
I just checked, and I see I'm using RRDTOOL 1.4 so I would not have problems. Anyway, the fact is that I used this command:

/usr/bin/rrdtool tune TEMPCucina.rrd DS:METEOTEMPEXT:GAUGE:1200:U:U RRA:AVERAGE:0.5:1:180000

I got this back from the computer:

DS[TEMPCucina] typ: GAUGE   hbt: 1200   min: nan    max: nan

But it seems that I'm not able to write into TEMPCucina.rrd
And if I try to perform the following command:

rrdtool info TEMPCucina.rrd

I just get the following, and it seems that no new gauge has been created

filename = "TEMPCucina.rrd"
rrd_version = "0003"
step = 60
last_update = 1510780261
header_size = 556
ds[TEMPCucina].index = 0
ds[TEMPCucina].type = "GAUGE"
ds[TEMPCucina].minimal_heartbeat = 1200
ds[TEMPCucina].min = NaN
ds[TEMPCucina].max = NaN
ds[TEMPCucina].last_ds = "18"
ds[TEMPCucina].value = 1,8000000000e+01
ds[TEMPCucina].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].rows = 30000
rra[0].cur_row = 1304
rra[0].pdp_per_row = 1
rra[0].xff = 0,0000000000e+00
rra[0].cdp_prep[0].value = NaN
rra[0].cdp_prep[0].unknown_datapoints = 0

(when I try to write I get this, but I don't know how to proceed at this point)

ERROR: TEMPCucina.rrd: illegal attempt to update using time 1510780527 when last update time is 1510780527 (minimum one second step)


问:
node.js asynchronous callbacks with async
All, I am struggling mightily with asynchronous callbacks in node.js. I am trying to make two HTTP requests and show the returned data from both at the end in separate variables. I am trying to use npm-async, but am failing setting it up properly.

Any help or suggestions would be greatly appreciated.

Here is my code:

```<code>// MODULES - INCLUDES
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var async = require('async');

// FORM - DATA COLLECTION
var cucmpub = 'xxxx';
var cucmversion = 'xxxx';
var username = 'xxxx';
var password = 'xxxx';

// 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:listRoutePartition 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);

async.series([
    function (callback) {

        // 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'];
                    callback(err, cssx);
                    // console.log(cssx);
                    // console.log(spacer);
                });
            });
        });

        // SOAP - SEND AXL CALL - CSS
        soapRequest.write(soapBody);
        soapRequest.end();
    },
    function (callback) {
        // 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', () => {
                console.log(soapreplyp);

                // EDIT - SCRUB XML OUTPUT
                var rmline1p = soapreplyp.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:listRoutePartition\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:listRoutePartition>/g, '');
                console.log(xmlscrubbedp);
                console.log(spacer);

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

    function (err, results) {
        console.log(cssx);
        console.log(partitionsx);
    }
]);
</code>```

-----UPDATE 1-----

Ok, I've updated my code; and I think I've got it! Thank you to the both of you for helping me through this! Alright, so this isn't exactly what you recommended @Chris Phillips. I was hoping to be able to display results separately instead of all combined. I looked up chaining Promises together and found this article: How to chain and share prior results with Promises. That mentioned how to "Nest, so all Previous Results Can Be Accessed". That did the trick for me.

Also, once I got my head wrapped around the request-promise framework, that was really easy and looks a lot better than the regular http.request framework.

Here is the new code!

```<code>// MODULES - INCLUDES
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var rp = require('request-promise');

// FORM - DATA COLLECTION
var cucmpub = 'xxxx';
var cucmversion = 'xxxx';
var username = 'xxxx';
var password = 'xxxx';

// JS - VARIABLE DEFINITION - GLOBAL
var authentication = username + ":" + password;
var cssx = null;
var partitionsx = null;
var spacer = '-----';

// CSS - JS - VARIABLE DEFINITION
var cssrmline1 = '';
var cssrmline2 = '';
var cssrmline3 = '';
var cssrmline4 = '';
var cssrmbottomup1 = '';
var cssrmbottomup2 = '';

// CSS - SOAP - AXL REQUEST
var cssaxlrequest = 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>');

// CSS - HTTP - REQUEST BUILD
var csshttprequest = {
    method: 'POST',
    uri: 'https://' + cucmpub + ':8443/axl/',
    rejectUnauthorized: false,
    headers: {
        'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
        'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
        'Content-Type': 'text/xml; charset=utf-8',
    },
    body: cssaxlrequest,
};

// PARTITIONS - JS - VARIABLE DEFINITION
var partitionsrmline1 = '';
var partitionsrmline2 = '';
var partitionsrmline3 = '';
var partitionsrmline4 = '';
var partitionsrmbottomup1 = '';

// PARTITIONS - SOAP - AXL REQUEST
var partitionsaxlrequest = 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:listRoutePartition sequence="?">' +
    '<searchCriteria>' +
    '<name>%</name>' +
    '</searchCriteria>' +
    '<returnedTags uuid="?">' +
    '<name>?</name>' +
    '</returnedTags>' +
    '</ns:listRoutePartition>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>');

// PARTITIONS - HTTP - REQUEST BUILD
var partitionshttprequest = {
    method: 'POST',
    uri: 'https://' + cucmpub + ':8443/axl/',
    rejectUnauthorized: false,
    headers: {
        'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listRoutePartition',
        'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
        'Content-Type': 'text/xml; charset=utf-8',
    },
    body: partitionsaxlrequest,
};

// CHAINED REQUESTS + OUTPUT
rp(csshttprequest)
    .then(function (resultcss) {
        var cssrmline1 = resultcss.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
        var cssrmline2 = cssrmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
        var cssrmline3 = cssrmline2.replace(/<soapenv:Body>/g, '');
        var cssrmline4 = cssrmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
        var cssrmbottomup1 = cssrmline4.replace(/<\/soapenv:Envelope>/g, '');
        var cssrmbottomup2 = cssrmbottomup1.replace(/<\/soapenv:Body>/g, '');
        var cssxmlscrubbed = cssrmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
        parser.parseString(cssxmlscrubbed, function (err, result) {
            var cssx = result['return']['css'];
            // console.log(cssx);
            // console.log(spacer);
            return rp(partitionshttprequest)
                .then(function (resultpartitions) {
                    var partitionsrmline1 = resultpartitions.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                    var partitionsrmline2 = partitionsrmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                    var partitionsrmline3 = partitionsrmline2.replace(/<soapenv:Body>/g, '');
                    var partitionsrmline4 = partitionsrmline3.replace(/<ns:listRoutePartitionResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                    var partitionsrmbottomup1 = partitionsrmline4.replace(/<\/soapenv:Envelope>/g, '');
                    var partitionsrmbottomup2 = partitionsrmbottomup1.replace(/<\/soapenv:Body>/g, '');
                    var partitionsxmlscrubbed = partitionsrmbottomup2.replace(/<\/ns:listRoutePartitionResponse>/g, '');
                    parser.parseString(partitionsxmlscrubbed, function (err, result) {
                        var partitionsx = result['return']['routePartition'];
                        console.log(cssx);
                        console.log(spacer);
                        console.log(partitionsx);
                    });
                })
        });
    })
</code>```

答:
Well you can use the request-promise library to make the http calls instead so it would be come something like (a bit rough, error handling omitted)

```<code>const request = require("request-promise");

const options1 = {
 //.. set URL, headers etc
};

request(options1).then ( body => {

   // do processing for request 1
   return [results1];
}).then( results => {
    return request(options2).then ( body => {
      //do processing for request 2
      results.push(results2);
      return results;
   });

})
.then((results) => {
});
</code>```

If you are using Node 8.x or greater you can use async/await to do something like

```<code>let resp1 = await request(options1);

//process resp1

let resp2 = await request(options2);

// process resp2

let results = [resp1, resp2];
</code>```

I would recommend moving all your request making code into a function so you can more easily re-use it.

Body:
All, I am struggling mightily with asynchronous callbacks in node.js. I am trying to make two HTTP requests and show the returned data from both at the end in separate variables. I am trying to use npm-async, but am failing setting it up properly.

Any help or suggestions would be greatly appreciated.

Here is my code:

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

// FORM - DATA COLLECTION
var cucmpub = 'xxxx';
var cucmversion = 'xxxx';
var username = 'xxxx';
var password = 'xxxx';

// 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:listRoutePartition 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);

async.series([
    function (callback) {

        // 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'];
                    callback(err, cssx);
                    // console.log(cssx);
                    // console.log(spacer);
                });
            });
        });

        // SOAP - SEND AXL CALL - CSS
        soapRequest.write(soapBody);
        soapRequest.end();
    },
    function (callback) {
        // 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', () => {
                console.log(soapreplyp);

                // EDIT - SCRUB XML OUTPUT
                var rmline1p = soapreplyp.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:listRoutePartition\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:listRoutePartition>/g, '');
                console.log(xmlscrubbedp);
                console.log(spacer);

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

    function (err, results) {
        console.log(cssx);
        console.log(partitionsx);
    }
]);

-----UPDATE 1-----

Ok, I've updated my code; and I think I've got it! Thank you to the both of you for helping me through this! Alright, so this isn't exactly what you recommended @Chris Phillips. I was hoping to be able to display results separately instead of all combined. I looked up chaining Promises together and found this article: How to chain and share prior results with Promises. That mentioned how to "Nest, so all Previous Results Can Be Accessed". That did the trick for me.

Also, once I got my head wrapped around the request-promise framework, that was really easy and looks a lot better than the regular http.request framework.

Here is the new code!

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

// FORM - DATA COLLECTION
var cucmpub = 'xxxx';
var cucmversion = 'xxxx';
var username = 'xxxx';
var password = 'xxxx';

// JS - VARIABLE DEFINITION - GLOBAL
var authentication = username + ":" + password;
var cssx = null;
var partitionsx = null;
var spacer = '-----';

// CSS - JS - VARIABLE DEFINITION
var cssrmline1 = '';
var cssrmline2 = '';
var cssrmline3 = '';
var cssrmline4 = '';
var cssrmbottomup1 = '';
var cssrmbottomup2 = '';

// CSS - SOAP - AXL REQUEST
var cssaxlrequest = 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>');

// CSS - HTTP - REQUEST BUILD
var csshttprequest = {
    method: 'POST',
    uri: 'https://' + cucmpub + ':8443/axl/',
    rejectUnauthorized: false,
    headers: {
        'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
        'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
        'Content-Type': 'text/xml; charset=utf-8',
    },
    body: cssaxlrequest,
};

// PARTITIONS - JS - VARIABLE DEFINITION
var partitionsrmline1 = '';
var partitionsrmline2 = '';
var partitionsrmline3 = '';
var partitionsrmline4 = '';
var partitionsrmbottomup1 = '';

// PARTITIONS - SOAP - AXL REQUEST
var partitionsaxlrequest = 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:listRoutePartition sequence="?">' +
    '<searchCriteria>' +
    '<name>%</name>' +
    '</searchCriteria>' +
    '<returnedTags uuid="?">' +
    '<name>?</name>' +
    '</returnedTags>' +
    '</ns:listRoutePartition>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>');

// PARTITIONS - HTTP - REQUEST BUILD
var partitionshttprequest = {
    method: 'POST',
    uri: 'https://' + cucmpub + ':8443/axl/',
    rejectUnauthorized: false,
    headers: {
        'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listRoutePartition',
        'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
        'Content-Type': 'text/xml; charset=utf-8',
    },
    body: partitionsaxlrequest,
};

// CHAINED REQUESTS + OUTPUT
rp(csshttprequest)
    .then(function (resultcss) {
        var cssrmline1 = resultcss.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
        var cssrmline2 = cssrmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
        var cssrmline3 = cssrmline2.replace(/<soapenv:Body>/g, '');
        var cssrmline4 = cssrmline3.replace(/<ns:listCssResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
        var cssrmbottomup1 = cssrmline4.replace(/<\/soapenv:Envelope>/g, '');
        var cssrmbottomup2 = cssrmbottomup1.replace(/<\/soapenv:Body>/g, '');
        var cssxmlscrubbed = cssrmbottomup2.replace(/<\/ns:listCssResponse>/g, '');
        parser.parseString(cssxmlscrubbed, function (err, result) {
            var cssx = result['return']['css'];
            // console.log(cssx);
            // console.log(spacer);
            return rp(partitionshttprequest)
                .then(function (resultpartitions) {
                    var partitionsrmline1 = resultpartitions.replace(/<\?xml\sversion='1\.0'\sencoding='utf-8'\?>/g, '');
                    var partitionsrmline2 = partitionsrmline1.replace(/<soapenv:Envelope\sxmlns:soapenv="http:\/\/schemas.xmlsoap.org\/soap\/envelope\/">/g, '');
                    var partitionsrmline3 = partitionsrmline2.replace(/<soapenv:Body>/g, '');
                    var partitionsrmline4 = partitionsrmline3.replace(/<ns:listRoutePartitionResponse\sxmlns:ns="http:\/\/www\.cisco\.com\/AXL\/API\/[0-9]*\.[0-9]">/g, '');
                    var partitionsrmbottomup1 = partitionsrmline4.replace(/<\/soapenv:Envelope>/g, '');
                    var partitionsrmbottomup2 = partitionsrmbottomup1.replace(/<\/soapenv:Body>/g, '');
                    var partitionsxmlscrubbed = partitionsrmbottomup2.replace(/<\/ns:listRoutePartitionResponse>/g, '');
                    parser.parseString(partitionsxmlscrubbed, function (err, result) {
                        var partitionsx = result['return']['routePartition'];
                        console.log(cssx);
                        console.log(spacer);
                        console.log(partitionsx);
                    });
                })
        });
    })

Body:
Well you can use the request-promise library to make the http calls instead so it would be come something like (a bit rough, error handling omitted)

const request = require("request-promise");

const options1 = {
 //.. set URL, headers etc
};

request(options1).then ( body => {

   // do processing for request 1
   return [results1];
}).then( results => {
    return request(options2).then ( body => {
      //do processing for request 2
      results.push(results2);
      return results;
   });

})
.then((results) => {
});

If you are using Node 8.x or greater you can use async/await to do something like

let resp1 = await request(options1);

//process resp1

let resp2 = await request(options2);

// process resp2

let results = [resp1, resp2];

I would recommend moving all your request making code into a function so you can more easily re-use it.


问:
CSV not importing to django models
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')
</code>```

models.py:

```<code>from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject
</code>```

views.py:

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")
</code>```

答:
I ended up re-writing the script and it worked. I think my strange looping structure caused the script to not work as intended (or at all, really). I also used bulk_create instead of having to call save after every row to make the process more efficient. Here's the version that works:

views.py:

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import os
import csv, sys

def import_data(request):

    # Opens all csv files in specified directory

    directory = os.path.join('Some Target Directory')
    count = 0
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(".csv"):
                file_path = os.path.join(root, filename)
                with open(file_path) as f:
                     reader = csv.reader(f)

                    #Checks the rows/columns and tries to find the specified string that marks the start of data

                    for i, row in enumerate(reader):
                        target_string = "Some Target String"
                        if target_string in row:

                        #Skips to the next line (where the data starts) when the target string is found

                            true_target_row = next(reader)
                            for row in reader:

                                #Counter tells you which file number is importing.

                                print "importing file number %d" %(count)

                                #Creates a bunch of objects

                                objects = [
                                    Data(
                                        SomeObject = row [n],
                                        ...
                                        ...
                                )
                                for row in reader if row[0] != "Some Target End String"
                            ]

                            # Does a bulk_create after the file is completed

                            Data.objects.bulk_create(objects)
                            count += 1

            # Prints something if the file isn't a csv file

            else:
                print "This isn't a csv file"

    print "Imported %d files! All done!" %(count)

    return render(request, "Data/DataLandingPage.html")
</code>```

Title: CSV not importing to django models

Body:
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')

models.py:

from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject

views.py:

from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")

Body:
I ended up re-writing the script and it worked. I think my strange looping structure caused the script to not work as intended (or at all, really). I also used bulk_create instead of having to call save after every row to make the process more efficient. Here's the version that works:

views.py:

from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import os
import csv, sys

def import_data(request):

    # Opens all csv files in specified directory

    directory = os.path.join('Some Target Directory')
    count = 0
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(".csv"):
                file_path = os.path.join(root, filename)
                with open(file_path) as f:
                     reader = csv.reader(f)

                    #Checks the rows/columns and tries to find the specified string that marks the start of data

                    for i, row in enumerate(reader):
                        target_string = "Some Target String"
                        if target_string in row:

                        #Skips to the next line (where the data starts) when the target string is found

                            true_target_row = next(reader)
                            for row in reader:

                                #Counter tells you which file number is importing.

                                print "importing file number %d" %(count)

                                #Creates a bunch of objects

                                objects = [
                                    Data(
                                        SomeObject = row [n],
                                        ...
                                        ...
                                )
                                for row in reader if row[0] != "Some Target End String"
                            ]

                            # Does a bulk_create after the file is completed

                            Data.objects.bulk_create(objects)
                            count += 1

            # Prints something if the file isn't a csv file

            else:
                print "This isn't a csv file"

    print "Imported %d files! All done!" %(count)

    return render(request, "Data/DataLandingPage.html")


问:
SqlAlchemy query result outputting
I am trying to query one of my tables in my Postgres database using SqlAlchemy in Python 3. It runs the query fine but as I go through each row in the result that SqlAlchemy returns, I try to use the attribute 'text' (one of my column names). I receive this error:

```<code>'str' object has no attribute 'text'
</code>```

I have printed the attribute like so:

```<code>for row in result:
   print(row.text)
</code>```

This does not give the error. The code that produces the error is below. However, to give my environment:

I have two servers running. One is for my database the other is for my python server.

Database Server:

Postgres v9.6 - On Amazon's RDS

Server with Python

Linux 3.13.0-65-generic x86_64 - On an Amazon EC2 Instance

SqlAlchemy v1.1.5

Python v3.4.3

Flask 0.11.1

Files related:

```<code>import sqlalchemy as sa
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
import re
from nltk import sent_tokenize

class DocumentProcess:
  def __init__(self):
    ...
    Engine = sa.create_engine(
        CONFIG.POSTGRES_URL,
        client_encoding='utf8',
        pool_size=20,
        max_overflow=0
    )

    # initialize SQLAlchemy
    Base = automap_base()

    # reflect the tables
    Base.prepare(Engine, reflect=True)

    # Define all needed tables
    self.Document = Base.classes.documents

    self.session = Session(Engine)
    ...

  def process_documents(self):
    try:
        offset = 5
        limit = 50
        ###### This is the query in question ##########
        result = self.session.query(self.Document) \
            .order_by(self.Document.id) \
            .offset(offset) \
            .limit(limit)
        for row in result:
          # The print statement below does print out the text
          print(row.text)
          # when passing document.text to sent_tokenize, it
          # gives the following error:
          # 'str' object has no attribute 'text'
          snippets = sent_tokenize(row.text.strip('\n')) # I have removed strip, but the same problem
    except Exception as e:
        logging.info(format(e))
        raise e
</code>```

This is my model for Document, in my PostgreSQL database:

```<code>class Document(db.Model):
    __tablename__ = "documents"

    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text)
    tweet = db.Column(db.JSON)
    keywords = db.Column(db.ARRAY(db.String), nullable=True)

    def to_dict(self):
        return dict(
            id=self.id,
            text=self.text,
            tweet=self.tweet,
            keywords=self.keywords
        )

    def json(self):
        return jsonify(self.to_dict())

    def __repr__(self):
        return "<%s %r>" % (self.__class__, self.to_dict())
</code>```

Things I have tried

Before, I did not have order_by in the Document query. This was working before. However, even removing order_by does not fix it anymore.

Used a SELECT statement and went through the result manually, but still the same result

What I haven't tried

I am wondering if its because I named the column 'text'. I noticed that when I write this query out in postgres, it highlights it as a reserved word. I'm confused why my query worked before, but now it doesn't work. Could this be the issue?

Any thoughts on this issue would be much appreciated.

答: You are likely to get this error in PostgreSQL if you are creating a foreign table and one of the column datatype is text. Change it to character varying() and the error disappears!

Title: SqlAlchemy query result outputting

Body:
I am trying to query one of my tables in my Postgres database using SqlAlchemy in Python 3. It runs the query fine but as I go through each row in the result that SqlAlchemy returns, I try to use the attribute 'text' (one of my column names). I receive this error:

'str' object has no attribute 'text'

I have printed the attribute like so:

for row in result:
   print(row.text)

This does not give the error. The code that produces the error is below. However, to give my environment:

I have two servers running. One is for my database the other is for my python server.

Database Server:

Postgres v9.6 - On Amazon's RDS

Server with Python

Linux 3.13.0-65-generic x86_64 - On an Amazon EC2 Instance

SqlAlchemy v1.1.5

Python v3.4.3

Flask 0.11.1

Files related:

import sqlalchemy as sa
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
import re
from nltk import sent_tokenize

class DocumentProcess:
  def __init__(self):
    ...
    Engine = sa.create_engine(
        CONFIG.POSTGRES_URL,
        client_encoding='utf8',
        pool_size=20,
        max_overflow=0
    )

    # initialize SQLAlchemy
    Base = automap_base()

    # reflect the tables
    Base.prepare(Engine, reflect=True)

    # Define all needed tables
    self.Document = Base.classes.documents

    self.session = Session(Engine)
    ...

  def process_documents(self):
    try:
        offset = 5
        limit = 50
        ###### This is the query in question ##########
        result = self.session.query(self.Document) \
            .order_by(self.Document.id) \
            .offset(offset) \
            .limit(limit)
        for row in result:
          # The print statement below does print out the text
          print(row.text)
          # when passing document.text to sent_tokenize, it
          # gives the following error:
          # 'str' object has no attribute 'text'
          snippets = sent_tokenize(row.text.strip('\n')) # I have removed strip, but the same problem
    except Exception as e:
        logging.info(format(e))
        raise e

This is my model for Document, in my PostgreSQL database:

class Document(db.Model):
    __tablename__ = "documents"

    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text)
    tweet = db.Column(db.JSON)
    keywords = db.Column(db.ARRAY(db.String), nullable=True)

    def to_dict(self):
        return dict(
            id=self.id,
            text=self.text,
            tweet=self.tweet,
            keywords=self.keywords
        )

    def json(self):
        return jsonify(self.to_dict())

    def __repr__(self):
        return "<%s %r>" % (self.__class__, self.to_dict())

Things I have tried

Before, I did not have order_by in the Document query. This was working before. However, even removing order_by does not fix it anymore.

Used a SELECT statement and went through the result manually, but still the same result

What I haven't tried

I am wondering if its because I named the column 'text'. I noticed that when I write this query out in postgres, it highlights it as a reserved word. I'm confused why my query worked before, but now it doesn't work. Could this be the issue?

Any thoughts on this issue would be much appreciated.


问:
Trying to use controllers in AngularJS
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

```<code>(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();
</code>```

This is my HTML for the first scenario:

```<code><div class="autocompletedemoFloatingLabel" ng-controller="DemoCtrl as ctrl" ng-app="MyApp" layout="column" ng-cloak="">
      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">
            <div layout-gt-sm="row">
            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                <span md-highlight-text="ctrl.searchText">{{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}</span>
              </md-item-template>
              <div ng-messages="searchForm.autocompleteField.$error" ng-if="searchForm.autocompleteField.$touched">
                <div ng-message="required">You <b>must</b> have a favorite movie.</div>
                <div ng-message="minlength">Your entry is not long enough.</div>
                <div ng-message="maxlength">Your entry is too long.</div>
              </div>
            </md-autocomplete>
          </input>
          </div>
    </form>
  </md-content>
</div>
</code>```

Now the application currently contains controller in this format:

```<code>var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});
</code>```

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

答:
This worked:</p>

```<code><script>
var app = angular.module("MyApp");
app.controller("DemoCtrl", function ($http) {
    this.querySearch = function (query)
    {
          return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
          return result.data;
        });
    }
});
</script>
</code>```

Title: Trying to use controllers in AngularJS

Body:
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();

This is my HTML for the first scenario:

      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">

            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                {{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}
              </md-item-template>

You must have a favorite movie.

Your entry is not long enough.

Your entry is too long.

            </md-autocomplete>
          </input>

    </form>
  </md-content>

Now the application currently contains controller in this format:

var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

Body:
This worked:

<script>
var app = angular.module("MyApp");
app.controller("DemoCtrl", function ($http) {
    this.querySearch = function (query)
    {
          return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
          return result.data;
        });
    }
});
</script>


问:
Chrome can't open localhost:3000 with Gulp / BrowserSync
For some reason, no matter what I try, Google Chrome never seems to be able to display http://localhost:3000 (or any other specified port number for that matter) when starting up a server with BrowserSync through Gulp.

Navigating to the same URI in Firefox, shows that it works and that BrowserSync is connected.

```<code>gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: './'
        },
        port: 8080
    });
});
</code>```

I'm specifying port 8080 above as an alternative, but even using the default 3000 does not work in Chrome. Firefox seems to be able to work with either.

I've been to: chrome://net-internals/#dns and cleared the host cache, restarted, etc. Nothing works.

In Chrome I simply get the message: ERR_CONNECTION_REFUSED

Any ideas? Thanks.

PS - Also works in Safari.

答:
Manually setting the browser property in the init function worked for me.

```<code>gulp.task('browserSync', () => {
        browserSync.init({
            server: {
                baseDir: task.dir.base,
                middleware: [
                    webpackDevMiddleware(bundler, {
                        publicPath: webpackConfig.output.publicPath,
                        stats: 'errors-only'
                    })
                  ]
            },
            browser: 'chrome'
        });
    });
</code>```

I'm running windows 10 x64

Body:
For some reason, no matter what I try, Google Chrome never seems to be able to display http://localhost:3000 (or any other specified port number for that matter) when starting up a server with BrowserSync through Gulp.

Navigating to the same URI in Firefox, shows that it works and that BrowserSync is connected.

gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: './'
        },
        port: 8080
    });
});

I'm specifying port 8080 above as an alternative, but even using the default 3000 does not work in Chrome. Firefox seems to be able to work with either.

I've been to: chrome://net-internals/#dns and cleared the host cache, restarted, etc. Nothing works.

In Chrome I simply get the message: ERR_CONNECTION_REFUSED

Any ideas? Thanks.

PS - Also works in Safari.

Body:
Manually setting the browser property in the init function worked for me.

gulp.task('browserSync', () => {
        browserSync.init({
            server: {
                baseDir: task.dir.base,
                middleware: [
                    webpackDevMiddleware(bundler, {
                        publicPath: webpackConfig.output.publicPath,
                        stats: 'errors-only'
                    })
                  ]
            },
            browser: 'chrome'
        });
    });

I'm running windows 10 x64


问:
splitting small amount of data over multiple vs a single index?
We are in the process of jumping from ES 2.3.2 to 6.0.  As part of this work, we are breaking up our monolithic index into multiple indexes.  The index we have is split into 23 shards, each of which is about 50 GB.  We are doing two things:

1) Split out our types (we have 26 types with widely varying fields) into individual indexes
2) Create date-based indexes

We are doing #1 as that as mapping types are being deprecated.

We are doing #2 as 80% of our queries are on data from just the last 30 days.  We do have queries that go back over all time.  Also, our data is mutable (any document from any date can be updated), so we are managing our index targeting in our api.

What I am dealing with now is that when we split this all out, for some of our larger types, this works really well.  For the smaller ones, we end up with indexes that, once split out by type and date, are very small (like ~100 mb).  I am concerned that for the small types, we will end up with 15 (we have a 15 month retention) indexes that are all small, making it inefficient for searching.  Is this really bad?  I did a test of collapsing the smaller ones and not having them date based, but I found performance actually went down. I am hyothesizing that this is because all the data was in one shard (I set it to one shard), and the search could not be parallelized.

My root question is to find out if there is a penalty for having a small amount of data spread over multiple indexes vs collocating it in one index?  We really need the date-based for our larger types, and managing a mix of date vs non-date-based is undesirable.

thanks,
~john

答: if you are able to get performance you need from time sliced indices. I'd go with that approach. A simple , indexing strategy is  better than having another system to manage number of indices based on size.</p>


问:
Added button successfully by using .innerHTML but can't access the button using its class name
```<code>    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}
</code>```

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?

答:
Hopefully this helps. I re-wrote the function

function displaMatches (matches) {

   var menu = document.querySelector('.menu')

   matches.forEach(match => {
    //Create/add objects in javascript
    $li = document.createElement('li');
    $btn = document.createElement('button');
    $btn.className = 'suggestion';
    $btn.append(match);
    $li.appendChild($btn)
    menu.appendChild($li);
   });

   var suggestion = document.querySelectorAll('.suggestion')//this should return array of buttons with the defined classname

   console.log('ppp', suggestion[0]);

 suggestion.forEach(match => {
  match.onclick = () => {
   console.log(match.textContent)
   searchText = match.textContent;
  };
 })

}```

Body:
    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?


问:
Algorithm to determine fundamental frequency from potential harmonics
I am attempting to extract a fundamental frequency from a sound source.   maybe someone is singing A3 into the microphone,  so I want to be detecting ~ 110Hz

my approach is:

FFT 1024 floats

use the phase of each bin to accurately determine its precise frequency

determine peaks (typically 50 or so)

order them with the loudest first

(Peak[0].power=1063.343750, .freq=2032.715088

(Peak[1].power=1047.764893, .freq=3070.605225

(Peak[2].power=1014.986877, .freq=5925.878418

(Peak[3].power=1011.707825, .freq=6963.769043

(Peak[4].power=1009.152954, .freq=4022.363037

(Peak[5].power=995.199585, .freq=4974.120605

(Peak[6].power=987.243713, .freq=8087.792480

(Peak[7].power=533.514832, .freq=908.691833

(MARKER1) start with the loudest, and match it against all remaining peaks,  so if I had N peaks, I will have at this point N-1 peak-pairs

examine each peak-pair for harmonicity; ie  how close is it to some fraction a/b, ie  can we find a/b with b<20  such that |peakA.freq/peakB.freq - a/b| < 0.01 (this would match harmonics up to the 20th one)

we now have a refined list of peaks that are considered harmonic with one another

Harmonic PeakPair: (0,1)=2/3, error:0.00468 => f0 @ 1019.946289

  Harmonic PeakPair: (0,2)=1/3, error:0.00969 => f0 @ 2004.003906

  Harmonic PeakPair: (0,3)=2/7, error:0.00618 => f0 @ 1005.590820

  Harmonic PeakPair: (0,4)=1/2, error:0.00535 => f0 @ 2021.948242

  Harmonic PeakPair: (0,5)=2/5, error:0.00866 => f0 @ 1005.590820

  Harmonic PeakPair: (0,6)=1/4, error:0.00133 => f0 @ 2027.331543

  Harmonic PeakPair: (0,7)=9/4, error:0.01303 => f0 @ 226.515106

My question is: how can I devise an algorithm that will correctly identify the above fundamental as ~1000Hz?

It is by no means guaranteed that there will be a higher concentration of values at ~1000 than at ~2000 or ~3000 etc.   it isn't even guaranteed that there will be any entry ~1000.   we could have ~5000 x  one entry, ~4000 x three entries, ~3000 x 2 entries,  and a couple of bogus values floating around,  like the 226  in the above list.

I guess I can repeat the procedure again, weeding out suggested fundamentals which are not 'harmonic' with the rest of the list.   this would at least get rid of the bogus values...

it may be that I'm not even asking the right question. Maybe this whole approach sucks. But I think it makes sense to pick the strongest peak and extract a set of harmonics associated with that peak.

in theory that should generate a load of ratios,  say if how original strongest peak was the third harmonic,  then  this set of peaks should contain 3/1 3/2 3/3 3/4 3/5 3/6 3/7 etc ...  although some may be missing.

realistically I have a feeling it's always going to be either a fundamental or the first harmonic that has the greatest strength.   but I don't know if I can rely on this...

so many factors, it is making my head swim. I apologise in advance for such a messy question. Hopefully I can tidy it up posthumously.

答:
A Cepstum (or Cepstral analysis) and Harmonic Product Spectrum are two well studied algorithms that estimate the exciter frequency from an overtone series.

If the sequences of overtones are appropriately spaced, than a Cepstrum (FFT of the log of the FFT peaks) may be useful in estimating the period of the frequency spacing, which can then be used to estimate the frequency.

The Harmonic Product Spectrum basically compares the spectral peaks with nth multiple copies of themselves by decimating the spectrum by multiple low integer ratios and overlapping them.

ContentLicense: CC BY-SA 2.5


问:
.bashrc/.profile is not loaded on new tmux session (or window) -- why?
When tmux starts or opens a new window, it does not load my .profile or .bashrc.  I end up typing . ~/.bashrc every time.  Is there a way to make this happen automatically?

答:
Running bash explicitly worked for me, by adding this line to my ~/.tmux.conf file:</p>

```<code>set-option -g default-command "exec /bin/bash"
</code>```

Body:
Running bash explicitly worked for me, by adding this line to my ~/.tmux.conf file:

set-option -g default-command "exec /bin/bash"


问:
How to save value from System.currentTimeMillis() in android studio
I have this code:

```<code>public class MainActivity extends AppCompatActivity implements SensorEventListener {

    long start_time;
    int record_state;

    @Override
    public void onSensorChanged(SensorEvent event) {
    Long time = System.currentTimeMillis();

    if (record_state == 1)
    {
        start_time = time;
        record_state = 0;
    }

    if(Ax.size() == N_SAMPLES && Ay.size() == N_SAMPLES && Az.size() == N_SAMPLES) //assuming this gets executed
    {
        Toast.makeText(MainActivity.this, "Size of Ax: " + Integer.toString(Ax.size()) +
                    "\nSize of Ay: " + Integer.toString(Ay.size()) +
                    "\nSize of Az: " + Integer.toString(Az.size()) + "\n" + Long.toString((time)) + "\n" + Long.toString((start_time)) + "\nrecord state: " + Integer.toString((record_state)), Toast.LENGTH_LONG).show();
        }
    }
}
</code>```

But it appears that time and start_time always have the same value. I want start_time to record the time at the very beginning (or freeze the value of time at one instant) only. How can I do this? What is wrong with this code?

答: Use lowercase 'long'.  You are using objects currently and pointing them both to the same reference, so when you change the value of one it affects the other.</p>

Body:
I have this code:

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    long start_time;
    int record_state;

    @Override
    public void onSensorChanged(SensorEvent event) {
    Long time = System.currentTimeMillis();

    if (record_state == 1)
    {
        start_time = time;
        record_state = 0;
    }

    if(Ax.size() == N_SAMPLES && Ay.size() == N_SAMPLES && Az.size() == N_SAMPLES) //assuming this gets executed
    {
        Toast.makeText(MainActivity.this, "Size of Ax: " + Integer.toString(Ax.size()) +
                    "\nSize of Ay: " + Integer.toString(Ay.size()) +
                    "\nSize of Az: " + Integer.toString(Az.size()) + "\n" + Long.toString((time)) + "\n" + Long.toString((start_time)) + "\nrecord state: " + Integer.toString((record_state)), Toast.LENGTH_LONG).show();
        }
    }
}

But it appears that time and start_time always have the same value. I want start_time to record the time at the very beginning (or freeze the value of time at one instant) only. How can I do this? What is wrong with this code?


问:
What does the "at" (@) symbol do in Python?
What does the @ symbol do in Python?

答:
@ symbol is also used to access variables inside a plydata / pandas dataframe query, pandas.DataFrame.query.
Example:

```<code>df = pandas.DataFrame({'foo': [1,2,15,17]})
y = 10
df >> query('foo > @y') # plydata
df.query('foo > @y') # pandas
</code>```

ContentLicense: CC BY-SA 4.0

Body: What does the @ symbol do in Python?

Body:
@ symbol is also used to access variables inside a plydata / pandas dataframe query, pandas.DataFrame.query.
Example:

df = pandas.DataFrame({'foo': [1,2,15,17]})
y = 10
df >> query('foo > @y') # plydata
df.query('foo > @y') # pandas


问:
R: using gsub in a for loop
Low level R user here.

I have 3 population data frames (low.proj, med.proj, high.proj) with the exact same number of rows and columns I'm trying to clean and reshape.

I want to eliminate some extra commas in the country column all three of the frames so I'm trying this loop with gsub:

```<code>for(i in c("low.proj", "med.proj", "high.proj")){
    i$Country <- gsub(",","",i[,"Country"])
    }
</code>```

When I run this I get the error "Error in i[, "Country"] : incorrect number of dimensions"

When I run the code without the loop:

```<code>low.proj$Country <- gsub(",","",low.proj[,"Country"])
</code>```

It works. What causes this error and how do I fix it?

答:
In order to retrieve the contents of the object with the string contained in i use get() to put new data in that object use assign

```<code>for(i in c("low.proj", "med.proj", "high.proj")){
  tmp <- get(i)
  tmp$Country <- gsub(",","",tmp[,"Country"])
  assign(i, tmp)
}
</code>```

Title: R: using gsub in a for loop

Body:
Low level R user here.

I have 3 population data frames (low.proj, med.proj, high.proj) with the exact same number of rows and columns I'm trying to clean and reshape.

I want to eliminate some extra commas in the country column all three of the frames so I'm trying this loop with gsub:

for(i in c("low.proj", "med.proj", "high.proj")){
    i$Country <- gsub(",","",i[,"Country"])
    }

When I run this I get the error "Error in i[, "Country"] : incorrect number of dimensions"

When I run the code without the loop:

low.proj$Country <- gsub(",","",low.proj[,"Country"])

It works. What causes this error and how do I fix it?

Body:
In order to retrieve the contents of the object with the string contained in i use get() to put new data in that object use assign

for(i in c("low.proj", "med.proj", "high.proj")){
  tmp <- get(i)
  tmp$Country <- gsub(",","",tmp[,"Country"])
  assign(i, tmp)
}


问:
Google sheets: Get column headers when data is present
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

```<code>     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0
</code>```

So if I have the Filter function:

```<code>=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")
</code>```

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.

答:
 Use a double FILTER:

```<code>=FILTER(C1:E1,--FILTER(C2:E3, A2:A3="Bob", B2:B3="Glv"))
</code>```

Body:
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0

So if I have the Filter function:

=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.

Body:
 Use a double FILTER:

=FILTER(C1:E1,--FILTER(C2:E3, A2:A3="Bob", B2:B3="Glv"))


问:
Changing background color of selected cell?
Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.</p>

答:
```<code>override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    if selected {
        self.contentView.backgroundColor = .black
    } else {
        self.contentView.backgroundColor = .white
    }
}
</code>```


问:
WPF&prism MVVM and Tabitem with an image
I have a wpf application with a tab control showing images instead of text on the tabitem.
Now I want to rewrite the whole thing and use prism.
I found an example but there is only a text property bound to the tabitem.
How can I display an image through binding to a viewmodel
(Each module has one tab).</p>

答:
When binding the items to the TabControl, use ItemsSource. The ItemTemplate defines what is shown in the tab header. The ContentTemplate defines what is shown in the tab area.

View Models

```<code>public class ShellViewModel : BindableBase
{
    public ObservableCollection<ItemViewModel> Items
    {
        get;
    } = new ObservableCollection<ItemViewModel>();

    public ShellViewModel()
    {
        Items.Add(new ItemViewModel { Name = "First", ImageUri = new Uri("http://placehold.it/50x50") });
        Items.Add(new ItemViewModel { Name = "Second", ImageUri = new Uri("http://placehold.it/40x40") });
        Items.Add(new ItemViewModel { Name = "Third", ImageUri = new Uri("http://placehold.it/30x30") });
    }
}

public class ItemViewModel : BindableBase
{
    private string _name;
    private Uri _imageUri;

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public Uri ImageUri
    {
        get => _imageUri;
        set => SetProperty(ref _imageUri, value);
    }
}
</code>```

View

```<code><Window x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp4"
    xmlns:viewModels="clr-namespace:WpfApp4.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <viewModels:ShellViewModel />
</Window.DataContext>
<Grid>
    <TabControl ItemsSource="{Binding Items}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding ImageUri}" Height="20"></Image>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>
</code>```

The above code will show three (3) tabs with the specified image in the tab header. I've dummied up the content with just text.

Body:
When binding the items to the TabControl, use ItemsSource. The ItemTemplate defines what is shown in the tab header. The ContentTemplate defines what is shown in the tab area.

View Models

public class ShellViewModel : BindableBase
{
    public ObservableCollection<ItemViewModel> Items
    {
        get;
    } = new ObservableCollection<ItemViewModel>();

    public ShellViewModel()
    {
        Items.Add(new ItemViewModel { Name = "First", ImageUri = new Uri("http://placehold.it/50x50") });
        Items.Add(new ItemViewModel { Name = "Second", ImageUri = new Uri("http://placehold.it/40x40") });
        Items.Add(new ItemViewModel { Name = "Third", ImageUri = new Uri("http://placehold.it/30x30") });
    }
}

public class ItemViewModel : BindableBase
{
    private string _name;
    private Uri _imageUri;

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public Uri ImageUri
    {
        get => _imageUri;
        set => SetProperty(ref _imageUri, value);
    }
}

View

<Window x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp4"
    xmlns:viewModels="clr-namespace:WpfApp4.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <viewModels:ShellViewModel />
</Window.DataContext>
<Grid>
    <TabControl ItemsSource="{Binding Items}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding ImageUri}" Height="20"></Image>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

The above code will show three (3) tabs with the specified image in the tab header. I've dummied up the content with just text.


问:
Replace two buttons with a toggle switch
I have the following code:

```<code><img id="v1" src="pic1.jpg"><br>
<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>
<br>
<img id="v2" src="pic3.jpg"><br>
<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>
<br>
</code>```

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

```<code><label class="switchBA">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</code>```

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

答:
Try this.

function toggleImage(){
 var el = document.getElementById("toggle")
 if(el.checked){
 document.getElementById("v1").src="https://picsee.co/images/social_facebook.png";
 }
 else{
  document.getElementById("v1").src="https://picsee.co/images/social_twitter.png";
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="v1" src="https://picsee.co/images/social_facebook.png">

<label class="switchBA">
<input type="checkbox" id="toggle" checked onclick="toggleImage()">
<span class="slider"></span>
</label></code>```

Body:
I have the following code:

<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>

<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

<input type="checkbox" checked>

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

Body:
Try this.

function toggleImage(){
 var el = document.getElementById("toggle")
 if(el.checked){
 document.getElementById("v1").src="https://picsee.co/images/social_facebook.png";
 }
 else{
  document.getElementById("v1").src="https://picsee.co/images/social_twitter.png";
 }
}

<img id="v1" src="https://picsee.co/images/social_facebook.png">

<label class="switchBA">
<input type="checkbox" id="toggle" checked onclick="toggleImage()">
<span class="slider"></span>
</label>


问:
S3 and CloudFront website hosting for multiple SPA redirect to different index.html based by url path
I have a single S3 bucket for multiple Single Page Applications, and enabled static website hosting for this bucket. Bucket has the following folders and files (firstApp & secondApp are folders and correspond to different SPA):

```<code>firstApp
    index.html
    *.js & *.css files
secondApp
    index.html
    *.js & *.css files
</code>```

Also I setup CloudFront in front of S3 bucket, default root object is set to index.html.
And now cloud-front-url/firstApp/ displays index.html from firstApp SPA and cloud-front-url/secondApp displays index.html from secondApp.

I need that all incorrect requests redirect to different index.html for specific app based by url path, e.g. if someone requests cloud-front-url/firstApp/non-existing-path - it should redirect to index.html from firstApp and similar behavior for secondApp.

I know how to setup CloudFront to redirect all 404 errors to a single index.html:

```<code>select distribution > Error Pages > Create custom error response:
* Http error code: 404
* Error Caching Minimum TTL (seconds) : 0
* Customize response: Yes
* Response Page Path : /firstApp/index.html
* HTTP Response Code: 200
</code>```

Is it possible with CloudFront to redirect 404 errors to different index.html based on requested path (redirect to index.html either in firstApp or secondApp folder)?

答:
When hosting a static website on S3, it's not possible to have different 404 pages. Generally speaking, one bucket has one 404 error page.

You could host your two applications in two separate buckets. Each would have it's own 404 error page.

Then, in CloudFront, use multiple behaviours pointing to each separate bucket. This way, /firstApp/ goes to bucket1, and /secondApp/ goes to bucket2.

Body:
I have a single S3 bucket for multiple Single Page Applications, and enabled static website hosting for this bucket. Bucket has the following folders and files (firstApp & secondApp are folders and correspond to different SPA):

firstApp
    index.html
    *.js & *.css files
secondApp
    index.html
    *.js & *.css files

Also I setup CloudFront in front of S3 bucket, default root object is set to index.html.
And now cloud-front-url/firstApp/ displays index.html from firstApp SPA and cloud-front-url/secondApp displays index.html from secondApp.

I need that all incorrect requests redirect to different index.html for specific app based by url path, e.g. if someone requests cloud-front-url/firstApp/non-existing-path - it should redirect to index.html from firstApp and similar behavior for secondApp.

I know how to setup CloudFront to redirect all 404 errors to a single index.html:

select distribution > Error Pages > Create custom error response:
* Http error code: 404
* Error Caching Minimum TTL (seconds) : 0
* Customize response: Yes
* Response Page Path : /firstApp/index.html
* HTTP Response Code: 200

Is it possible with CloudFront to redirect 404 errors to different index.html based on requested path (redirect to index.html either in firstApp or secondApp folder)?


问:
Drone.io | Create docker-compose settings
I can't connect to Drone.io with my GitHub.
And have several problems with the app:

1) drone-agent can't connect to server

```<code>dodge@comp:$drone agent
28070:M 15 Nov 22:04:01.906 * connecting to server http://<my_ip>
28070:M 15 Nov 22:04:01.906 # connection failed, retry in 15s. websocket.Dial http://<my_ip>: bad scheme
</code>```

2) I can't add Postgresql to docker-compose.
When I add this text from your site

```<code>DRONE_DATABASE_DRIVER: postgres
DRONE_DATABASE_DATASOURCE: postgres://root:password@1.2.3.4:5432/postgres?sslmode=disable
</code>```

I have this error

```<code>INFO: 2017/11/15 19:42:33 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: Error while dialing dial tcp 172.18.0.2:9000: getsockopt: connection refused"; Reconnecting to {drone-server:9000 <nil>}
</code>```

3) When I use only a server and an agent in docker-compose I have this error

```<code>dodge@comp:$drone server

ERRO[0000] sql: unknown driver "sqlite3" (forgotten import?)
FATA[0000] database connection failed
</code>```

docker-compose.yml

```<code>version: '2'
services:
  drone-server:
    image: drone/drone:0.8
    ports:
      - 80:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_OPEN=true
      - DRONE_HOST=http://172.18.0.2
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=secretid
      - DRONE_GITHUB_SECRET=secretpass
      - DRONE_SECRET=password

  drone-agent:
    image: drone/agent:0.8
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=password
</code>```

4) I cannot start tests in my project. Maybe I missed something during the setup.

答:
$ drone server

$ drone agent

I see the above commands in your examples. These commands are only available in drone 0.7 and below. Drone 0.8 uses drone-server and drone-agent binaries. There seems to be some version disconnect here.

connection failed, retry in 15s. websocket.Dial

drone 0.7 and below used websockets. I see in the docker-compose example you are using drone 0.8 which uses http2 and grpc. There seems to be a disconnect in your configuration vs the version of drone you are using.

sql: unknown driver "sqlite3"

this happens when you compile drone with CGO disabled, or use a version of drone that has been compiled with CGO disabled. If CGO is disabled the sqlite3 driver is not compiled into the binary. Are you trying to build drone from source?

grpc: addrConn.resetTransport failed to create client transport

This error comes from the agent, and is therefore unrelated to a postgres configuration. You should not be providing your agent with a postgres configuration, only the server.

Body:
I can't connect to Drone.io with my GitHub.
And have several problems with the app:

1) drone-agent can't connect to server

dodge@comp:$drone agent
28070:M 15 Nov 22:04:01.906 * connecting to server http://<my_ip>
28070:M 15 Nov 22:04:01.906 # connection failed, retry in 15s. websocket.Dial http://<my_ip>: bad scheme

2) I can't add Postgresql to docker-compose.
When I add this text from your site

DRONE_DATABASE_DRIVER: postgres
DRONE_DATABASE_DATASOURCE: postgres://root:password@1.2.3.4:5432/postgres?sslmode=disable

I have this error

INFO: 2017/11/15 19:42:33 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: Error while dialing dial tcp 172.18.0.2:9000: getsockopt: connection refused"; Reconnecting to {drone-server:9000 <nil>}

3) When I use only a server and an agent in docker-compose I have this error

dodge@comp:$drone server

ERRO[0000] sql: unknown driver "sqlite3" (forgotten import?)
FATA[0000] database connection failed

docker-compose.yml

version: '2'
services:
  drone-server:
    image: drone/drone:0.8
    ports:
      - 80:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_OPEN=true
      - DRONE_HOST=http://172.18.0.2
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=secretid
      - DRONE_GITHUB_SECRET=secretpass
      - DRONE_SECRET=password

  drone-agent:
    image: drone/agent:0.8
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=password

4) I cannot start tests in my project. Maybe I missed something during the setup.