问:
jQuery .on() "append"
So I know about jQuery's .on() function to give dynamically added element's event handlers.

E.g I've used it this way

```<code>$(document).on("change",Items,function(){/*Code here*/});
</code>```

But is there a way to use this .on() function (or something else) to call a function once an object has been appended into the document? I ask this because I'm using a jquery plugin called Chosen which creates better select boxes, and it works by using the line

```<code>$(selector).chosen();
</code>```

However that line doesn't work if it's used before an element is appended into the document, and for the sake of the cleanliness of my code it would be nice if I could call a function to run that line when the element has been appended, instead of adding that line after I've appended the element.

Edit: The problem isn't that I can't use .chosen() after I've appended the element. Because I can! I just want to be able to keep my code better organised by not having the $(selector).chosen() line hidden all the way at the bottom of my code unnoticed.

My code:

```<code>//Create the dropdown box for the items
var Items = document.createElement("select");
$(Items).attr( {"id":"Items"} );

$(document).on("change",Items,
    function(){
        updateHolder(true);
        $(InfoBox).trigger("chosen:updated");
        setTimeout(
            function(){
                $(Items).data('chosen').input_blur();
            }, 100
        );
    }
);

//Add items from ED.listOfItems to HTML Items dropdown box
for(var it in ED.listOfItems){
    var iKey = ED.listOfItems[it];
    var itemOption = document.createElement("option");
    if(!Array.isArray(iKey)){
        $(itemOption).val(iKey);
        $(itemOption).html(iKey.split("_")[0]);
    }
    else{
        $(itemOption).val(iKey[0]);
        $(itemOption).html(iKey[1]);

    }
    $(Items).append( itemOption );
}

/*******Set default to spawn*******/
/**/ ED.objectType = "Spawn";   /**/
/**/ ED.infoType = "";          /**/
/**/ $(Items).val("Spawn");     /**/
/**********************************/

$(MenuBar).append(Items);

$(Items).chosen({disable_search_threshold: 100});
$("#Items_chosen").css({"width":"100px","position":"absolute","left":"5px","top":"20px"});
</code>```

As you can see, the 2nd to last line is the chosen line, but it just seems to be in an illogical place to me. I'm very OCD with my code :P

答:
I had the problem of add a class to an element i've created and appended, since this class have transition, css transitions doesn't work if element is not in the DOM tree, all solutions i've tried didn't work for me so i ended up with this workaround:

```<code>  elementParent.append(elementToAdd);
  setTimeout(() => {
    $(elementToAdd).addClass("show");
  }, 0);
</code>```

In this way the class will be added only after the element has been added in the DOM.

Title: jQuery .on() "append"

Body:
So I know about jQuery's .on() function to give dynamically added element's event handlers.

E.g I've used it this way

$(document).on("change",Items,function(){/*Code here*/});

But is there a way to use this .on() function (or something else) to call a function once an object has been appended into the document? I ask this because I'm using a jquery plugin called Chosen which creates better select boxes, and it works by using the line

$(selector).chosen();

However that line doesn't work if it's used before an element is appended into the document, and for the sake of the cleanliness of my code it would be nice if I could call a function to run that line when the element has been appended, instead of adding that line after I've appended the element.

Edit: The problem isn't that I can't use .chosen() after I've appended the element. Because I can! I just want to be able to keep my code better organised by not having the $(selector).chosen() line hidden all the way at the bottom of my code unnoticed.

My code:

//Create the dropdown box for the items
var Items = document.createElement("select");
$(Items).attr( {"id":"Items"} );

$(document).on("change",Items,
    function(){
        updateHolder(true);
        $(InfoBox).trigger("chosen:updated");
        setTimeout(
            function(){
                $(Items).data('chosen').input_blur();
            }, 100
        );
    }
);

//Add items from ED.listOfItems to HTML Items dropdown box
for(var it in ED.listOfItems){
    var iKey = ED.listOfItems[it];
    var itemOption = document.createElement("option");
    if(!Array.isArray(iKey)){
        $(itemOption).val(iKey);
        $(itemOption).html(iKey.split("_")[0]);
    }
    else{
        $(itemOption).val(iKey[0]);
        $(itemOption).html(iKey[1]);

    }
    $(Items).append( itemOption );
}

/*******Set default to spawn*******/
/**/ ED.objectType = "Spawn";   /**/
/**/ ED.infoType = "";          /**/
/**/ $(Items).val("Spawn");     /**/
/**********************************/

$(MenuBar).append(Items);

$(Items).chosen({disable_search_threshold: 100});
$("#Items_chosen").css({"width":"100px","position":"absolute","left":"5px","top":"20px"});

As you can see, the 2nd to last line is the chosen line, but it just seems to be in an illogical place to me. I'm very OCD with my code :P

Body:
I had the problem of add a class to an element i've created and appended, since this class have transition, css transitions doesn't work if element is not in the DOM tree, all solutions i've tried didn't work for me so i ended up with this workaround:

  elementParent.append(elementToAdd);
  setTimeout(() => {
    $(elementToAdd).addClass("show");
  }, 0);

In this way the class will be added only after the element has been added in the DOM.


来源: stackexchange

问:
Azure IoT Hub via REST results in Unauthorized
I try to call some HTTP GET calls to the device twins of the MS Azure IoT Hub.

HTTP GET call via Postman

As you can see the GET call results in an unauthorized IoTHubUnauthorizedAccess error code.

I generated the token for the authorization header with the Azure Device Explorer as you can see in the picture below.

Generated SAS Token

Anyone any idea about this? I already searched here, and the only topic did not help me.

答:
From your picture, you used the specified device SAS token. While you need use IoT Hub SAS token it can grant access control and permissions. You can get it using Device Explorer like this:

And you will get the device twin information after posting the Get request successfully, in the postman, it looks like this:

ContentLicense: CC BY-SA 3.0


问:
React not passing state to child via props
I am trying to pass my parent App state to a child component Chart.

App

```<code>constructor() {
    super();
    this.state = {
        dataPoints: {
            '424353': {
                date: '10/10/2016',
                qty: '95'
            },
            '535332': {
                date: '10/11/2016',
                qty: '98'
            },
            '3453432': {
                date: '10/01/2017',
                qty: '94'
            }
        }
    };
    this.addPoint = this.addPoint.bind(this);
}

addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}

render() {
    return (
        <div className="app">
            <Chart dataPoints={this.state.dataPoints} />
            <FormControl addPoint={this.addPoint} />
        </div>
    );
}
</code>```

Chart

```<code>composeData() {
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

componentWillUpdate() {
    this.composeData();
}
</code>```

The addPoint method works, i.e. I can see in the React console that the new datapoint is added to the state. But it is not reflected in the Chart component. More oddly (to me) is the fact that when I've added a point, the console.log line in my addPoint method (above):

console.log('new state', this.state.dataPoints)

does not show the new data point.

答:
In add point

```<code>addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}
</code>```

In the above code you do not see the updated value because setState takes time to mutate, You must log it in the setState call back

```<code>this.setState({ dataPoints: dataPoints }, function(){
    console.log('new state', this.state.dataPoints);
 });
</code>```

And also in the Chart component you need to bind the composeData function if you are using this.props inside it like

```<code>composeData = () =>{
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}
</code>```

However componentWillMount is only called once and hence you will want to call the composeData function from componentWillReceiveProps also like

```<code>componentWillReceiveProps(nextProps) {
     this.composeData(nextProps)
}
componentWillMount() {
      this.composeData(this.props.dataPoints)
 }
composeData(props){
        Object
            .keys(props.dataPoints)
            .forEach(key => {
                ** do stuff **
            });

        return **stuff**;
    }
</code>```

Body:
I am trying to pass my parent App state to a child component Chart.

App

constructor() {
    super();
    this.state = {
        dataPoints: {
            '424353': {
                date: '10/10/2016',
                qty: '95'
            },
            '535332': {
                date: '10/11/2016',
                qty: '98'
            },
            '3453432': {
                date: '10/01/2017',
                qty: '94'
            }
        }
    };
    this.addPoint = this.addPoint.bind(this);
}

addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}

render() {
    return (

            <Chart dataPoints={this.state.dataPoints} />
            <FormControl addPoint={this.addPoint} />

    );
}

Chart

composeData() {
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

componentWillUpdate() {
    this.composeData();
}

The addPoint method works, i.e. I can see in the React console that the new datapoint is added to the state. But it is not reflected in the Chart component. More oddly (to me) is the fact that when I've added a point, the console.log line in my addPoint method (above):

console.log('new state', this.state.dataPoints)

does not show the new data point.

Body:
In add point

addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}

In the above code you do not see the updated value because setState takes time to mutate, You must log it in the setState call back

this.setState({ dataPoints: dataPoints }, function(){
    console.log('new state', this.state.dataPoints);
 });

And also in the Chart component you need to bind the composeData function if you are using this.props inside it like

composeData = () =>{
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

However componentWillMount is only called once and hence you will want to call the composeData function from componentWillReceiveProps also like

componentWillReceiveProps(nextProps) {
     this.composeData(nextProps)
}
componentWillMount() {
      this.composeData(this.props.dataPoints)
 }
composeData(props){
        Object
            .keys(props.dataPoints)
            .forEach(key => {
                ** do stuff **
            });

        return **stuff**;
    }


问:
How to define number of bits to generate using independent_bits_engine?
independent_bits_engine is the template class

```<code>template<
    class Engine,
    std::size_t W,
    class UIntType
> class independent_bits_engine;
</code>```

The second parametr define, how much bits need to be generated. I don't know its. I would to ask this question to user in runtime. How do it?

答:
The c++ templates are expanded at compile time, just like MICRO:
c++ template explanation wikipedia

When you run the c++ program the templates params are already determined.

So if you insist on the using the template to implement the independent_bits_engine, you have to remove the template param std::size_t W.
And instand you can pass the size param to the independent_bits_engine object at runtime.

Body:
independent_bits_engine is the template class

template<
    class Engine,
    std::size_t W,
    class UIntType
> class independent_bits_engine;

The second parametr define, how much bits need to be generated. I don't know its. I would to ask this question to user in runtime. How do it?


问:
Heroku HIPAA Compliance
Is it possible to run apps on Heroku that are HIPAA compliant? More specifically, I need two apps, one that stores member information and another that stores private health information of the members. I intend to encrypt sensitive data using both asymmetric and symmetric key encryption–asymmetric for the keys that link members with their sensitive data on the other app, and symmetric for specific fields in the members app, such as name, email address and phone. My main concern is that anyone at Heroku can break the asymmetric encryption, since they have access to both apps (and private keys). Am I correct to be concerned about this, or does the infrastructure of Amazon EC2 prevent Heroku staff from accessing both apps? </p>

答:
Amazon has a whitepaper on HIPAA compliance with AWS (just google AWS Hipaa compliance) where they talk about their HIPAA bona fides. For example, AWS sysadmins don't have direct login access to customer OS images.

To the best of my knowledge, Heroku has not shared details of how they secure their individual customer accounts.

ContentLicense: CC BY-SA 2.5

Title: Heroku HIPAA Compliance


问:
How does callback really work in node js
Below is my code which has two callbacks and one get route

```<code>app.get('/login', function(req, res, next) {
     res.sendFile(__dirname + '/public/views/login.html');
});
app.use(function (req, res, next) {
      console.log("first callback 1");
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
      console.log("first callback 2");
});
app.use(function (err, req, res, next) {
   // set locals, only providing error in development
      console.log("second callback");
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
     res.status(err.status || 500);
     res.render('error');
     console.log("error send");
});
</code>```

Basically here the two callbacks are for error handling.If I run the app and go to localhost:3000/home ,since there is no route and because of the call backs Ill get the 404 errror.

But if I go to localhost:3000/login ,it is displaying my login.html page but no call backs are getting called.Even though there is no error I mean atleast it should print first console message in the callback.But why it is not calling the callback?

What I read about callbacks is that if you don't specify any path,it gets called for all the routes.But why not here?Can someone take time to read this and clear me if I'm wrong.

答:
This is not about callbacks. It is about how the middleware (plugin/module) architecture work in Express (and incidentally lots of other frameworks, but be warned: not all frameworks work like this).

The real code implemented by Express is modular and a bit more complicated but basically it works something like this:

```<code>var middlewares = [];

var app = {
    use: function (callback) {
        middlewares.push({path:"", callback: callback});
    },
    get: function (path, callback) {
        middlewares.push({path: path, callback: callback});
    }
}
</code>```

So you see, the idea is simple. There really is nothing fancy. .use() is used to add code you want to execute with all paths and .get() is used to add code you want to execute if the path matches.

So we can now process each request to the server by looping through the array:

```<code>// WARNING: NOT REAL CODE, this is only meant as an illustration

function processRequest (req, res) {
    for (var i=0; i<middlewares.length; i++) {
        var whatToDo = middlewares[i];

        if (whatToDo.path == "") { // no need to check path
            whatToDo.callback(err, req, res, next);
        }
        else if (whatToDo.path == req.path) { // check if path match
            whatToDo.callback(req, res, next);
        }
    }
}
</code>```

So that's how it works. Of course, the middlewares are asynchronous so in the real code we can't use the for loop. That's actually what the next() function is for - to loop through the middlewares like a linked list (only, its linked functions). If no next() is called the loop stops.

Body:
Below is my code which has two callbacks and one get route

app.get('/login', function(req, res, next) {
     res.sendFile(__dirname + '/public/views/login.html');
});
app.use(function (req, res, next) {
      console.log("first callback 1");
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
      console.log("first callback 2");
});
app.use(function (err, req, res, next) {
   // set locals, only providing error in development
      console.log("second callback");
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
     res.status(err.status || 500);
     res.render('error');
     console.log("error send");
});

Basically here the two callbacks are for error handling.If I run the app and go to localhost:3000/home ,since there is no route and because of the call backs Ill get the 404 errror.

But if I go to localhost:3000/login ,it is displaying my login.html page but no call backs are getting called.Even though there is no error I mean atleast it should print first console message in the callback.But why it is not calling the callback?

What I read about callbacks is that if you don't specify any path,it gets called for all the routes.But why not here?Can someone take time to read this and clear me if I'm wrong.

Body:
This is not about callbacks. It is about how the middleware (plugin/module) architecture work in Express (and incidentally lots of other frameworks, but be warned: not all frameworks work like this).

The real code implemented by Express is modular and a bit more complicated but basically it works something like this:

var middlewares = [];

var app = {
    use: function (callback) {
        middlewares.push({path:"", callback: callback});
    },
    get: function (path, callback) {
        middlewares.push({path: path, callback: callback});
    }
}

So you see, the idea is simple. There really is nothing fancy. .use() is used to add code you want to execute with all paths and .get() is used to add code you want to execute if the path matches.

So we can now process each request to the server by looping through the array:

// WARNING: NOT REAL CODE, this is only meant as an illustration

function processRequest (req, res) {
    for (var i=0; i<middlewares.length; i++) {
        var whatToDo = middlewares[i];

        if (whatToDo.path == "") { // no need to check path
            whatToDo.callback(err, req, res, next);
        }
        else if (whatToDo.path == req.path) { // check if path match
            whatToDo.callback(req, res, next);
        }
    }
}

So that's how it works. Of course, the middlewares are asynchronous so in the real code we can't use the for loop. That's actually what the next() function is for - to loop through the middlewares like a linked list (only, its linked functions). If no next() is called the loop stops.


问:
cannot access wordpress frontend page without proxy_set_header Host
I use nginx as reverse proxy for apache wordpress site. But I cannot access word.com frontend page if I comment out the proxy_set_header part, it just redirect to 127.0.0.1 in my brower. Who can explain it for me?
Nginx settings:</p>

```<code>server {
    listen 80 default_server;
    server_name word.com
    charset utf-8;
    index index.htm index.html;
    access_log /var/log/nginx/word-access.log main;
    error_log /var/log/nginx/word-error.log;

    location / {
        proxy_pass http://127.0.0.1:8080;
    }

    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}
</code>```

答:
In the absence of a proxy_set_header directive, nginx will set the proxied Host header to 127.0.0.0:8080.

Apache will see this hostname and use it when constructing certain response to the browser (such as a redirect).

It is usual to specify proxy_set_header Host $host;. The default value is only useful in limited cases, such as contacting remote resources.

See this document for more.

Body:
I use nginx as reverse proxy for apache wordpress site. But I cannot access word.com frontend page if I comment out the proxy_set_header part, it just redirect to 127.0.0.1 in my brower. Who can explain it for me?
Nginx settings:

server {
    listen 80 default_server;
    server_name word.com
    charset utf-8;
    index index.htm index.html;
    access_log /var/log/nginx/word-access.log main;
    error_log /var/log/nginx/word-error.log;

    location / {
        proxy_pass http://127.0.0.1:8080;
    }

    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}


问:
Chartjs adding icon to tooltip and label
I want to add a prefix to the tooltip and y-label in chartjs, but the problem is, when I put the  it is returned as string not as an html tag as you can see on the image

Here's my code:

```<code><script>

$(document).ready(function(){
    var lineLabel = <?php echo json_encode(array_reverse( $ch1_arrDate)); ?>;
    var dataVal1 = <?php echo json_encode(array_reverse( $ch1_arrRevenue_conf)); ?>;
    var dateFilter = <?php echo json_encode(array_reverse($ch1_arrDate2)); ?>;

    var lineData = {
        labels: lineLabel,
        datasets: [
            {
                label: 'Confirmed Revenue',
                backgroundColor: 'rgba(0,0,0,0.03)',
                data: dataVal1,
                borderColor: 'rgba(163,216,3,1)',
                borderWidth:1,
            },
        ]
    };

    var lineOptions = {
        responsive: true,
        maintainAspectRatio: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    userCallback: function(value, index, values) {
                        return "<i class='fa fa-sampleicon'></i>"+addCommas(value);
                    }
                }
            }]
        },
        legend: {
            display: true,
            position: 'bottom'
        },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              return "<i class='fa fa-sampleicon'></i>"+addCommas(tooltipItem.yLabel);
            }
          }
        }

    }

    var ctx = document.getElementById("chart1").getContext("2d");

    if($(window).width()>748){
        ctx.canvas.height = 160;
    }
    else{
        ctx.canvas.height = 300;
    }

    var chartDisplay = new Chart(ctx, {
        type: 'line',
        data: lineData,
        options: lineOptions
    });

    $("#chart1").click(
       function(e){
            var activeLines= chartDisplay.getElementsAtEvent(e);
            var index = activeLines[0]["_index"];
            window.open(
            "dash_chartdeals.php?from=past&filter_date="+fixedEncodeURIComponent(dateFilter[index]),
            '_blank'
            )
    });

    $("#chart1").mouseenter(function(){
        $("#chart1").css("cursor", "pointer");
    });
});
function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

</script>
</code>```

答:
I've found an answer to this,
So basically as @jordanwillis said, it's only string painted on canvas therefore you can't add html tags.

So the concept is to create a seperate div where you will put your custom tooltip(text / icons / image) onto, then positioning that div to where the default tooltip shows.

under my chart I added a new div chartjs-tooltip3

```<code><div class="row">
    <div class="col-xs-12">
        <canvas id="chart3" width="500" height="300" style="border:1px solid #f1f1f1; padding:20px; padding-top:40px; box-shadow:2px 2px 2px rgba(0,0,0,0.2);"></canvas>
        <div id="chartjs-tooltip3"></div>
    </div>
</div>
</code>```

then on my script:

I changed my default tooltip configuration to show false so it wont get in the way of my new tooltip.

```<code>$(document).ready(function(){
    Chart.defaults.global.tooltips.enabled = false; //disable default tooltip
</code>```

And at the lineOptions, instead of calling callbacks

```<code>tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              return "<i class='fa fa-sampleicon'></i>"+addCommas(tooltipItem.yLabel);
            }
          }
        }
</code>```

I've called custom, here you can freely manipulate your div and other things inside the function..

```<code>tooltips: {
            custom: function(tooltip) {
                var tooltipEl = $('#chartjs-tooltip3');

                if (!tooltip) {
                    tooltipEl.css({
                        opacity: 0
                    });
                    return;
                }

                if(tooltip.body){ // if the cursor hits the point

                    value = addCommas(tooltip.body["0"].lines["0"].substring(18)); //the data i need to add on my custom tooltip

                    tooltipEl.html(icon+" "+value); //icon is the html tag <i class="fa fa-sampleicon"></i>

                    //set the custom div to where the default tooltip is supposed to show.
                    tooltipEl.css({
                        opacity: 1,
                        left: tooltip.x + 'px',
                        top: tooltip.y + 'px',
                        fontFamily: this.fontFamily,
                        fontSize: this.fontSize,
                        fontStyle: this.fontStyle,
                    });
                    $("#chart3").css("cursor", "pointer");
                }
                else
                {
                    // if outside of the point, it'll hide the custom div
                    tooltipEl.css({
                        opacity: 0
                    });
                    //change my cursor to default
                    $("#chart3").css("cursor", "default");
                }
            }

        }
</code>```

to get the data you wanted to get, you can always log the tooltip.. It'll give you the list of the array objects.

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

Here is the basic css of my custom div:

```<code>#chartjs-tooltip3{
     opacity: 0;
     position: absolute;
     background: rgba(0, 0, 0, .6);
     color: white;
     padding: 5px 12px 3px 12px;
     border-radius: 3px;
     -webkit-transition: all .1s ease;
     transition: all .2s ease;
     pointer-events: none;
     -webkit-transform: translate(-50%, 0);
     transform: translate(-50%, 0);
 }
</code>```

I've gathered my answer from these threads Chart JS Show HTML in Tooltip and How to add image to chart.js tooltip?  and

Body:
I've found an answer to this,
So basically as @jordanwillis said, it's only string painted on canvas therefore you can't add html tags.

So the concept is to create a seperate div where you will put your custom tooltip(text / icons / image) onto, then positioning that div to where the default tooltip shows.

under my chart I added a new div chartjs-tooltip3

<div class="row">
    <div class="col-xs-12">
        <canvas id="chart3" width="500" height="300" style="border:1px solid #f1f1f1; padding:20px; padding-top:40px; box-shadow:2px 2px 2px rgba(0,0,0,0.2);"></canvas>
        <div id="chartjs-tooltip3"></div>
    </div>
</div>

then on my script:

I changed my default tooltip configuration to show false so it wont get in the way of my new tooltip.

$(document).ready(function(){
    Chart.defaults.global.tooltips.enabled = false; //disable default tooltip

And at the lineOptions, instead of calling callbacks

tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              return "<i class='fa fa-sampleicon'></i>"+addCommas(tooltipItem.yLabel);
            }
          }
        }

I've called custom, here you can freely manipulate your div and other things inside the function..

tooltips: {
            custom: function(tooltip) {
                var tooltipEl = $('#chartjs-tooltip3');

                if (!tooltip) {
                    tooltipEl.css({
                        opacity: 0
                    });
                    return;
                }

                if(tooltip.body){ // if the cursor hits the point

                    value = addCommas(tooltip.body["0"].lines["0"].substring(18)); //the data i need to add on my custom tooltip

                    tooltipEl.html(icon+" "+value); //icon is the html tag <i class="fa fa-sampleicon"></i>

                    //set the custom div to where the default tooltip is supposed to show.
                    tooltipEl.css({
                        opacity: 1,
                        left: tooltip.x + 'px',
                        top: tooltip.y + 'px',
                        fontFamily: this.fontFamily,
                        fontSize: this.fontSize,
                        fontStyle: this.fontStyle,
                    });
                    $("#chart3").css("cursor", "pointer");
                }
                else
                {
                    // if outside of the point, it'll hide the custom div
                    tooltipEl.css({
                        opacity: 0
                    });
                    //change my cursor to default
                    $("#chart3").css("cursor", "default");
                }
            }

        }

to get the data you wanted to get, you can always log the tooltip.. It'll give you the list of the array objects.

console.log(tooltip);

Here is the basic css of my custom div:

#chartjs-tooltip3{
     opacity: 0;
     position: absolute;
     background: rgba(0, 0, 0, .6);
     color: white;
     padding: 5px 12px 3px 12px;
     border-radius: 3px;
     -webkit-transition: all .1s ease;
     transition: all .2s ease;
     pointer-events: none;
     -webkit-transform: translate(-50%, 0);
     transform: translate(-50%, 0);
 }

I've gathered my answer from these threads Chart JS Show HTML in Tooltip and How to add image to chart.js tooltip?  and


答:
Try the below script</p>

```<code>SELECT  DISTINCT USER_ID
FROM    Table_01
GROUP BY USER_ID, (YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING  COUNT(*) > 1
</code>```

Title: Users that returned

Body:
I have a table with [EVENT_DATE] and [USER_ID], I would like to know how to count the users who came back in the same month.

Table_01
-------------------------------------------
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

The answering being 2, because users 0006235012201 & 0006235012203 both came back within the same month.

EDIT: Sorry

I am looking to get the count by month.

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

This is what I have, but it isn't correct as it seems to be listing users.

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016. Compatibility level: SQL Server 2005 (90)

Body:
Try the below script

SELECT  DISTINCT USER_ID
FROM    Table_01
GROUP BY USER_ID, (YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING  COUNT(*) > 1


问:
Displaying a Play button on Multiple videos on the same page
I'm a complete novice when it comes to Javascript (& copy and paste kind of guy ;)... so I'm having a bit of a problem trying to figure out how to do the following:

I've got a slideshow gallery that has 2 mp4 videos in the same set

I've found some javascript that overlays a play button on the mp4 video

However... the code work fine when I have one video - but when I place the 2nd video, I'm failing to get the overlaid arrows working on both...

There's an obvious problem with clashing classes / variables (or something to that effect) - but I can't figure it out...

HTML:

```<code><div class="swiper-slide">
    <div class="video-wrapper">
        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>
    </div>
</div>

<div class="swiper-slide">
    <div class="video-wrapper-two">
        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>
    </div>
</div>
</code>```

Javascript:

```<code><script>

var videoPlayButton,
videoWrapper = document.getElementsByClassName('video-wrapper')[0],
video = document.getElementsByTagName('video')[0],
videoMethods = {
    renderVideoPlayButton: function() {
        if (videoWrapper.contains(video)) {
            this.formatVideoPlayButton()
            video.classList.add('has-media-controls-hidden')
            videoPlayButton = document.getElementsByClassName('video-overlay-play-button')[0]
            videoPlayButton.addEventListener('click', this.hideVideoPlayButton)
        }
    },

    formatVideoPlayButton: function() {
        videoWrapper.insertAdjacentHTML('beforeend', '\
            <svg class="video-overlay-play-button" viewBox="0 0 200 200" alt="Play video">\
                <circle cx="100" cy="100" r="90" fill="#000" stroke-width="5" stroke="#fff"/>\
                <polygon points="70, 55 70, 145 145, 100" fill="#fff"/>\
            </svg>\
        ')
    },

    hideVideoPlayButton: function() {
        video.play()
        videoPlayButton.classList.add('is-hidden')
        video.classList.remove('has-media-controls-hidden')
        video.setAttribute('controls', 'controls')
    }
}

videoMethods.renderVideoPlayButton()

</script>
</code>```

The javascript handles the 1st wrapper fine, I'm just having difficulty getting the 2nd wrapper to display the Play button correctly...

Any help appreciated.

答:
                    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>

So let's focus on these lines.
Your first error in HTML is renaming the 'video-wrapper' class to 'video-wrapper-two' on the second element. It must be the same if you plan to reuse the elements in JavaScript.

Your second error is referencing only the first 'video-wrapper' from your array instead of getting them all
    videoWrapper = document.getElementsByClassName('video-wrapper')[0]

Instead you would need this

```<code>videoWrappers = document.getElementsByClassName('video-wrapper');
videos = document.getElementsByTagName('video');
</code>```

The third problem needs a bit more code, because at the moment you baked in the single videoElement item into your functions, so you can't call it on each. So instead of referencing the videos from the function, you have to pass it as a reference (as a function parameter) so you could do something like this when you call it

```<code>for(var i = 0; i < videWrappers.length; i++){
    // it will be called on each video element one by one
    videoMethods.renderVideoPlayButton(videoWrappers[i], video[i]);
}
</code>```

The key point is to never bake variables into your functions, instead always use function parameters so you can reuse those functions whenever you need it.

Body:
I'm a complete novice when it comes to Javascript (& copy and paste kind of guy ;)... so I'm having a bit of a problem trying to figure out how to do the following:

I've got a slideshow gallery that has 2 mp4 videos in the same set

I've found some javascript that overlays a play button on the mp4 video

However... the code work fine when I have one video - but when I place the 2nd video, I'm failing to get the overlaid arrows working on both...

There's an obvious problem with clashing classes / variables (or something to that effect) - but I can't figure it out...

HTML:

        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>

        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>

Javascript:

The javascript handles the 1st wrapper fine, I'm just having difficulty getting the 2nd wrapper to display the Play button correctly...

Any help appreciated.

Body:
<div class="swiper-slide">
                <div class="video-wrapper-two">
                    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>
                </div>
            </div>

So let's focus on these lines.
Your first error in HTML is renaming the 'video-wrapper' class to 'video-wrapper-two' on the second element. It must be the same if you plan to reuse the elements in JavaScript.

Your second error is referencing only the first 'video-wrapper' from your array instead of getting them all
    videoWrapper = document.getElementsByClassName('video-wrapper')[0]

Instead you would need this

videoWrappers = document.getElementsByClassName('video-wrapper');
videos = document.getElementsByTagName('video');

The third problem needs a bit more code, because at the moment you baked in the single videoElement item into your functions, so you can't call it on each. So instead of referencing the videos from the function, you have to pass it as a reference (as a function parameter) so you could do something like this when you call it

for(var i = 0; i < videWrappers.length; i++){
    // it will be called on each video element one by one
    videoMethods.renderVideoPlayButton(videoWrappers[i], video[i]);
}

The key point is to never bake variables into your functions, instead always use function parameters so you can reuse those functions whenever you need it.


问:
CoreData Relationship not updating after insert
I have a 1 to many relationship between 2 entities in my model.  I fetch entity1 that is on the '1' side and access the relationships set.  When I find that there are no items currently in the set I request information from my service, create/insert entities, set properties, set relationship back to entity1, and save the ManagedObjectContext.

I then reload a TableView, which immediately accesses the relationships set on entity1 and checks the count to see if there are any relationships to display.  No matter what I do, even if I call refreshObject, the count on the relationships set is always 0.
If I restart my app, the count is correct and I can see that the relationships to entity1 have been setup correctly.

Any idea what I am doing wrong here?  I am doing similar code with other entities in my data model and am not having this problem.  Something is strangely out of sync.

Thanks!

答: Are the new objects being inserted and set on the relationship in the same MOC?</p>


问:
react native login username not find
can someone help me, i dont what will i do. this code always error if i setting the username and password. i'am a newbie, this my first work build app with react native

```<code>export default class Login extends Component {

   constructor(props) {
    super(props);
    this.state = {
     username: '',
     password: ''};
  }

  async loginAjax() {
    try {
      let response = await fetch('http://panel.erzap.com/web_services/login_json/new.json', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          erzap: {
            username: this.state.username,
            password: this.state.password,
            }
        })
      });
      let responseJson = await response.json();
      Alert.alert(responseJson.notice);
    } catch(error) {
      Alert.alert(error);
      console.error(error);
    }
  }
</code>```

enter image description here

答:
```<code><TouchableHighlight onPress={() => this.loginAjax()}>
     <Text style={styles.btn}>Login</Text>
</TouchableHighlight>
</code>```

Replace this part of the code with your code. It's work for me...

Title: react native login username not find

Body:
can someone help me, i dont what will i do. this code always error if i setting the username and password. i'am a newbie, this my first work build app with react native

export default class Login extends Component {

   constructor(props) {
    super(props);
    this.state = {
     username: '',
     password: ''};
  }

  async loginAjax() {
    try {
      let response = await fetch('http://panel.erzap.com/web_services/login_json/new.json', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          erzap: {
            username: this.state.username,
            password: this.state.password,
            }
        })
      });
      let responseJson = await response.json();
      Alert.alert(responseJson.notice);
    } catch(error) {
      Alert.alert(error);
      console.error(error);
    }
  }

enter image description here

Body:
<TouchableHighlight onPress={() => this.loginAjax()}>
     <Text style={styles.btn}>Login</Text>
</TouchableHighlight>

Replace this part of the code with your code. It's work for me...


问:
Query for updating a column in same table from same table
I have to update the authorid column which are matching  (where documentculture = 'en-US'

to matching (where documentculture = 'el-GR' in the same table. which includes a inner join to another table

I written like below which looks wrong:

```<code>  UPDATE t1
  SET t1.authorid = t2.authorid
  FROM wv_blogdata AS t1
  INNER JOIN wv_blogdata AS t2
  ON t1.documentnodeid = t2.documentnodeid
  inner join CMS_Document d
  ON d.BlogDataID = d.DocumentForeignKeyValue
  WHERE t2.DocumentCulture = 'en-US';
</code>```

could you please correct me?

More explanation:

```<code>select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='el-GR'
</code>```

The author id of above query is different from authorid of below query
which i want to make it synch

```<code>select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='en-US'
</code>```

答:
The following query should make the records in sync so authorid of german blogs and authorid of usa blogs will become the same after you run this query.

Note that top(1) is required so only one value is returned by the sub-query else if there are multiple blog records for german culture you will encounter an error.

```<code>UPDATE b
SET b.authorid =
  (SELECT top(1) wvb.authorid
   FROM wv_blogdata wvb
   INNER JOIN CMS_Document cms ON wvb.BlogDataID = cms.DocumentForeignKeyValue
   WHERE cms.DocumentCulture ='el-GR' AND b.BlogDataID = cms.DocumentForeignKeyValue order by wvb.authorid)
 FROM wv_blogdata b
  INNER JOIN CMS_Document  ON b.BlogDataID = CMS_Document.DocumentForeignKeyValue
WHERE CMS_Document.DocumentCulture ='en-US';
</code>```

Body:
I have to update the authorid column which are matching  (where documentculture = 'en-US'

to matching (where documentculture = 'el-GR' in the same table. which includes a inner join to another table

I written like below which looks wrong:

  UPDATE t1
  SET t1.authorid = t2.authorid
  FROM wv_blogdata AS t1
  INNER JOIN wv_blogdata AS t2
  ON t1.documentnodeid = t2.documentnodeid
  inner join CMS_Document d
  ON d.BlogDataID = d.DocumentForeignKeyValue
  WHERE t2.DocumentCulture = 'en-US';

could you please correct me?

More explanation:

select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='el-GR'

The author id of above query is different from authorid of below query
which i want to make it synch

select authorid from wv_blogdata
inner join CMS_Document
on wv_blogdata.BlogDataID = CMS_Document.DocumentForeignKeyValue
Where DocumentCulture ='en-US'

Body:
The following query should make the records in sync so authorid of german blogs and authorid of usa blogs will become the same after you run this query.

Note that top(1) is required so only one value is returned by the sub-query else if there are multiple blog records for german culture you will encounter an error.

UPDATE b
SET b.authorid =
  (SELECT top(1) wvb.authorid
   FROM wv_blogdata wvb
   INNER JOIN CMS_Document cms ON wvb.BlogDataID = cms.DocumentForeignKeyValue
   WHERE cms.DocumentCulture ='el-GR' AND b.BlogDataID = cms.DocumentForeignKeyValue order by wvb.authorid)
 FROM wv_blogdata b
  INNER JOIN CMS_Document  ON b.BlogDataID = CMS_Document.DocumentForeignKeyValue
WHERE CMS_Document.DocumentCulture ='en-US';


问:
Third party soap provider & Clean Architecture
We are designing an application with clean/hexagonal architecture paradigm but we are newbies on this. So we have some questions.

The scenario is:

We have an external SOAP service who gives to us some "Entity" information and related "Document"

For every Entity the application must:

store all the Entity Documents on a CMS (content and some Entity-attributes)

store Entity on DDBB with stored Document reference

Lets see our initial solution on java-like approach:

Entity and Document

```<code>class Entity {
  private String id;
  // other attributes ...
  private Document xml;
  private Document pdf;
  // some business logic
}

class Document {
  private long id;
  //other attributes
  InputStream getStream() {...}
}
</code>```

FRepositori abstraction at Domain Layer

```<code>class EntityRepositori {
  Entity create(Entity entity);
  ...
}
</code>```

DocumentRepositori abstraction at Domain Layer

```<code>class DocumentRepositori {
  Document create(Document document)
  ...
}
</code>```

ExternalService abstraction at Application Layer for the SOAP service

```<code>class ExternalService {
  List<Entity> getEntities();
  ...
}
</code>```

An Use Case implementation at Application Layer

```<code>class IncorporateEntityUseCase {
  IncorporateFUserCase(EntityRepositori, DocumentRepositori, ExternalService){...}
  void incorporate() {
    List<Entity> entities = externalService.getEntities();
    for (Entity entity : entities) {
        Document xml = dRepository.create(entity.getXmnl());
        Document pdf = dRepository.create(entity.getPdf());
        entity.setXml(xml);
        entity.setPdf(pdf);
        entityRepository.create(entity);
    }
  }
}
</code>```

Questions

About ExternalService, it is correct to define its abstraction with
Entity and Document or must it returns some ValueObject that UseCase implementations will transform to entities?

About Document, must we design it as an aggregate root and eliminate Document object references from Entity?

答:
Short version: try thinking about any of your 3rd party services as simply another Gateway (or "repository").

Having just come across this exact same question myself (think a system where users upload documents as part of a larger domain object "Questionnaire" and then parse them), I ended up going with the approach that the external api / parser (or in your case, 3rd party SOAP service) is really, just another Gateway. Ie: the files are passed in (via webpage upload), send down from the webapi controllers to the interactor, transmitted out through a gateway (currently as a stream, but in the same way that they might be passed to a db gateway/repository) - where they are processed, and the result returned as an Entity model. So the Interactor has a db gateway and a document parser gateway, both of which return Domain models that are usable.

Body:
We are designing an application with clean/hexagonal architecture paradigm but we are newbies on this. So we have some questions.

The scenario is:

We have an external SOAP service who gives to us some "Entity" information and related "Document"

For every Entity the application must:

store all the Entity Documents on a CMS (content and some Entity-attributes)

store Entity on DDBB with stored Document reference

Lets see our initial solution on java-like approach:

Entity and Document

class Entity {
  private String id;
  // other attributes ...
  private Document xml;
  private Document pdf;
  // some business logic
}

class Document {
  private long id;
  //other attributes
  InputStream getStream() {...}
}

FRepositori abstraction at Domain Layer

class EntityRepositori {
  Entity create(Entity entity);
  ...
}

DocumentRepositori abstraction at Domain Layer

class DocumentRepositori {
  Document create(Document document)
  ...
}

ExternalService abstraction at Application Layer for the SOAP service

class ExternalService {
  List<Entity> getEntities();
  ...
}

An Use Case implementation at Application Layer

class IncorporateEntityUseCase {
  IncorporateFUserCase(EntityRepositori, DocumentRepositori, ExternalService){...}
  void incorporate() {
    List<Entity> entities = externalService.getEntities();
    for (Entity entity : entities) {
        Document xml = dRepository.create(entity.getXmnl());
        Document pdf = dRepository.create(entity.getPdf());
        entity.setXml(xml);
        entity.setPdf(pdf);
        entityRepository.create(entity);
    }
  }
}

Questions

About ExternalService, it is correct to define its abstraction with
Entity and Document or must it returns some ValueObject that UseCase implementations will transform to entities?

About Document, must we design it as an aggregate root and eliminate Document object references from Entity?


问:
SQL Server- get manager of employee (with exceptions)
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

```<code>EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL
</code>```

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

```<code>EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL
</code>```

I only got this far

```<code>SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte
</code>```

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?

答:
Try this</p>

```<code>DECLARE @Employee AS TABLE
(
   EmployeeID int ,
   OrganisationID int,
   Level int,
   Manager1 int,
   Manager2 int,
   Manager3 int,
   Manager4 int,
   Manager5 int
)

INSERT INTO @Employee VALUES(1          , 1001           , 1     , NULL     , NULL     , NULL     , NULL     , NULL    )
INSERT INTO @Employee VALUES(8          , 1011           , 1     , 1        , NULL     , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(2          , 1002           , 2     , 1        , 1        , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(3          , 1002           , 2     , 1        , 1        , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(4          , 1003           , 4     , 1        , 2        , NULL     , 4        , NULL     )
INSERT INTO @Employee VALUES(5          , 1004           , 3     , NULL     , NULL     , 2        , NULL     , NULL   )
INSERT INTO @Employee VALUES(6          , 1005           , 5     , 1        , NULL     , 2        , 6        , 6)
INSERT INTO @Employee VALUES(7          , 1006           , 5     , NULL     , 7        , 7        , NULL     , NULL   )

;WITH temps AS
(SELECT e.EmployeeID,e.Level, cr.ManagerId, cr.ManagerLevel
FROM @Employee e
CROSS APPLY
(
   SELECT e.Manager1 AS ManagerId,  1 AS ManagerLevel
   UNION ALL
   SELECT e.Manager2,  2 AS ManagerLevel
   UNION ALL
   SELECT e.Manager3,  3 AS ManagerLevel
   UNION ALL
   SELECT e.Manager4,  4 AS ManagerLevel
   UNION ALL
   SELECT e.Manager5,  5 AS ManagerLevel
) AS cr
)
SELECT  e.EmployeeID, t.ManagerId
FROM  @Employee e
LEFT JOIN
(
   SELECT DISTINCT t.EmployeeID , First_Value(t.ManagerId) OVER (PARTITION BY t.EmployeeID ORDER BY t.ManagerLevel DESC) AS ManagerId
   FROM temps t
   WHERE t.ManagerLevel <= t.Level AND t.ManagerId IS NOT NULL AND t.ManagerId <> t.EmployeeID
) t ON e.EmployeeID = t.EmployeeID
</code>```

Body:
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL

I only got this far

SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?

Body:
Try this

DECLARE @Employee AS TABLE
(
   EmployeeID int ,
   OrganisationID int,
   Level int,
   Manager1 int,
   Manager2 int,
   Manager3 int,
   Manager4 int,
   Manager5 int
)

INSERT INTO @Employee VALUES(1          , 1001           , 1     , NULL     , NULL     , NULL     , NULL     , NULL    )
INSERT INTO @Employee VALUES(8          , 1011           , 1     , 1        , NULL     , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(2          , 1002           , 2     , 1        , 1        , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(3          , 1002           , 2     , 1        , 1        , NULL     , NULL     , NULL     )
INSERT INTO @Employee VALUES(4          , 1003           , 4     , 1        , 2        , NULL     , 4        , NULL     )
INSERT INTO @Employee VALUES(5          , 1004           , 3     , NULL     , NULL     , 2        , NULL     , NULL   )
INSERT INTO @Employee VALUES(6          , 1005           , 5     , 1        , NULL     , 2        , 6        , 6)
INSERT INTO @Employee VALUES(7          , 1006           , 5     , NULL     , 7        , 7        , NULL     , NULL   )

;WITH temps AS
(SELECT e.EmployeeID,e.Level, cr.ManagerId, cr.ManagerLevel
FROM @Employee e
CROSS APPLY
(
   SELECT e.Manager1 AS ManagerId,  1 AS ManagerLevel
   UNION ALL
   SELECT e.Manager2,  2 AS ManagerLevel
   UNION ALL
   SELECT e.Manager3,  3 AS ManagerLevel
   UNION ALL
   SELECT e.Manager4,  4 AS ManagerLevel
   UNION ALL
   SELECT e.Manager5,  5 AS ManagerLevel
) AS cr
)
SELECT  e.EmployeeID, t.ManagerId
FROM  @Employee e
LEFT JOIN
(
   SELECT DISTINCT t.EmployeeID , First_Value(t.ManagerId) OVER (PARTITION BY t.EmployeeID ORDER BY t.ManagerLevel DESC) AS ManagerId
   FROM temps t
   WHERE t.ManagerLevel <= t.Level AND t.ManagerId IS NOT NULL AND t.ManagerId <> t.EmployeeID
) t ON e.EmployeeID = t.EmployeeID


问:
(null != someVariable) OR (someVariable != null)
What is the difference between (null != someVariable) and (someVariable != null)? I have seen a lot of people using 'null' first in the comparison. Which one is better than the other and why?</p>

答:
Consider you want this :

```<code>if (number == 42) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42
</code>```

Now, imagine you forget there should be a double = and you just write a single = instead :

```<code>if (number = 42) { /* ... */ }
// This assigns 42 to "number"
// The if-condition is always true
</code>```

Such errors are pretty common and can be hard to detect in programming languages that allow variable assignments within conditionals.

Now, consider reversing the order of your condition :

```<code>if (42 == number) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42
</code>```

The behavior of 42 == number is exactly the same as the behavior of number == 42.

However, if make the same mistake mentioned hereabove (you forget there should be a double = and you just write a single = instead), the behavior is no longer the same :

```<code>if (42 = number) { /* ... */ }
// This produces an error
</code>```

Therefore, some people prefer to reverse the order of their conditions, as it makes a common error much easier to detect. Such "reversed" conditions are known as Yoda conditions.

In programming languages that do not allow variable assignments within conditionals (eg. Python or Swift), there is no advantage whatsover to using Yoda conditions, and it's typically discouraged to use them. In other languages (eg. JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it's still largely a matter of your personal preference or whatever coding standards your project require.

Wordpress & Symfony are two popular open source projects where Yoda conditions are part of the coding standards.

Body:
Consider you want this :

if (number == 42) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42

Now, imagine you forget there should be a double = and you just write a single = instead :

if (number = 42) { /* ... */ }
// This assigns 42 to "number"
// The if-condition is always true

Such errors are pretty common and can be hard to detect in programming languages that allow variable assignments within conditionals.

Now, consider reversing the order of your condition :

if (42 == number) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42

The behavior of 42 == number is exactly the same as the behavior of number == 42.

However, if make the same mistake mentioned hereabove (you forget there should be a double = and you just write a single = instead), the behavior is no longer the same :

if (42 = number) { /* ... */ }
// This produces an error

Therefore, some people prefer to reverse the order of their conditions, as it makes a common error much easier to detect. Such "reversed" conditions are known as Yoda conditions.

In programming languages that do not allow variable assignments within conditionals (eg. Python or Swift), there is no advantage whatsover to using Yoda conditions, and it's typically discouraged to use them. In other languages (eg. JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it's still largely a matter of your personal preference or whatever coding standards your project require.

Wordpress & Symfony are two popular open source projects where Yoda conditions are part of the coding standards.


问:
Trying to replicate GridLayout column alignment with ConstraintLayout
I'm new to ConstraintLayout, and I'm trying to replicate the same grid behavior offered by GridLayout with ConstraintLayout.

Specifically, I want to design a two columns grid. The first column width should be as narrow as possible, while the second column should take all the remaining horizontal space. Of course, the second column should be just to the right of the first column, or rather, to the widest view on the first column.

I don't know how can I replicate this last requirement with ConstraintLayout. I don't want to use a Gridline between the two columns, because the first column should not have a fixed nor a percentage width, but rather be as wide as the widest of its view.

At https://gist.github.com/venator85/499dd82f47b3efbbed7a1e9e1ca1412d I prepared a layout example, and the corresponding preview, showing a GridLayout that implements what I want. The first two ConstraintLayout attempts in that layout show C1 and D1 be aligned to B1, and C2 and D2 be aligned to B2. When B2 is narrower than A2, A1 and C1 will overlap.

Any help?

Thanks

答:
Update

The accepted answer is correct. When I answered this on Mar 2017, this was the only option. Two months later, Google introduced barriers.

I don't think it is possible to perform purely with one ConstraintLayout container at this time. I hope that in the future Google will add something like group_id or some other way to calculate layout with "align to group".

In the mean time, I suggest you use ConstraintLayout containers inside ConstraintLayout.
This is how I implemented this:

To make the rows "grid" like, I used "ConstraintLayout Chains". Number of rows in each ConstraintLayout chain must be identical, so the auto distribution will align rows correctly. (Though they can stay empty or hidden if not used).

The xml gist

ContentLicense: CC BY-SA 4.0


问:
JQuery .attr tag not working
I don't understand why .attr() will not change the background-color of div "outline" to red.

HTML CODE:

```<code><div id="outline"></div>
</code>```

CSS CODE:

```<code>#outline {
height: 300px;
width: 300px;
background-color: black;
}
</code>```

JAVASCRIPT (JQUERY) CODE:

```<code>$("#outline").attr('background-color', 'blue');
</code>```

答:
background-color isn't an attribute, it's a css property.

Use :

```<code>$("#outline").css('backgroundColor', 'blue');
</code>```

Title: JQuery .attr tag not working

Body:
I don't understand why .attr() will not change the background-color of div "outline" to red.

HTML CODE:

CSS CODE:

#outline {
height: 300px;
width: 300px;
background-color: black;
}

JAVASCRIPT (JQUERY) CODE:

$("#outline").attr('background-color', 'blue');

Body:
background-color isn't an attribute, it's a css property.

Use :

$("#outline").css('backgroundColor', 'blue');


问:
Jquery function optimalize (slick slider)
I made a slick slider with some filter functions.

Everything works, but my functions for the filters are not as efficient as I want them to be.
Does anyone know of a way to make it efficient?

```<code>// init Isotope
var slickoptions = {
      rows: 2,
      dots: true,
      appendDots: $('.slick-nav'),
      appendArrows: $('.slick-nav'),
      accessibility: true,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      infinite: false,
}

$(document).ready(function () {
  $('.slider2').slick(slickoptions);

  var slider = $('.slider2');
  var allSlides = $('.slick-slide > div > *').clone();
  var trigger = $('js-filter');

  $('.filter-all').on('click', function () {
        $('.active').removeClass('active');
        $('.filter-all').addClass('active');
        var filterSlides = allSlides.filter('*');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
  });

    $('.js-filter[data-filter=".category-website"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-website"]').addClass('active');
        var filterSlides = allSlides.filter('.category-website');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-webshop"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-webshop"]').addClass('active');
        var filterSlides = allSlides.filter('.category-webshop');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-drukwerk"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-drukwerk"]').addClass('active');
        var filterSlides = allSlides.filter('.category-drukwerk');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-videos"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-videos"]').addClass('active');
        var filterSlides = allSlides.filter('.category-videos');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-bestaat-niet"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-bestaat-niet"]').addClass('active');
        var filterSlides = allSlides.filter('.category-bestaat-niet');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

});
</code>```

http://codepen.io/Pondake/pen/vxVQam

答:
Try this.

// init Isotope
var slickoptions = {
      rows: 2,
      dots: true,
      appendDots: $('.slick-nav'),
      appendArrows: $('.slick-nav'),
      accessibility: true,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      infinite: false,
}

$(document).ready(function () {
  $('.slider2').slick(slickoptions);

  var slider = $('.slider2');
  var allSlides = $('.slick-slide > div > *').clone();
  var trigger = $('js-filter');

  var ClassFilter = function (object, item) {
      this.object = object;
      this.item = item;

      this.filterFunc = function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter="'+this.item+'"]').addClass('active');
        var filterSlides = allSlides.filter(this.item);
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
      }
  }

  jQuery('.js-filter').on('click', function (e) {
    var attr = jQuery(this).attr('data-filter')
    var newFilter = new ClassFilter(this, attr);
        newFilter.filterFunc();
  });

});

    ```

Body:
I made a slick slider with some filter functions.

Everything works, but my functions for the filters are not as efficient as I want them to be.
Does anyone know of a way to make it efficient?

// init Isotope
var slickoptions = {
      rows: 2,
      dots: true,
      appendDots: $('.slick-nav'),
      appendArrows: $('.slick-nav'),
      accessibility: true,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      infinite: false,
}

$(document).ready(function () {
  $('.slider2').slick(slickoptions);

  var slider = $('.slider2');
  var allSlides = $('.slick-slide > div > *').clone();
  var trigger = $('js-filter');

  $('.filter-all').on('click', function () {
        $('.active').removeClass('active');
        $('.filter-all').addClass('active');
        var filterSlides = allSlides.filter('*');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
  });

    $('.js-filter[data-filter=".category-website"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-website"]').addClass('active');
        var filterSlides = allSlides.filter('.category-website');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-webshop"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-webshop"]').addClass('active');
        var filterSlides = allSlides.filter('.category-webshop');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-drukwerk"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-drukwerk"]').addClass('active');
        var filterSlides = allSlides.filter('.category-drukwerk');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-videos"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-videos"]').addClass('active');
        var filterSlides = allSlides.filter('.category-videos');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-bestaat-niet"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-bestaat-niet"]').addClass('active');
        var filterSlides = allSlides.filter('.category-bestaat-niet');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

});

http://codepen.io/Pondake/pen/vxVQam


问:
SQL Report Builder: Return only date for available parameter values
I have a SQL Server report which prompts for a import date. Later I pass this date to a procedure to get the data (dbo.spGetData). My procedure to get the available import dates looks like this:

```<code>ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CONVERT(DATE, i.ImportDate) ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END
</code>```

In the report I've added this SP as a new dataset and selected it as "Available Values" for the Date/Time parameter @importDate to get a dropdown. So far, so good. The problem is that the time is also included in the result set when I leave it like this:

```<code>+---------------------+
| ImportDate          |
+---------------------+
| 29.03.2017 00:00:00 |
| 25.03.2017 00:00:00 |
| ...                 |
+---------------------+
</code>```

I couldn't find any option to change the format of the parameter prompt. I even tried to use the SELECT query directly in the query designer of the dataset but I get the same results.

Do I really have to use it as text parameter and then reconvert it to DATE in the procedure dbo.spGetData or is there any other solution?

答:
Leave the ImportDate column in the stored procedure as DATE datatype.
Go to your dataset in SSRS and click on 'Fields'.
Add a new calculated field, name it ImportDateLabel and set it as the following expression:

```<code>=Format(Fields!ImportDate.Value,"dd/mm/yyyy")
</code>```

Now go to your Paramater, click on 'Available values' and change the 'Label field' to reference the new ImportDateLabel field. Leave the 'Value field' pointing to the ImportDate field.

Body:
I have a SQL Server report which prompts for a import date. Later I pass this date to a procedure to get the data (dbo.spGetData). My procedure to get the available import dates looks like this:

ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CONVERT(DATE, i.ImportDate) ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END

In the report I've added this SP as a new dataset and selected it as "Available Values" for the Date/Time parameter @importDate to get a dropdown. So far, so good. The problem is that the time is also included in the result set when I leave it like this:

+---------------------+
| ImportDate          |
+---------------------+
| 29.03.2017 00:00:00 |
| 25.03.2017 00:00:00 |
| ...                 |
+---------------------+

I couldn't find any option to change the format of the parameter prompt. I even tried to use the SELECT query directly in the query designer of the dataset but I get the same results.

Do I really have to use it as text parameter and then reconvert it to DATE in the procedure dbo.spGetData or is there any other solution?

Body:
Leave the ImportDate column in the stored procedure as DATE datatype.
Go to your dataset in SSRS and click on 'Fields'.
Add a new calculated field, name it ImportDateLabel and set it as the following expression:

=Format(Fields!ImportDate.Value,"dd/mm/yyyy")

Now go to your Paramater, click on 'Available values' and change the 'Label field' to reference the new ImportDateLabel field. Leave the 'Value field' pointing to the ImportDate field.


问:
Render v-for list false order (new added items first) Vue.js
I am new to vue.js (2) and I am working on a mini twitter platform. Currently I am testing to add a new tweet + name to an array. All that is going well except the new added items are placed below of the v-for list. That is standard of course, But I would like to place the new added items on top of the list, so the new tweets are visible at the top.

I don't know how I could achieve this. I am reading the docs but that doesn't help unfortunately.

HTML

```<code> <transition-group name="list">

    <div class="social-item " v-for="message in messages" :key="message">

        <img class="img-responsive img-full" :src="message.image">

        <p>
            {{ message.message }}
        </p>

        <div class="platform-twitter" v-if="message.platform == 'fb'">

            <strong class="name facebook">
                <a :href="message.adress" target="_blank">
                    <i class="fa fa-facebook"></i> {{ message.name }}
                </a>
            </strong>

            <div class="stats" v-if="message.fblike > 0 || message.share > 0">
               <i class="fa fa-thumbs-up"></i> {{ message.fblike }}
               <i class="fa fa-share"></i> {{ message.share }}
            </div>

        </div>

        <div class="platform-twitter" v-if="message.platform == 'tw'">

            <strong class="name twitter">
                <a :href="message.adress" target="_blank">
                    <i class="fa fa-twitter"></i> {{ message.name }}
                </a>
            </strong>

            <div class="stats" v-if="message.retweets > 0 || message.likes > 0">
                <i class="fa fa-retweet"></i> {{ message.retweets }}
                <i class="fa fa-star"></i> {{ message.likes }}
            </div>

        </div>

    </div>

    </transition-group>
</code>```

JS

```<code>    new Vue({

        el: '#app',

        data: {

            message: {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'},

            messages: [

                {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'tw'},
                {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'fb'}

            ]

        },

        methods: {
        addMessage: function() {
            if(this.message.message){
                this.messages.push(this.message);
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
            }
        }

    }

});
</code>```

I've created a simple https://jsfiddle.net/25d813c4/ with the part of my application.

答:
Because push appends items at last.

You can use unshift instead:

```<code>this.messages.unshift(this.message)
</code>```

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

Body:
I am new to vue.js (2) and I am working on a mini twitter platform. Currently I am testing to add a new tweet + name to an array. All that is going well except the new added items are placed below of the v-for list. That is standard of course, But I would like to place the new added items on top of the list, so the new tweets are visible at the top.

I don't know how I could achieve this. I am reading the docs but that doesn't help unfortunately.

HTML

 <transition-group name="list">

            {{ message.message }}

                     {{ message.name }}

 0 || message.share > 0">
                {{ message.fblike }}
                {{ message.share }}

                     {{ message.name }}

 0 || message.likes > 0">
                 {{ message.retweets }}
                 {{ message.likes }}

    </transition-group>

JS

    new Vue({

        el: '#app',

        data: {

            message: {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'},

            messages: [

                {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'tw'},
                {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'fb'}

            ]

        },

        methods: {
        addMessage: function() {
            if(this.message.message){
                this.messages.push(this.message);
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
            }
        }

    }

});

I've created a simple https://jsfiddle.net/25d813c4/ with the part of my application.

Body:
Because push appends items at last.

You can use unshift instead:

this.messages.unshift(this.message)

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift


问:
I want to store date in dd-MMM-yyyy (17-MAR-2017) in string say X.
in one string say X. Now I want to split this string in another string that is, say y= x.split , such that y[0] = 17, y[1] = MAR y[2] = 2017. How to write prog for this in Java. </p>

答:
Try splitting:-

```<code>String s = "17-MAR-2017";
String array[] = s.split("-");
System.out.println(array[0]); //Prints 17. Same way, print others.
</code>```

Body:
Try splitting:-

String s = "17-MAR-2017";
String array[] = s.split("-");
System.out.println(array[0]); //Prints 17. Same way, print others.


问:
AjaxControlKit in .NET 2.0 from Visual Studio 2008
I am working on a project which was developed in Visual Studio 2005 (.NET 2.0). I have Visual Studio 2008 and on opening the solution the files are converted to older framework.

But the project uses a AjaxControlKit which I guess is not available by default in ASP.NET 2.0 and hence it throws an error that a reference/library is missing on conversion and compiling it in 2008.

Any library/ reference can be added to solve this ? where can I find it?

答: Are you getting the error during the conversion process or when you attempt to compile the converted application?  Have you tried removing the reference and re-adding it?  Removing it before conversion, upgrading to .NET 3.5 and adding the newer, 3.5-dependent version back in?</p>

OwnerDisplayName: tvanfosson


问:
Using a string to define Numpy array slice
I have an image array that has an X times Y shape of 2048x2088. The x-axis has two 20 pixel regions, one at the start and one at the end, which are used to calibrate the main image area. To access these regions I can slice the array like so:

```<code>prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]
</code>```

My question is how to define these areas in a configuration file in order the generalise this slice for other cameras which may have different prescan and overscan areas and therefore require a different slice.

Ideally, something like the strings below would allow a simple representation in the camera specific configuration file, but I am not sure how to translate these strings into array slices.

```<code>prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"
</code>```

Maybe there is something obvious that I am missing?

Thanks!

答:
You can parse the string and use slice. The following generator expression within tuple will create the slice objects for you:

```<code>tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))
</code>```

Demo:

```<code>In [5]: import numpy as np

In [6]:

In [6]: a = np.arange(20).reshape(4, 5)

In [7]: a
Out[7]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [8]:

In [8]: prescan_area_def = "[:, :3]"

In [9]: a[:, :3]
Out[9]:
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])

In [10]: indices = tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))

In [11]: indices
Out[11]: (slice(None, None, None), slice(None, 3, None))

In [12]: a[indices]
Out[12]:
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])
</code>```

Body:
I have an image array that has an X times Y shape of 2048x2088. The x-axis has two 20 pixel regions, one at the start and one at the end, which are used to calibrate the main image area. To access these regions I can slice the array like so:

prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]

My question is how to define these areas in a configuration file in order the generalise this slice for other cameras which may have different prescan and overscan areas and therefore require a different slice.

Ideally, something like the strings below would allow a simple representation in the camera specific configuration file, but I am not sure how to translate these strings into array slices.

prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"

Maybe there is something obvious that I am missing?

Thanks!

Body:
You can parse the string and use slice. The following generator expression within tuple will create the slice objects for you:

tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))

Demo:

In [5]: import numpy as np

In [6]:

In [6]: a = np.arange(20).reshape(4, 5)

In [7]: a
Out[7]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [8]:

In [8]: prescan_area_def = "[:, :3]"

In [9]: a[:, :3]
Out[9]:
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])

In [10]: indices = tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))

In [11]: indices
Out[11]: (slice(None, None, None), slice(None, 3, None))

In [12]: a[indices]
Out[12]:
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])


问:
ArangoDB: Search for a property and filter multiple values in the path
I want to do an expand and search for nodes with a certain label. But i want also to filter the nodes of the path with a certain label.
the label column contains values like "Entity;Person", "Entity;Organization"

What i have got so far

```<code>LET source = (FOR x IN Entity FILTER x.objectID == @nodeId
    Return x)[0]
FOR node, edge, path IN 1..@maxLength ANY source GRAPH @graph
        FILTER CONTAINS(node.label,  @search)
        AND node != source
        AND (CONTAINS (path.vertices[*].label, "Person") OR CONTAINS (path.vertices[*].label, "Organization") OR CONTAINS (path.vertices[*].label, "Incident"))
        LIMIT @maxPaths
        RETURN {node,path}
</code>```

Problems

The filter is on all nodes of the path. i would like to filter on the path without source and destination.

The contains/or part is really ugly. is there a better way to filter for multiple values?

答:
1) With path.vertices[* LIMIT 1,LENGTH(path.vertices)-2] you ignore the first (source) and the last (destination) entry in the vertices array.

2) You can iterate over the searched labels in a subquery and check if one exists in the vertices of the path. If you find one you exit the subquery with LIMIT 1 RETURN 1 which returns you an array of length 1 otherwise you get an array of length 0. Then you can filter on these length.

```<code>LET labels = ["Person","Organization","Incident"]

FOR source IN Entity FILTER source.objectID == @nodeId
LIMIT 1
FOR node, edge, path IN 1..@maxLength ANY source GRAPH @graph
  FILTER CONTAINS(node.label,  @search)
  AND node != source
  AND LENGTH(FOR i IN labels
    FILTER CONTAINS(path.vertices[* LIMIT 1,LENGTH(path.vertices)-2].label, i)
    LIMIT 1
    RETURN 1) == 1
  LIMIT @maxPaths
  RETURN {node,path}
</code>```

Node: I would use labels as a bind parameter. So you can extend your label logic without changeing the query.

Body:
I want to do an expand and search for nodes with a certain label. But i want also to filter the nodes of the path with a certain label.
the label column contains values like "Entity;Person", "Entity;Organization"

What i have got so far

LET source = (FOR x IN Entity FILTER x.objectID == @nodeId
    Return x)[0]
FOR node, edge, path IN 1..@maxLength ANY source GRAPH @graph
        FILTER CONTAINS(node.label,  @search)
        AND node != source
        AND (CONTAINS (path.vertices[*].label, "Person") OR CONTAINS (path.vertices[*].label, "Organization") OR CONTAINS (path.vertices[*].label, "Incident"))
        LIMIT @maxPaths
        RETURN {node,path}

Problems

The filter is on all nodes of the path. i would like to filter on the path without source and destination.

The contains/or part is really ugly. is there a better way to filter for multiple values?

Body:
1) With path.vertices[* LIMIT 1,LENGTH(path.vertices)-2] you ignore the first (source) and the last (destination) entry in the vertices array.

2) You can iterate over the searched labels in a subquery and check if one exists in the vertices of the path. If you find one you exit the subquery with LIMIT 1 RETURN 1 which returns you an array of length 1 otherwise you get an array of length 0. Then you can filter on these length.

LET labels = ["Person","Organization","Incident"]

FOR source IN Entity FILTER source.objectID == @nodeId
LIMIT 1
FOR node, edge, path IN 1..@maxLength ANY source GRAPH @graph
  FILTER CONTAINS(node.label,  @search)
  AND node != source
  AND LENGTH(FOR i IN labels
    FILTER CONTAINS(path.vertices[* LIMIT 1,LENGTH(path.vertices)-2].label, i)
    LIMIT 1
    RETURN 1) == 1
  LIMIT @maxPaths
  RETURN {node,path}

Node: I would use labels as a bind parameter. So you can extend your label logic without changeing the query.


答:
you can do something like:

```<code>var1="img"
prescan_area_def = "[:, :20]"
</code>```

and to use eval

```<code>prescan_area=eval(var1+prescan_area_def)
</code>```

Title: Using a string to define Numpy array slice

Body:
you can do something like:

var1="img"
prescan_area_def = "[:, :20]"

and to use eval

prescan_area=eval(var1+prescan_area_def)


问:
jQuery checking if a link is clicked
I have created a burger menu using jQuery. And I have also created another jQuery function that automatically scrolls down the page to the anchor position when a link is clicked. Now what I need the burger menu function to do is close when one of the auto_close class links is clicked.

```<code><nav>
            <img class="logo_animated" src="images/popsies.svg">

            <ul id="height">
                <li class="auto_close"><a href="#welcomeAnchor">Welcome</a></li>
                <li class="auto_close"><a href="#menuAnchor">Menu</a></li>
                <li class="auto_close"><a href="#timesAnchor">Opening Times</a></li>
                <li id="mob_icons">
                    <a href=""><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>
                    <a href=""><i class="fa fa-twitter-square fa-2x" aria-hidden="true"></i></a>
                </li>
                <li class="mob_contact">Tel: 0113 0000000</li>
                <li class="mob_contact">Email: example@yahoo.co.uk</li>
            </ul>
        </nav>
</code>```

my burger menu function:

```<code>$(document).ready(function(){
$(".burger-button").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});
</code>```

答:
Assuming that the show class reveals the burger menu, remove it if any of the a elements was clicked.

```<code>$("#height li a").click(function() {
  $(".burger-button").removeClass("show");
});
</code>```

Title: jQuery checking if a link is clicked

Body:
I have created a burger menu using jQuery. And I have also created another jQuery function that automatically scrolls down the page to the anchor position when a link is clicked. Now what I need the burger menu function to do is close when one of the auto_close class links is clicked.

Welcome

Menu

Opening Times

Tel: 0113 0000000

Email: example@yahoo.co.uk

my burger menu function:

$(document).ready(function(){
$(".burger-button").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});

Body:
Assuming that the show class reveals the burger menu, remove it if any of the a elements was clicked.

$("#height li a").click(function() {
  $(".burger-button").removeClass("show");
});


答:
since you are using toggle you can just add a reference to the .auto_close a links like so:

```<code>$(document).ready(function(){
$(".burger-button,.auto_close a").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});
</code>```

Title: jQuery checking if a link is clicked

Body:
since you are using toggle you can just add a reference to the .auto_close a links like so:

$(document).ready(function(){
$(".burger-button,.auto_close a").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});


问:
How to extract all alphabetical characters from a string and store as a 1-dim array?
I have a variable $var = "My name's Ankit". I want to store all the English alphabet characters of $var into an array $charvar. I know that I can use a simple for loop over the entire length of $var and array_push the characters if they are English characters else ignore. However, I wanted to know if PHP provides some function which can do this.
What I want in $charvar is:

```<code>Array
(
        [0] => M
        [1] => y
        [2] => n
        [3] => a
        [4] => m
        [5] => e
        [6] => s
        [7] => A
        [8] => n
        [9] => k
        [10] => i
        [11] => t
)
</code>```

答:
You can use this method to strip away all characters and leave only those you want. Let us assume $s is where the string is stored. To select only alphabets, try;

```<code>$result = preg_replace("/[^a-zA-Z]+/", "", $s);
</code>```

To add numbers to the mix, try;

```<code>$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
</code>```

You can play around with it for any other characters.

For your case;

```<code>$var = "My name's Ankit"
$charvar = preg_replace("/[^a-zA-Z]+/", "", $var);
</code>```

Let me know if it helps.

Body:
I have a variable $var = "My name's Ankit". I want to store all the English alphabet characters of $var into an array $charvar. I know that I can use a simple for loop over the entire length of $var and array_push the characters if they are English characters else ignore. However, I wanted to know if PHP provides some function which can do this.
What I want in $charvar is:

Array
(
        [0] => M
        [1] => y
        [2] => n
        [3] => a
        [4] => m
        [5] => e
        [6] => s
        [7] => A
        [8] => n
        [9] => k
        [10] => i
        [11] => t
)

Body:
You can use this method to strip away all characters and leave only those you want. Let us assume $s is where the string is stored. To select only alphabets, try;

$result = preg_replace("/[^a-zA-Z]+/", "", $s);

To add numbers to the mix, try;

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

You can play around with it for any other characters.

For your case;

$var = "My name's Ankit"
$charvar = preg_replace("/[^a-zA-Z]+/", "", $var);

Let me know if it helps.