问:
Parse JSON Response Array using ForEach component in WSO2 ESB
I have a requirement to parse JSON response which contain array of products(P1,P2,P3,etc.). Each product contains multiple information like name, type, cost, etc.

I need to read each product one by one and append additional data got from the another service into an new JSON output. I am thinking of using ForEach component of WSO2 ESB to iterate each product one by one.

Problem is that ForEach component uses ForEachExpression which expects XML expression in the configuration.

Please suggest on the method to parse array of JSON response one by one in WSO2 ESB.

/Abhishek

答:
Can use both Iterate or ForEach mediator for iterating the JSON array, since both are content aware mediators and support JSON.

Which one to use depends upon the specific usecase as Iterate provides the capability to use call / callout / send mediators in the sequence whereas ForEach doesn´t allow it.

For the below given sample JSON request, the following iteration works and the JSON array and objects can be referred like the same.

```<code>{
   "products":[
      {
         "product":{
            "id":"1234",
            "size":"20",
            "quantity":"1",
            "price":"990",
            "type":"Electronics",
            "store":{
               "id":"001"
            }
         }
      }
   ]
}

<iterate expression="//products" id="PRD_ITR">
    <target>
      <sequence>
        <sequence key="Product_Enrich_Sequence_s"/>
        <!-- For example, Switching sequence based on the product type -->
        <switch source="//products/product/type">
          <case regex="Computer">
            <sequence key="Computer_Product_Enrich_Sequence_s"/>
          </case>
          <case regex="Mobile">
            <sequence key="Mobile_Product_Enrich_Sequence_s"/>
          </case>
          <case regex="Grocery">
            <sequence key="GR_Product_Enrich_Sequence_s"/>
          </case>
          <default>
            <!-- default stuff --!>
          </default>
        </switch>
      </sequence>
    </target>
  </iterate>
</code>```

FYR

https://docs.wso2.com/display/ESB490/Iterate+Mediator

https://docs.wso2.com/display/ESB490/ForEach+Mediator

Note: tested in WSO2 ESB 4.9.0

Body:
Can use both Iterate or ForEach mediator for iterating the JSON array, since both are content aware mediators and support JSON.

Which one to use depends upon the specific usecase as Iterate provides the capability to use call / callout / send mediators in the sequence whereas ForEach doesn´t allow it.

For the below given sample JSON request, the following iteration works and the JSON array and objects can be referred like the same.

{
   "products":[
      {
         "product":{
            "id":"1234",
            "size":"20",
            "quantity":"1",
            "price":"990",
            "type":"Electronics",
            "store":{
               "id":"001"
            }
         }
      }
   ]
}

<iterate expression="//products" id="PRD_ITR">
    <target>
      <sequence>
        <sequence key="Product_Enrich_Sequence_s"/>
        <!-- For example, Switching sequence based on the product type -->
        <switch source="//products/product/type">
          <case regex="Computer">
            <sequence key="Computer_Product_Enrich_Sequence_s"/>
          </case>
          <case regex="Mobile">
            <sequence key="Mobile_Product_Enrich_Sequence_s"/>
          </case>
          <case regex="Grocery">
            <sequence key="GR_Product_Enrich_Sequence_s"/>
          </case>
          <default>
            <!-- default stuff --!>
          </default>
        </switch>
      </sequence>
    </target>
  </iterate>

FYR

https://docs.wso2.com/display/ESB490/Iterate+Mediator

https://docs.wso2.com/display/ESB490/ForEach+Mediator

Note: tested in WSO2 ESB 4.9.0


来源: stackexchange

问:
Angular 2 - Expandable table row containing another table
I'm looking for a datatable which has expandable rows containing other rows (basically a table within a table).

I have found an PrimeNG example but this only displays more information about the same row when it's expanded.  There seems to be a few AngularJS example but I can't find any for Angular 2.

This is another example of what I'm looking for on Bootply, but when I use it the rows don't expand.  I have the bootstrap stylesheet imported in index.html and I'm able to use other bootstrap features.

答:
You can add a primeng datatable within the rowexpansion template with the value of the datatable set to a property (usually an array) of a row.

```<code><ng-template let-cp pTemplate="rowexpansion">
      <p-dataTable *ngIf="cp.associated_seasons" #dtSeasons [value]="cp.associated_seasons">
      </p-dataTable>
</ng-template>
</code>```

here "cp" is your reference to a row in the main data table and cp.associated_seasons refers to a property of the row called "associated_seasons".

ContentLicense: CC BY-SA 3.0

Body:
You can add a primeng datatable within the rowexpansion template with the value of the datatable set to a property (usually an array) of a row.

<ng-template let-cp pTemplate="rowexpansion">
      <p-dataTable *ngIf="cp.associated_seasons" #dtSeasons [value]="cp.associated_seasons">
      </p-dataTable>
</ng-template>

here "cp" is your reference to a row in the main data table and cp.associated_seasons refers to a property of the row called "associated_seasons".


问:
how to stop recursion and/or restart the current function with updated variables
I've got two arrays which are updating themselves and each other based on criteria (it is way longer to describe than I suspect the solution is).

What I end up with is a function which calls itself within a while loop. As you can imagine, this causes a ridiculous amount of recursion.

Here's an example (keeping it short)

```
var buildArray=firstFunction(new Array(), existingArray)

function firstFunction(thisArray, existingArray){
     for(test1=0; test1<existingArray.length; test1++){
         if(existingArray[test1][3]=='2'){
           secondFunction(thisArray, existingArray, test1);
        }
     }

function secondFunction(thisArray, existingArray, t1){
       for(test2=0; test2<thisArray.length; test2++){
          if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
            // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
     return firstFunction(new Array(), existingArray);

              // check that the value isn't already in the 'thisArray'
   var check= new Array(existingArray[test1]);
  else if (jQuery.inArray(check, thisArray==-1){
         // value isn't in the new array, so add it
        thisArray.push(check);
       // thisArray has changed. need to restart the the second function
       secondFunction(thisArray,existingArray);
     }

   }
 }

}
}
```

I was hoping that

```return secondFunction(thisArray, existingArray);
```

would reset and restart the function, but apparently that isn't happening.

Is there a way to stop the current function and loops and restart with the updated variables?

答:
i do not get what you are trying yo do, however based on the fact that return stop the execution in the secondFunction, and thisArray is never changed,
you can add a loop to the firstFunction:

```<code>function firstFunction(thisArray, existingArray){
    var restart = true;
    while(restart)
    {
        restart = false;
         for(test1=0; !restart && test1<existingArray.length; test1++){
             if(existingArray[test1][3]=='2'){
               if(secondFunction(thisArray, existingArray, test1))
               {
                restart = true;
               }
            }
         }
    }
</code>```

and in the secondFunction instead of returning the array return true:

```<code>  if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
    // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
 return true;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've got two arrays which are updating themselves and each other based on criteria (it is way longer to describe than I suspect the solution is).

What I end up with is a function which calls itself within a while loop. As you can imagine, this causes a ridiculous amount of recursion.

Here's an example (keeping it short)

var buildArray=firstFunction(new Array(), existingArray)

function firstFunction(thisArray, existingArray){
     for(test1=0; test1<existingArray.length; test1++){
         if(existingArray[test1][3]=='2'){
           secondFunction(thisArray, existingArray, test1);
        }
     }

function secondFunction(thisArray, existingArray, t1){
       for(test2=0; test2<thisArray.length; test2++){
          if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
            // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
     return firstFunction(new Array(), existingArray);

              // check that the value isn't already in the 'thisArray'
   var check= new Array(existingArray[test1]);
  else if (jQuery.inArray(check, thisArray==-1){
         // value isn't in the new array, so add it
        thisArray.push(check);
       // thisArray has changed. need to restart the the second function
       secondFunction(thisArray,existingArray);
     }

   }
 }

}
}

I was hoping that

return secondFunction(thisArray, existingArray);

would reset and restart the function, but apparently that isn't happening.

Is there a way to stop the current function and loops and restart with the updated variables?

Body:
i do not get what you are trying yo do, however based on the fact that return stop the execution in the secondFunction, and thisArray is never changed,
you can add a loop to the firstFunction:

function firstFunction(thisArray, existingArray){
    var restart = true;
    while(restart)
    {
        restart = false;
         for(test1=0; !restart && test1<existingArray.length; test1++){
             if(existingArray[test1][3]=='2'){
               if(secondFunction(thisArray, existingArray, test1))
               {
                restart = true;
               }
            }
         }
    }

and in the secondFunction instead of returning the array return true:

  if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
    // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
 return true;


问:
Pause jQuery On Hover (Mouse Over)
I looked around but didn't find anything, please see below for my code.

With that in mind, I just need the ability to be able to pause the animation on mouse hover.

Any assistance is gratefully appreciated!

(function ( $ ) {
 $.fn.textSlider = function ( options ) {

  /* Default settings */
  var settings = $.extend(
   {
    timeout: 2000,
    slideTime: 750,
   },
   options
  );

  var nextItem;

  var currentItem = 0;
  var count = 0;

  this.children('.slider-item').each(
   function ()
   {
    $(this).addClass( 'slide-' + ( count ) )
     .css(
      {
       //opacity:    0,
       //paddingTop: '100px',
       //paddingBottom: '0px'
      }
     );
    $(this).hide();
    count++;
   }
  );

  function firstSlide ()
  {
   $('.slide-' + currentItem ).show().animate({
    //paddingTop: '0px', paddingBottom: '50px',
    opacity: 1 }, settings.slideTime);

   setTimeout ( transition, settings.timeout );
  }

  function transition ()
  {
   nextItem = parseInt ( currentItem + 1 );

   if ( nextItem >= count )
    nextItem = 0;

   $('.slide-' + currentItem ).animate({
    //paddingTop: '100px', paddingBottom: '0px',
    opacity: 0 }, settings.slideTime, function () {
     $(this).hide();
     $('.slide-' + nextItem ).show().animate({
      //paddingTop: '0px', paddingBottom: '50px',
      opacity: 1 }, settings.slideTime);
   });

   currentItem = nextItem;
   setTimeout ( transition, settings.timeout );
  }
  return firstSlide ();
 };
}( jQuery ));

// Start the Text Slider
 $('.slide').textSlider({
  timeout: 5000,
  slideTime: 650,
  loop: 1
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Main Message & Text */
.main-message {
 font-size: 150%;
 font-weight: bold;
 padding-bottom: 20px;
 margin-left: 20px;
}
.main-text {
 font-size: 110%;
 margin-left: 20px;
}</code>```

Test 1

Sub text here 1

Test 2

Sub text here 2

Test 3

Sub text here 3

 ```

答:
In your function transition() {... you can add at the beginning:

```<code>// if mouse is hover element call again the settimeout...
if ($('.slide-' + currentItem + ':hover').length != 0) {
    setTimeout(transition, settings.timeout);
    return;
}
</code>```

A different solution can be based on .hover(), adding the following event handler:

```<code>this.children('.slider-item').hover(
        function (e) {
            $(this).addClass('hover');
        },
        function (e) {
            $(this).removeClass('hover');
        }
);
</code>```

and, so, changing the first suggested code with:

```<code>// if element has hover class call again the settimeout...
if ($('.slide-' + currentItem + '.hover').length != 0) {
    setTimeout(transition, settings.timeout);
    return;
}
</code>```

The snippet:

(function ($) {
    $.fn.textSlider = function (options) {

        /* Default settings */
        var settings = $.extend(
                {
                    timeout: 2000,
                    slideTime: 750,
                },
                options
        );

        var nextItem;

        var currentItem = 0;
        var count = 0;

        this.children('.slider-item').each(function () {
                    $(this).addClass('slide-' + ( count ))
                            .css({
                                //opacity:    0,
                                //paddingTop: '100px',
                                //paddingBottom: '0px'
                            }
                    );
                    $(this).hide();
                    count++;
                }
        );

        this.children('.slider-item').hover(
                function (e) {
                    $(this).addClass('hover');
                },
                function (e) {
                    $(this).removeClass('hover');
                }
        );

        function firstSlide() {
            $('.slide-' + currentItem).show().animate({
                //paddingTop: '0px', paddingBottom: '50px',
                opacity: 1
            }, settings.slideTime);

            setTimeout(transition, settings.timeout);
        }

        function transition() {
            if ($('.slide-' + currentItem + '.hover').length != 0) {
                setTimeout(transition, settings.timeout);
                return;
            }
            nextItem = parseInt(currentItem + 1);

            if (nextItem >= count)
                nextItem = 0;

            $('.slide-' + currentItem).animate({
                //paddingTop: '100px', paddingBottom: '0px',
                opacity: 0
            }, settings.slideTime, function () {
                $(this).hide();
                $('.slide-' + nextItem).show().animate({
                    //paddingTop: '0px', paddingBottom: '50px',
                    opacity: 1
                }, settings.slideTime);
            });

            currentItem = nextItem;
            setTimeout(transition, settings.timeout);
        }

        return firstSlide();
    };
}(jQuery));

 // Start the Text Slider
$('.slide').textSlider({
    timeout: 1000,
    slideTime: 350,
    loop: 1
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-message {
    font-size: 150%;
    font-weight: bold;
    padding-bottom: 20px;
    margin-left: 20px;
}

.main-text {
    font-size: 110%;
    margin-left: 20px;
}</code>```

Test 1

Sub text here 1

Test 2

Sub text here 2

Test 3

Sub text here 3

```

Title: Pause jQuery On Hover (Mouse Over)

Body:
I looked around but didn't find anything, please see below for my code.

With that in mind, I just need the ability to be able to pause the animation on mouse hover.

Any assistance is gratefully appreciated!

(function ( $ ) {
 $.fn.textSlider = function ( options ) {

  /* Default settings */
  var settings = $.extend(
   {
    timeout: 2000,
    slideTime: 750,
   },
   options
  );

  var nextItem;

  var currentItem = 0;
  var count = 0;

  this.children('.slider-item').each(
   function ()
   {
    $(this).addClass( 'slide-' + ( count ) )
     .css(
      {
       //opacity:    0,
       //paddingTop: '100px',
       //paddingBottom: '0px'
      }
     );
    $(this).hide();
    count++;
   }
  );

  function firstSlide ()
  {
   $('.slide-' + currentItem ).show().animate({
    //paddingTop: '0px', paddingBottom: '50px',
    opacity: 1 }, settings.slideTime);

   setTimeout ( transition, settings.timeout );
  }

  function transition ()
  {
   nextItem = parseInt ( currentItem + 1 );

   if ( nextItem >= count )
    nextItem = 0;

   $('.slide-' + currentItem ).animate({
    //paddingTop: '100px', paddingBottom: '0px',
    opacity: 0 }, settings.slideTime, function () {
     $(this).hide();
     $('.slide-' + nextItem ).show().animate({
      //paddingTop: '0px', paddingBottom: '50px',
      opacity: 1 }, settings.slideTime);
   });

   currentItem = nextItem;
   setTimeout ( transition, settings.timeout );
  }
  return firstSlide ();
 };
}( jQuery ));

// Start the Text Slider
 $('.slide').textSlider({
  timeout: 5000,
  slideTime: 650,
  loop: 1
 });

/* Main Message & Text */
.main-message {
 font-size: 150%;
 font-weight: bold;
 padding-bottom: 20px;
 margin-left: 20px;
}
.main-text {
 font-size: 110%;
 margin-left: 20px;
}

Test 1

Sub text here 1

Test 2

Sub text here 2

Test 3

Sub text here 3

Body:
In your function transition() {... you can add at the beginning:

// if mouse is hover element call again the settimeout...
if ($('.slide-' + currentItem + ':hover').length != 0) {
    setTimeout(transition, settings.timeout);
    return;
}

A different solution can be based on .hover(), adding the following event handler:

this.children('.slider-item').hover(
        function (e) {
            $(this).addClass('hover');
        },
        function (e) {
            $(this).removeClass('hover');
        }
);

and, so, changing the first suggested code with:

// if element has hover class call again the settimeout...
if ($('.slide-' + currentItem + '.hover').length != 0) {
    setTimeout(transition, settings.timeout);
    return;
}

The snippet:

(function ($) {
    $.fn.textSlider = function (options) {

        /* Default settings */
        var settings = $.extend(
                {
                    timeout: 2000,
                    slideTime: 750,
                },
                options
        );

        var nextItem;

        var currentItem = 0;
        var count = 0;

        this.children('.slider-item').each(function () {
                    $(this).addClass('slide-' + ( count ))
                            .css({
                                //opacity:    0,
                                //paddingTop: '100px',
                                //paddingBottom: '0px'
                            }
                    );
                    $(this).hide();
                    count++;
                }
        );

        this.children('.slider-item').hover(
                function (e) {
                    $(this).addClass('hover');
                },
                function (e) {
                    $(this).removeClass('hover');
                }
        );

        function firstSlide() {
            $('.slide-' + currentItem).show().animate({
                //paddingTop: '0px', paddingBottom: '50px',
                opacity: 1
            }, settings.slideTime);

            setTimeout(transition, settings.timeout);
        }

        function transition() {
            if ($('.slide-' + currentItem + '.hover').length != 0) {
                setTimeout(transition, settings.timeout);
                return;
            }
            nextItem = parseInt(currentItem + 1);

            if (nextItem >= count)
                nextItem = 0;

            $('.slide-' + currentItem).animate({
                //paddingTop: '100px', paddingBottom: '0px',
                opacity: 0
            }, settings.slideTime, function () {
                $(this).hide();
                $('.slide-' + nextItem).show().animate({
                    //paddingTop: '0px', paddingBottom: '50px',
                    opacity: 1
                }, settings.slideTime);
            });

            currentItem = nextItem;
            setTimeout(transition, settings.timeout);
        }

        return firstSlide();
    };
}(jQuery));

 // Start the Text Slider
$('.slide').textSlider({
    timeout: 1000,
    slideTime: 350,
    loop: 1
});

.main-message {
    font-size: 150%;
    font-weight: bold;
    padding-bottom: 20px;
    margin-left: 20px;
}

.main-text {
    font-size: 110%;
    margin-left: 20px;
}

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

<div class="slide">
    <div class="slider-item">
        <div class="main-message">Test 1</div>
        <div class="main-text">Sub text here 1</div>
    </div>
    <div class="slider-item">
        <div class="main-message">Test 2</div>
        <div class="main-text">Sub text here 2</div>
    </div>
    <div class="slider-item">
        <div class="main-message">Test 3</div>
        <div class="main-text">Sub text here 3</div>
    </div>
</div>


问:
How to enable Genymotion emulator to use the WIFI internet the host is using
The app I am running on Genymotion emulator needs internet. The internet does not seem to work on the Genymotion emulator. I tried to confirm this by opening the browser, and this is what I got:

I am running Windows 7 on my laptop and using the Wifi internet. I opened Oracle VM Virtual box, navigated to Settings > Network, and the following two images show what I see there:

So how do I enable the emulator to use the internet from my computer?

Note: Please tell me in layman terms. I saw articles and questions talking in terms of IP addresses and other things which are strange for me.

EDIT 1:

答:
Try just turning on the WiFi in GenyMotion and selecting the WiredSSID.

I know this question been answered, but thought a picture would be easy to understand. Hope it helps.


问:
value of variable vanishes
I do not understand what is happening with my variables, the values all vanish / become empty within the function. I don't have anything within the function. I believe that I am doing the 'checks' correctly '==' and the assignments correctly '='. Regardless of what i try, i continue to get the 'file doesn't exist result'. and if i var_dump to see what the value of $cID or $check, they come back as empty ''.

```<code>function gt_masthead($cID='3', $check=false, $str=''){ //assign value to var

$check == file_exists('./' . $cID . 'bg-userProfile.jpg');  //file exists?

    //echo '<h1> / ' . $cID . ' / ' . $check . ' </h1>';

    dumpVar($cID);  //test

    if($check == 1){
        // file exists, show
        $str = '<img class=" img-fluid" style="width: 100%;" src="./3bg-userProfile.jpg" alt="Card image cap">';
    }else{
        // file does not exist, show default
        $str = '<img class=" img-fluid" style="width: 100%;" src="./img_logoMarvel.gif" alt="Card image cap">';
    }
    return $str;
}
</code>```

答:
Try this code instead:

```<code><?php
    function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
        //check if given image file exists
        if(file_exists("./{$cID}{$image}")) {
            //if it does exist, set the displayImage variable to the path of the image.
            $displayImage = "./{$cID}{$image}";
        } else {
            //if it does not exist, set the displayImage variable to the path of the default image
            $displayImage = "./{$default}";
        }
        //Add the displayImage path to an image element, and return that element.
        $str = "<img class='img-fluid' style='width:100%;' src='{$displayImage}' alt='Card image cap'>";
        return $str;
    }
?>
</code>```

The usage of this code is pretty simple. You call it like this:

gt_masthead("cID number", "image name"); - you can also use variables here, just drop the quotes.

Alternatively, you can also use a 3rd variable to dynamically set the default image if the searched one does not exist.

gt_masthead("cID number", "image name", "default image name");

I commented the code to try to explain what is going on. If you have any questions please ask

Here is a more standard way to write the function, I know the squiggly braces sometimes confused people, but the code is basically the same.

```<code><?php
    function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
        //check if given image file exists
        if(file_exists("./".$cID.$image)) {
            //if it does exist, set the displayImage variable to the path of the image.
            $displayImage = "./".$cID.$image;
        } else {
            //if it does not exist, set the displayImage variable to the path of the default image
            $displayImage = "./".$default;
        }
        //Add the displayImage path to an image element, and return that element.
        $str = "<img class='img-fluid' style='width:100%;' src='".$displayImage."' alt='Card image cap'>";
        return $str;
    }
?>
</code>```

Title: value of variable vanishes

Body:
I do not understand what is happening with my variables, the values all vanish / become empty within the function. I don't have anything within the function. I believe that I am doing the 'checks' correctly '==' and the assignments correctly '='. Regardless of what i try, i continue to get the 'file doesn't exist result'. and if i var_dump to see what the value of $cID or $check, they come back as empty ''.

function gt_masthead($cID='3', $check=false, $str=''){ //assign value to var

$check == file_exists('./' . $cID . 'bg-userProfile.jpg');  //file exists?

    //echo '
 / ' . $cID . ' / ' . $check . '
';

    dumpVar($cID);  //test

    if($check == 1){
        // file exists, show
        $str = '';
    }else{
        // file does not exist, show default
        $str = '';
    }
    return $str;
}

Body:
Try this code instead:

<?php
    function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
        //check if given image file exists
        if(file_exists("./{$cID}{$image}")) {
            //if it does exist, set the displayImage variable to the path of the image.
            $displayImage = "./{$cID}{$image}";
        } else {
            //if it does not exist, set the displayImage variable to the path of the default image
            $displayImage = "./{$default}";
        }
        //Add the displayImage path to an image element, and return that element.
        $str = "<img class='img-fluid' style='width:100%;' src='{$displayImage}' alt='Card image cap'>";
        return $str;
    }
?>

The usage of this code is pretty simple. You call it like this:

gt_masthead("cID number", "image name"); - you can also use variables here, just drop the quotes.

Alternatively, you can also use a 3rd variable to dynamically set the default image if the searched one does not exist.

gt_masthead("cID number", "image name", "default image name");

I commented the code to try to explain what is going on. If you have any questions please ask

Here is a more standard way to write the function, I know the squiggly braces sometimes confused people, but the code is basically the same.

<?php
    function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
        //check if given image file exists
        if(file_exists("./".$cID.$image)) {
            //if it does exist, set the displayImage variable to the path of the image.
            $displayImage = "./".$cID.$image;
        } else {
            //if it does not exist, set the displayImage variable to the path of the default image
            $displayImage = "./".$default;
        }
        //Add the displayImage path to an image element, and return that element.
        $str = "<img class='img-fluid' style='width:100%;' src='".$displayImage."' alt='Card image cap'>";
        return $str;
    }
?>


问:
Jquery addition and multiplication calculation
I'm calculating some Jquery variables, but don't know why else if condition is not getting true please check with below code</p>

```<code>function roomCalc(){
  var noOfAdults = 2; // this is dynamic //parseInt($('#adults').val());
  var noOfChilds = 0;// this is dynamic parseInt($('#childs').val());
  var noofXtraAdults = 15000;//parseInt($('#extraAdult').val());
  var noofXtraChilds = 15000;//parseInt($('#extraChild').val());
  var maxRoomToatal = 1000;//parseInt($('#maxRoomToatal').text());

  $('#adults').keyup(function(){
    if(noOfAdults <= 2 )
  {
      var totalOutput = maxRoomToatal;
  }
  else if(noOfAdults >= 3 ){
    var totalOutput = noofXtraAdults + maxRoomToatal;
  }

  alert(totalOutput);
});

}
roomCalc();
</code>```

答:
You have not assigned your input value to noOfAdults.

function roomCalc() {
  var noOfAdults = 2; // this is dynamic //parseInt($('#adults').val());
  var noOfChilds = 0; // this is dynamic parseInt($('#childs').val());
  var noofXtraAdults = 15000; //parseInt($('#extraAdult').val());
  var noofXtraChilds = 15000; //parseInt($('#extraChild').val());
  var maxRoomToatal = 1000; //parseInt($('#maxRoomToatal').text());

  $('#adults').keyup(function() {
    noOfAdults = $('#adults').val() > 0 ? $('#adults').val() : noOfAdults;
    if (noOfAdults <= 2) {
      var totalOutput = maxRoomToatal;
    } else if (noOfAdults >= 3) {
      var totalOutput = noofXtraAdults + maxRoomToatal;
    }

    $("#maxRoomToatal").html(totalOutput);

  });

}
roomCalc();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="adults" type='number'>
<div id="maxRoomToatal"></div></code>```

Body:
I'm calculating some Jquery variables, but don't know why else if condition is not getting true please check with below code

function roomCalc(){
  var noOfAdults = 2; // this is dynamic //parseInt($('#adults').val());
  var noOfChilds = 0;// this is dynamic parseInt($('#childs').val());
  var noofXtraAdults = 15000;//parseInt($('#extraAdult').val());
  var noofXtraChilds = 15000;//parseInt($('#extraChild').val());
  var maxRoomToatal = 1000;//parseInt($('#maxRoomToatal').text());

  $('#adults').keyup(function(){
    if(noOfAdults <= 2 )
  {
      var totalOutput = maxRoomToatal;
  }
  else if(noOfAdults >= 3 ){
    var totalOutput = noofXtraAdults + maxRoomToatal;
  }

  alert(totalOutput);
});

}
roomCalc();

Body:
You have not assigned your input value to noOfAdults.

function roomCalc() {
  var noOfAdults = 2; // this is dynamic //parseInt($('#adults').val());
  var noOfChilds = 0; // this is dynamic parseInt($('#childs').val());
  var noofXtraAdults = 15000; //parseInt($('#extraAdult').val());
  var noofXtraChilds = 15000; //parseInt($('#extraChild').val());
  var maxRoomToatal = 1000; //parseInt($('#maxRoomToatal').text());

  $('#adults').keyup(function() {
    noOfAdults = $('#adults').val() > 0 ? $('#adults').val() : noOfAdults;
    if (noOfAdults <= 2) {
      var totalOutput = maxRoomToatal;
    } else if (noOfAdults >= 3) {
      var totalOutput = noofXtraAdults + maxRoomToatal;
    }

    $("#maxRoomToatal").html(totalOutput);

  });

}
roomCalc();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="adults" type='number'>
<div id="maxRoomToatal"></div>


问:
Merging rows in R while excluding certain data
Let's say I have a data frame with many subjects and many test variables:

```<code>   Name      Date1      Date2 `Test1` `Test2` `Test3`
  <dbl>     <dttm>     <dttm>   <chr>   <chr>   <chr>
1 Steve 2012-02-27 2011-11-18    <NA>    <NA>      3
2 Steve 2012-02-27 2012-01-22      4     <NA>    <NA>
3 Steve 2012-02-27 2014-08-09    <NA>      8     <NA>
4 Mike  2012-02-09 2007-03-29      1       2       3
5 Mike  2012-02-09 2009-07-13    <NA>      5       6
6 Mike  2012-02-09 2014-03-11    <NA>    <NA>      9
7 John  2012-03-20 2013-10-22      1       2     <NA>
8 John  2012-03-20 2014-03-17      4       5     <NA>
9 John  2012-03-20 2015-06-01    <NA>      8       9
</code>```

I would like to know (most likely with dplyr) how to exclude data of rows that have a Date2 that is past Date1. Then to combine the remaining data into one row by (arranged by Name) while excluding the earlier data that have more recent results. Then write a new data frame that excludes the Date2 column, all while still including the "NA"s in the data.

Also, if none of the Date2 column are before the Date1 column, I would like to keep the Name but include a row of "NA"s (as in the case of "John").

So the results should look like this:

```<code>   Name      Date1 `Test1` `Test2` `Test3`
  <dbl>     <dttm>   <chr>   <chr>   <chr>
1 Steve 2012-02-27      4     <NA>      3
2 Mike  2012-02-09      1       5       6
3 John  2012-03-20    <NA>    <NA>    <NA>
</code>```

Any help on this would be greatly appreciated, thank you.

答:
This will do it with dplyr...

```<code>library(dplyr)
df2 <- df %>% filter(as.Date(Date2) <= as.Date(Date1)) %>% #remove date2 past date1
  arrange(as.Date(Date2)) %>% #make sure ordered by date2
  group_by(Name, Date1) %>% #group by name and date1
  summarise_all(function(x) last(x[!is.na(x)])) %>% #summarise remaining (i.e. the test-columns) by the last non-NA value
  right_join(df %>% distinct(Name, Date1)) %>% #join names and date1 from original df (to restore NA rows such as John)
  select(-Date2) #remove Date2

df2

   Name      Date1 Test1 Test2 Test3
1 Steve 2012-02-27     4  <NA>     3
2  Mike 2012-02-09     1     5     6
3  John 2012-03-20  <NA>  <NA>  <NA>
</code>```

Body:
Let's say I have a data frame with many subjects and many test variables:

   Name      Date1      Date2 `Test1` `Test2` `Test3`
  <dbl>     <dttm>     <dttm>   <chr>   <chr>   <chr>
1 Steve 2012-02-27 2011-11-18    <NA>    <NA>      3
2 Steve 2012-02-27 2012-01-22      4     <NA>    <NA>
3 Steve 2012-02-27 2014-08-09    <NA>      8     <NA>
4 Mike  2012-02-09 2007-03-29      1       2       3
5 Mike  2012-02-09 2009-07-13    <NA>      5       6
6 Mike  2012-02-09 2014-03-11    <NA>    <NA>      9
7 John  2012-03-20 2013-10-22      1       2     <NA>
8 John  2012-03-20 2014-03-17      4       5     <NA>
9 John  2012-03-20 2015-06-01    <NA>      8       9

I would like to know (most likely with dplyr) how to exclude data of rows that have a Date2 that is past Date1. Then to combine the remaining data into one row by (arranged by Name) while excluding the earlier data that have more recent results. Then write a new data frame that excludes the Date2 column, all while still including the "NA"s in the data.

Also, if none of the Date2 column are before the Date1 column, I would like to keep the Name but include a row of "NA"s (as in the case of "John").

So the results should look like this:

   Name      Date1 `Test1` `Test2` `Test3`
  <dbl>     <dttm>   <chr>   <chr>   <chr>
1 Steve 2012-02-27      4     <NA>      3
2 Mike  2012-02-09      1       5       6
3 John  2012-03-20    <NA>    <NA>    <NA>

Any help on this would be greatly appreciated, thank you.

Body:
This will do it with dplyr...

library(dplyr)
df2 <- df %>% filter(as.Date(Date2) <= as.Date(Date1)) %>% #remove date2 past date1
  arrange(as.Date(Date2)) %>% #make sure ordered by date2
  group_by(Name, Date1) %>% #group by name and date1
  summarise_all(function(x) last(x[!is.na(x)])) %>% #summarise remaining (i.e. the test-columns) by the last non-NA value
  right_join(df %>% distinct(Name, Date1)) %>% #join names and date1 from original df (to restore NA rows such as John)
  select(-Date2) #remove Date2

df2

   Name      Date1 Test1 Test2 Test3
1 Steve 2012-02-27     4  <NA>     3
2  Mike 2012-02-09     1     5     6
3  John 2012-03-20  <NA>  <NA>  <NA>


问:
Problem with PHP session in Xampp
At it's simplest, if file_1.php contains

```<code><?php

  session_start();

  $_SESSION["test_message"] = "Hello, world";

  header("Location: http://localhost/file_2.php");
?>
</code>```

and file_2.php contains

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

</body>
</html>
</code>```

the result is Test message is not set and a var_dump($_SESSION) returns null - locally, with Xampp. However, if I upload those same files to a paid-for hosted web site, it works and I see

```<code>Hello, world
array
  'test_message' => string 'Hello, world' (length=12)
</code>```

When I look at PHPinfo under Xampp it shows Session Support  enabled.  What am I doing wrong?

答:
Session issue can be fixed in Xampp 7.1.6 do the following change in php.ini
    Line #1403</p>

```<code>session.auto_start = 1
</code>```

Title: Problem with PHP session in Xampp

Body:
At it's simplest, if file_1.php contains

<?php

  session_start();

  $_SESSION["test_message"] = "Hello, world";

  header("Location: http://localhost/file_2.php");
?>

and file_2.php contains

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

the result is Test message is not set and a var_dump($_SESSION) returns null - locally, with Xampp. However, if I upload those same files to a paid-for hosted web site, it works and I see

Hello, world
array
  'test_message' => string 'Hello, world' (length=12)

When I look at PHPinfo under Xampp it shows Session Support  enabled.  What am I doing wrong?

Body:
Session issue can be fixed in Xampp 7.1.6 do the following change in php.ini
    Line #1403

session.auto_start = 1


问:
Oracle Data Type for text file?
I need to create a table in Oracle that will store a series of large text files.  After looking at the Oracle datatype's it is unclear what type I should use to store the files.

The limits on the text specific types like VARCHAR2 seem very small (32K).  The other types don't seem to be the right match for a text file (e.g. BFILE).

Does anyone have an opinion on the right type to use?

答: Depends on what version of Oracle you are using Either CLOB or Long</p>

Title: Oracle Data Type for text file?


问:
Enable editing geojson data
Enable editing to layers drown using geojson

```<code> var drawnItems = new L.FeatureGroup();
 map.addLayer(drawnItems);
</code>```

Json data

```<code>    $.getJSON("js/draw/neighborhoods.json",function(hoodData){
     alert("this is editableLayers");
     var i = 0;
    var geojsonlayer = L.geoJson(hoodData,
    {
           onEachFeature: function (feature, layer) {
                alert(feature.properties.prop0);
                var myLayer = layer;
            drawnItems.addLayer(myLayer);

            }
    });
    map.addLayer(drawnItems);
    });
</code>```

Adding control

```<code>    //draw control
    var drawControl = new L.Control.Draw({
        draw: false,
        edit: {
            featureGroup: drawnItems,
            remove: false,
            edit: true
       }
    });

    map.addControl(drawControl);
    map.on('draw:edited', function (e) {
    var layers = e.layers;
    layers.eachLayer(function (layer) {
        console.log(layer)
    });
});
</code>```

Using this code i am able to draw the layers but unable to edit it.
I am using leaflet.draw lib.

答:
If you could set up a JSFiddle with some sample data, I can take a closer look at the process you have set up.

Ideally, the geojson data would be available prior to adding to the control and adding to the map. Since this is asynchronous, you should have the control and layer added to the map after each update from your ajax/getJSON closure. Sort of like cleaning the workspace each time you have new data to edit.

Title: Enable editing geojson data

Body:
Enable editing to layers drown using geojson

 var drawnItems = new L.FeatureGroup();
 map.addLayer(drawnItems);

Json data

    $.getJSON("js/draw/neighborhoods.json",function(hoodData){
     alert("this is editableLayers");
     var i = 0;
    var geojsonlayer = L.geoJson(hoodData,
    {
           onEachFeature: function (feature, layer) {
                alert(feature.properties.prop0);
                var myLayer = layer;
            drawnItems.addLayer(myLayer);

            }
    });
    map.addLayer(drawnItems);
    });

Adding control

    //draw control
    var drawControl = new L.Control.Draw({
        draw: false,
        edit: {
            featureGroup: drawnItems,
            remove: false,
            edit: true
       }
    });

    map.addControl(drawControl);
    map.on('draw:edited', function (e) {
    var layers = e.layers;
    layers.eachLayer(function (layer) {
        console.log(layer)
    });
});

Using this code i am able to draw the layers but unable to edit it.
I am using leaflet.draw lib.


问:
How do I build this block matrix in python?
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

```<code>1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1
</code>```

For 3 points the matrix is

```<code>1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1
</code>```

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

Body:
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1

For 3 points the matrix is

1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

Body:
Here's an approach upon computing those linear indices in a broadcasted manner and then assigning into an zeros-initialized array -

def block_mat(list_, n = 2):
    input_arr = np.array(list_).reshape(-1,4)
    N = 2*n + 2
    M = 2*N + 2

    p,q = input_arr.shape
    I,J,K = np.ix_(M*np.arange(n), N*np.arange(p), np.arange(q))
    idx = I + J + K + N

    out = np.zeros((N,N),dtype=input_arr.dtype)
    out.flat[idx] = input_arr
    out.flat[[0,-1]] = 1
    return out

Sample runs -

1) Input elements :

In [497]: a,b,c,d,e,f,g,h = range(3,11)

In [498]: a,b,c,d,e,f,g,h
Out[498]: (3, 4, 5, 6, 7, 8, 9, 10)

2) Various n cases :

In [499]: block_mat([a,b,c,d,e,f,g,h], n = 2)
Out[499]:
array([[ 1,  0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  0,  0],
       [ 7,  8,  9, 10,  0,  0],
       [ 0,  0,  3,  4,  5,  6],
       [ 0,  0,  7,  8,  9, 10],
       [ 0,  0,  0,  0,  0,  1]])

In [500]: block_mat([a,b,c,d,e,f,g,h], n = 3)
Out[500]:
array([[ 1,  0,  0,  0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  0,  0,  0,  0],
       [ 7,  8,  9, 10,  0,  0,  0,  0],
       [ 0,  0,  3,  4,  5,  6,  0,  0],
       [ 0,  0,  7,  8,  9, 10,  0,  0],
       [ 0,  0,  0,  0,  3,  4,  5,  6],
       [ 0,  0,  0,  0,  7,  8,  9, 10],
       [ 0,  0,  0,  0,  0,  0,  0,  1]])

In [501]: block_mat([a,b,c,d,e,f,g,h], n = 4)
Out[501]:
array([[ 1,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  0,  0,  0,  0,  0,  0],
       [ 7,  8,  9, 10,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  3,  4,  5,  6,  0,  0,  0,  0],
       [ 0,  0,  7,  8,  9, 10,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  3,  4,  5,  6,  0,  0],
       [ 0,  0,  0,  0,  7,  8,  9, 10,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  3,  4,  5,  6],
       [ 0,  0,  0,  0,  0,  0,  7,  8,  9, 10],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  1]])


问:
How to sum tuple values outputted by an API in Python
So a fairly simple problem which I'm trying to solve in the most efficient way possible.

I am querying an API which outputs a series of namedtuples, and I want to accumulate and sum the value of each outputted tuple.

i.e i'm doing something like the following:

```<code>for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)
</code>```

which would output something like:

```<code>Point(end_time='2017-07-05T12:12:24.471Z', start_time='2017-07-05T12:11:24.471Z', value=0)
Point(end_time='2017-07-05T12:13:24.471Z', start_time='2017-07-05T12:12:24.471Z', value=48)
Point(end_time='2017-07-05T12:14:24.471Z', start_time='2017-07-05T12:13:24.471Z', value=11)
Point(end_time='2017-07-05T12:15:24.471Z', start_time='2017-07-05T12:14:24.471Z', value=0)
Point(end_time='2017-07-05T11:52:24.471Z', start_time='2017-07-05T11:51:24.471Z', value=0)
</code>```

I need to grab the value in each namedtuple, and sum the total.

What I've got is:

```<code>   total_foo = []

   for time_series in api_query:
        for ts_tuple in time_series.header:
            total_foo.append(ts_tuple.value)
</code>```

then just call a sum on total_foo.

I was wondering whether anyone can suggest a more pythonic way? I'm trying to get away from just using for loops and appending to lists all the time.

NB: for some background the api is querying a Stackdriver metric via the google-cloud-python library.

答:
You can change your original loop to also do the sum:</p>

```<code>total_foo = 0
for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)
        total_foo += int(ts_tuple.value)
</code>```

Body:
So a fairly simple problem which I'm trying to solve in the most efficient way possible.

I am querying an API which outputs a series of namedtuples, and I want to accumulate and sum the value of each outputted tuple.

i.e i'm doing something like the following:

for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)

which would output something like:

Point(end_time='2017-07-05T12:12:24.471Z', start_time='2017-07-05T12:11:24.471Z', value=0)
Point(end_time='2017-07-05T12:13:24.471Z', start_time='2017-07-05T12:12:24.471Z', value=48)
Point(end_time='2017-07-05T12:14:24.471Z', start_time='2017-07-05T12:13:24.471Z', value=11)
Point(end_time='2017-07-05T12:15:24.471Z', start_time='2017-07-05T12:14:24.471Z', value=0)
Point(end_time='2017-07-05T11:52:24.471Z', start_time='2017-07-05T11:51:24.471Z', value=0)

I need to grab the value in each namedtuple, and sum the total.

What I've got is:

   total_foo = []

   for time_series in api_query:
        for ts_tuple in time_series.header:
            total_foo.append(ts_tuple.value)

then just call a sum on total_foo.

I was wondering whether anyone can suggest a more pythonic way? I'm trying to get away from just using for loops and appending to lists all the time.

NB: for some background the api is querying a Stackdriver metric via the google-cloud-python library.

Body:
You can change your original loop to also do the sum:

total_foo = 0
for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)
        total_foo += int(ts_tuple.value)


问:
How do I find the SourceLocation of the type definition of a VarDecl using the Clang AST?
I'm trying to determine if a type is defined within the file or is included in another file (either system header or otherwise), and I can't seem to find an easy way to find the location of a type of a variable. The closest I can get is using TypeLoc's methods, but those provide only the location of the variable declaration (weirdly enough). ASTContext and SourceManager classes don't seem to provide much help either. Any ideas on how this can be done (I'm sure there has to be a way)?

答:
This can be accomplished by typecasting or using the getAs() method to cast a Type class to something that has references to a type declaration.

For example,

```<code>// Get Type of variable declaration
const clang::Type* type = var_decl->getTypeSourceInfo()->getTypeLoc().getTypePtr();

// Cast it as its appropriate subtype and then obtain its declaration
// For example, if the type was a record, you can cast it as a
// RecordType and then obtain its definition.
const clang::RecordType* record_type = type->getAs<clang::RecordType>();
if (record_type != nullptr) {
  const clang::RecordDecl* type_decl = record_type->getDecl();

  clang::SourceLocation end_of_type_decl = type_decl->getLocEnd();
}
</code>```

Hope this helps!

Body:
This can be accomplished by typecasting or using the getAs() method to cast a Type class to something that has references to a type declaration.

For example,

// Get Type of variable declaration
const clang::Type* type = var_decl->getTypeSourceInfo()->getTypeLoc().getTypePtr();

// Cast it as its appropriate subtype and then obtain its declaration
// For example, if the type was a record, you can cast it as a
// RecordType and then obtain its definition.
const clang::RecordType* record_type = type->getAs<clang::RecordType>();
if (record_type != nullptr) {
  const clang::RecordDecl* type_decl = record_type->getDecl();

  clang::SourceLocation end_of_type_decl = type_decl->getLocEnd();
}

Hope this helps!


问:
ERROR TypeError: .forEach is not a function
In my Angular program, I need to create a deep copy of my object so that I'll be able to compare the changes. Here is what I tried and I get an error in my console that says ERROR TypeError: .forEach is not a function. How do I fix this?

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { PTOData } from './pto-data';
import { PTODataService } from './pto-data.service';
import { EmpInfo } from './emp-info';
import { EmpInfoService } from './emp-info.service';

@Component({
    selector: '[pto-row-edit]',
    templateUrl: `./row-edit.component.html`,
    styleUrls: ['./row-edit.component.css']
})

export class RowEditComponent implements OnInit {

    // Inputs & Outputs to/from grid component
    @Input() pto: PTOData[];
    @Input() rowSelected: number;

    @Output() onDelete = new EventEmitter<number>();
    @Output() onSave = new EventEmitter<number>();

    opto: PTOData[];

    private initialized: boolean = false;

    ngOnInit(): void {
        this.opto = [];
        this.pto.forEach(x => this.opto.push(x))
        console.log(this.opto);
    }

    constructor(
        private ptodataService: PTODataService,
        private empInfoService: EmpInfoService) { }

    resetRow(pto: PTOData): void {
        console.log(this.pto);
        console.log(this.opto);
        this.rowSelected = null;
        this.onSave.emit(this.rowSelected);
    }

}```

答:
See comments on the original question. The original issue, as @SaxyPandaBear pointed out, was that an array value was expected for the @Input() pto field rather than a plain object, so the declared type needed to be changed and the array-cloning statement needed to be replaced with an object-cloning statement.

If you want to clone an object instead of an array, use:

```<code>this.opto = Object.assign({}, originalObject);
</code>```

or (my preferred method, since it has better TypeScript type-checking support) the spread operator:

```<code>this.opto = {...originalObject};
</code>```

Body:
See comments on the original question. The original issue, as @SaxyPandaBear pointed out, was that an array value was expected for the @Input() pto field rather than a plain object, so the declared type needed to be changed and the array-cloning statement needed to be replaced with an object-cloning statement.

If you want to clone an object instead of an array, use:

this.opto = Object.assign({}, originalObject);

or (my preferred method, since it has better TypeScript type-checking support) the spread operator:

this.opto = {...originalObject};


问:
Referenced assembly deploy question
I have a project A.

A use a library aseembly(B) which referenced another 3rd party library(C).

I know B will be copies to my output directory. I am wondering whether C will be copies too?

答: In most cases, yes. If it doesn't, we'll talk about the exceptions :-)</p>

Title: Referenced assembly deploy question


问:
alert not showing after form validation success
I am trying to get a console log message if my validation passes but in its current state it doesn't do anything. All the validation errors display as expected but if there are no errors the success console log message doesn't display. </p>

```<code>    $.ajax({
                url:'php/functions.php',
                type:'POST',
                dataType:'json',
                data: {name: name, email: email, venue: venue, guests: guests, comments: comments},
                })

            .done(function(data) {

                console.log(data);

                if(!data.success) {

                    $( "#submit" ).prop('disabled', false);

                    if(data.errors.name) {
                        $( "#error-name" ).empty().append(data.errors.name).fadeIn();
                    }

                    if(data.errors.email) {
                        $("#error-email").empty().append(data.errors.email).fadeIn();
                    }

                    if(data.errors.venue) {
                        $( "#error-venue" ).empty().append(data.errors.venue).fadeIn();
                    }

                    if(data.errors.guests) {
                        $( "#error-guests" ).empty().append(data.errors.guests).fadeIn();
                    }

                    if(data.errors.comments) {
                        $( "#error-comments" ).empty().append(data.errors.comments).fadeIn();
                    }

                } else {

                    alert("okay!");
                }
            })

            .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus + ': ' + errorThrown);
            });
</code>```

答:
As you said

$reponse['success']

should be `

$response['success']

also as per our chat, you could end up doing the same functionality with just the errors array rather than adding multiple properties to verify the same

if you stick with your code
you can use either

if(!data.success) { as done now

or you can use

if(data.errors.length > 0) { }

in case of such issues always try to use console.log() to verify if your data or code is being executed.

Body:
I am trying to get a console log message if my validation passes but in its current state it doesn't do anything. All the validation errors display as expected but if there are no errors the success console log message doesn't display.

    $.ajax({
                url:'php/functions.php',
                type:'POST',
                dataType:'json',
                data: {name: name, email: email, venue: venue, guests: guests, comments: comments},
                })

            .done(function(data) {

                console.log(data);

                if(!data.success) {

                    $( "#submit" ).prop('disabled', false);

                    if(data.errors.name) {
                        $( "#error-name" ).empty().append(data.errors.name).fadeIn();
                    }

                    if(data.errors.email) {
                        $("#error-email").empty().append(data.errors.email).fadeIn();
                    }

                    if(data.errors.venue) {
                        $( "#error-venue" ).empty().append(data.errors.venue).fadeIn();
                    }

                    if(data.errors.guests) {
                        $( "#error-guests" ).empty().append(data.errors.guests).fadeIn();
                    }

                    if(data.errors.comments) {
                        $( "#error-comments" ).empty().append(data.errors.comments).fadeIn();
                    }

                } else {

                    alert("okay!");
                }
            })

            .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus + ': ' + errorThrown);
            });


问:
Use an Access 2010 form based on 1 table to enter data in a linked table
First of all, I am a total NOOB! I am trying to make an Access DB for handling orders through an entire process.  As such, I have created tables based on each of the individual processes. The order data, which holds only the basic information is in tblCurrentOrders.  Each of the other processes is linked to tblCurrentOrders by the OrderNumber field.  The first step of the process is due date information is entered in the tblPlanner table.  Obviously, until data is entered in tblPlanner, no OrderNumber exists (this will hold true for the other tables, too, if I ever get that far).

I want to create a form based tblCurrentOrders that shows only the records without corresponding entries in tblPlanner (new orders) and then I want to be able to enter the tblPlanner info in a subform.  I have tried making a form based on tblCurrentOrders with a subform based on tblPlanner, but I can't figure out how to only display new orders.  I also tried basing the form on a query that only showed new orders, but I don't know how to make the subform based on tblPlanner to work.

Please Help!!

答:
Well, the easiest way to link the tables would be to create your OrderNumber in the tblPlanner when you start a new order.  Then add a flag and timestamp as to whether it's "released" yet.

EDIT

Since you provide a little bit more detail, I'll edit my response to more closely align for your desired approach.

Creating a "New Order" is a multi-step process.  So it's usually best to create a Command Button on a form that calls VBA code.  This will allow you to control each step and make sure it's correct.

Step A: First you want to:

1) Create a Control Form (if you haven't already) that allows you to put Command Buttons which will launch different VBA code or open different display Forms.

2) On the Control Form, create a List Box that allows you to select an existing OrderNumber.

3) On the Control Form, create a Command Button to open an Order Form which uses the selected List Box OrderNumber.  When that Order Form opens, it will populate with the tblCurrentOrders data for that OrderNumber and also populate the subform with tblPlanner data.  (As long as you have them linked properly.)

4) On the Control Form, create a Command Button to open the Order Form with a set of records which are "New Orders" only.  See the more detailed process below in Step C.

5) On the Control Form, create a Command Button to Launch VBA code that will create a "New Order".  This is a multi step process detailed below in Step B.

6) Create any other buttons or controls that allow you to monitor or advance your "Order" along the way to completion.  (This is a ton of work to get all the pieces in place.)

Step B: When you press the Command Button to create a "New Order" you want to create VBA code that will:

1) Create a new record in the tblCurrentOrders table.

2) Create a Unique OrderNumber on the new Record.  It's usually best if you control the generation of this number and don't just let it be a system generated sequence number.  But whatever you desire is ok as long as it's Unique.

3) Set your ReleasedFlag to false on the new tblCurrentOrders record.

4) Make sure your ReleasedTimeStamp is null.  (Or whatever value you want it to be.)

5) You may want a CreatedTimeStamp which you can populate with a date of Now().

6) Populate any other "Initalization" fields that need to be filled.  (Like Backorder status, Return flags, Shorted Flags, etc. etc. etc.)

7) Create a new record in the tblPlanner table.

8) Copy the Unique OrderNumber that you created for the tblCurrentOrders record into the OrderNumber field on the new tblPlanner record. This creates a link for you to use with your subqueries and subforms.

9) Now you can open the Order Form with this new OrderNumber.

Step C: When you press the Command Button to open a set of records which are "New Orders" only:

The Command Button needs to launch a query to find "...tblCurrentOrders that shows only the records without corresponding entries in tblPlanner (new orders)":
You just need to select tblCurrentOrders that have a ReleasedFlag set to false.

```<code>`SELECT * FROM tblCurrentOrders WHERE ReleasedFlag = false`
</code>```

So when you say: "...and then I want to be able to enter the tblPlanner info in a subform"... you can create a subform linking to tblPlanner based on the tblCurrentOrders OrderNumber field.

This is all reliant on you observing that when you say "...records without corresponding entries in tblPlanner..." That you really mean: records without released entries in tblPlanner.  And that means: in order for a record to exist in tblCurrentOrders, it has to have a corresponding blank (or starter) record created in tblPlanner.  Thus now you can display blank tblPlanner records that are linked to unreleased tblCurrentOrders records.

Then once your data entry people are done monkeying around with the New Order, they can "Release" the order (usually by clicking on a Release Command Button).  At that point, you can set your ReleasedTimeStamp to Now() and set your ReleasedFlag to True in the tblCurrentOrders.  It's officially no longer a "new order" and is now a live order in your system.

You are at the tip of the iceberg for creating a home grown order entry system.  The complexities for building a good one are immense. Best of luck figuring it all out.  Just remember to use time stamps and ID fields so you can go back and un-do what may have been done by accident.

Hope this all helps. :)

Body:
Well, the easiest way to link the tables would be to create your OrderNumber in the tblPlanner when you start a new order.  Then add a flag and timestamp as to whether it's "released" yet.

EDIT

Since you provide a little bit more detail, I'll edit my response to more closely align for your desired approach.

Creating a "New Order" is a multi-step process.  So it's usually best to create a Command Button on a form that calls VBA code.  This will allow you to control each step and make sure it's correct.

Step A: First you want to:

1) Create a Control Form (if you haven't already) that allows you to put Command Buttons which will launch different VBA code or open different display Forms.

2) On the Control Form, create a List Box that allows you to select an existing OrderNumber.

3) On the Control Form, create a Command Button to open an Order Form which uses the selected List Box OrderNumber.  When that Order Form opens, it will populate with the tblCurrentOrders data for that OrderNumber and also populate the subform with tblPlanner data.  (As long as you have them linked properly.)

4) On the Control Form, create a Command Button to open the Order Form with a set of records which are "New Orders" only.  See the more detailed process below in Step C.

5) On the Control Form, create a Command Button to Launch VBA code that will create a "New Order".  This is a multi step process detailed below in Step B.

6) Create any other buttons or controls that allow you to monitor or advance your "Order" along the way to completion.  (This is a ton of work to get all the pieces in place.)

Step B: When you press the Command Button to create a "New Order" you want to create VBA code that will:

1) Create a new record in the tblCurrentOrders table.

2) Create a Unique OrderNumber on the new Record.  It's usually best if you control the generation of this number and don't just let it be a system generated sequence number.  But whatever you desire is ok as long as it's Unique.

3) Set your ReleasedFlag to false on the new tblCurrentOrders record.

4) Make sure your ReleasedTimeStamp is null.  (Or whatever value you want it to be.)

5) You may want a CreatedTimeStamp which you can populate with a date of Now().

6) Populate any other "Initalization" fields that need to be filled.  (Like Backorder status, Return flags, Shorted Flags, etc. etc. etc.)

7) Create a new record in the tblPlanner table.

8) Copy the Unique OrderNumber that you created for the tblCurrentOrders record into the OrderNumber field on the new tblPlanner record. This creates a link for you to use with your subqueries and subforms.

9) Now you can open the Order Form with this new OrderNumber.

Step C: When you press the Command Button to open a set of records which are "New Orders" only:

The Command Button needs to launch a query to find "...tblCurrentOrders that shows only the records without corresponding entries in tblPlanner (new orders)":
You just need to select tblCurrentOrders that have a ReleasedFlag set to false.

`SELECT * FROM tblCurrentOrders WHERE ReleasedFlag = false`

So when you say: "...and then I want to be able to enter the tblPlanner info in a subform"... you can create a subform linking to tblPlanner based on the tblCurrentOrders OrderNumber field.

This is all reliant on you observing that when you say "...records without corresponding entries in tblPlanner..." That you really mean: records without released entries in tblPlanner.  And that means: in order for a record to exist in tblCurrentOrders, it has to have a corresponding blank (or starter) record created in tblPlanner.  Thus now you can display blank tblPlanner records that are linked to unreleased tblCurrentOrders records.

Then once your data entry people are done monkeying around with the New Order, they can "Release" the order (usually by clicking on a Release Command Button).  At that point, you can set your ReleasedTimeStamp to Now() and set your ReleasedFlag to True in the tblCurrentOrders.  It's officially no longer a "new order" and is now a live order in your system.

You are at the tip of the iceberg for creating a home grown order entry system.  The complexities for building a good one are immense. Best of luck figuring it all out.  Just remember to use time stamps and ID fields so you can go back and un-do what may have been done by accident.

Hope this all helps. :)


问:
Apply formatting to all subplots in Jupyter notebook
When plotting 3 pandas dataframe with different time resolution (hourly, daily, monthly) in Jupyter Notebook, I would like to apply a consistent format to all three subplots showing only month and not year (i.e. Jan, Feb, Mar, and not Jan 2010, Feb 2010, Mar 2010).

Question: how to apply the formatting across all subplots?

Import libraries

```<code>import matplotlib
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
%matplotlib inline
</code>```

Create 3 dataframes

```<code>hourly = pd.DataFrame({'val': np.random.rand(24*365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1H'))
daily = pd.DataFrame({'val': np.random.rand(365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1D'))
monthly = pd.DataFrame({'val': np.random.rand(12)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1M'))
</code>```

Plot and apply formatting to three subplots

```<code>def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    hourly[['val']].plot(ax=ax[0], legend=False)
    daily[['val']].plot(ax=ax[1], legend=False)
    monthly[['val']].plot(ax=ax[2], legend=False)

    for axA in ax:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax

plot2(hourly, daily, monthly)
</code>```

The resulting figure shows the desired formatting for the second and third plots, but not the first plot.
Figure showing the first plot is not formatted properly, but the second and third plots are formatted properly

I am using Python 3.5

答:
Seems like pandas has some problems. Using matplolib directly works better:

```<code>def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    ax[0].plot(hourly.index, hourly[['val']])
    ax[1].plot(daily.index, daily[['val']])
    ax[2].plot(monthly.index, monthly[['val']])

    for axA in ax[::-1]:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax
</code>```

Body:
When plotting 3 pandas dataframe with different time resolution (hourly, daily, monthly) in Jupyter Notebook, I would like to apply a consistent format to all three subplots showing only month and not year (i.e. Jan, Feb, Mar, and not Jan 2010, Feb 2010, Mar 2010).

Question: how to apply the formatting across all subplots?

Import libraries

import matplotlib
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
%matplotlib inline

Create 3 dataframes

hourly = pd.DataFrame({'val': np.random.rand(24*365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1H'))
daily = pd.DataFrame({'val': np.random.rand(365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1D'))
monthly = pd.DataFrame({'val': np.random.rand(12)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1M'))

Plot and apply formatting to three subplots

def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    hourly[['val']].plot(ax=ax[0], legend=False)
    daily[['val']].plot(ax=ax[1], legend=False)
    monthly[['val']].plot(ax=ax[2], legend=False)

    for axA in ax:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax

plot2(hourly, daily, monthly)

The resulting figure shows the desired formatting for the second and third plots, but not the first plot.
Figure showing the first plot is not formatted properly, but the second and third plots are formatted properly

I am using Python 3.5

Body:
Seems like pandas has some problems. Using matplolib directly works better:

def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    ax[0].plot(hourly.index, hourly[['val']])
    ax[1].plot(daily.index, daily[['val']])
    ax[2].plot(monthly.index, monthly[['val']])

    for axA in ax[::-1]:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax


问:
Creating a Handle that guarantees hClose failure
I'd like to create a Handle that guarantees failure (exception) when it's passed into hClose. I need this for testing purposes.

How do I create such a Handle?

答:
The module GHC.IO.Handle of the base package has the function mkFileHandle:

mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev   -> FilePath -> IOMode -> Maybe TextEncoding -> NewlineMode  -> IO Handle

IODevice and BufferedIO are typeclasses that provide basic handle operations for a device. In particular, IODevice has the close method.

You can create your own dummy device type, define those two instances for it (with a close that throws an exception) and then use mkFileHandle to obtain a useable Handle.

See the code of the knob package for an example of how to do this.


问:
What method should be used to read XML data in JavaScript?
I ran into a problem in my project where the values of XML nodes were returned as undefined in IE11 while they were returned as the expected valid values in all other browsers, including Edge.

To get the values I was using .innerHTML and after some research, I found out that .innerHTML doesn't work in IE11 and that technically it shouldn't be used to read XML node values in the first place.

I found a few solutions that all seemed hacky to me because they suggested using different methods of reading XML data for different browsers (aka IE11 and everything else). I figured there must be a standard way to read XML data that would work in all browsers since parsing XML is extremely common, not an obscure practice that would have different implementations in different browsers.

I finally found one video where a guy explained using .firstChild.data to read XML node values. I've implemented that in my project and it seems to work fine across all browsers. That's the only time I've come across this method. Everywhere else I looked suggested using .text(), .innerHTML, or .textContent (for IE11).

Is there a reason why .firstChild.data isn't or shouldn't be used and are there other methods that are cross browser compatible that are preferable?

答:
If the firstChild is a text node, then you want to use nodeValue to access its text content. See also the textContent property.

However, the firstChild may NOT be a text node, depending on your data. For example, given this XML document…

```<code><root><a><b>foo</b> bar</a></root>
</code>```

…the firstChild of the  element is an Element with text node child. So you would not want to use firstChild to find the text node.

Further, data is specific to CharacterData interface. If you're sure you have a Text node, then you can use this property. Otherwise, I'd personally use the interfaces on Node itself until you know what type of node you have.

Body:
If the firstChild is a text node, then you want to use nodeValue to access its text content. See also the textContent property.

However, the firstChild may NOT be a text node, depending on your data. For example, given this XML document…

<root><a><b>foo</b> bar</a></root>

…the firstChild of the <a> element is an Element with text node child. So you would not want to use firstChild to find the text node.

Further, data is specific to CharacterData interface. If you're sure you have a Text node, then you can use this property. Otherwise, I'd personally use the interfaces on Node itself until you know what type of node you have.


问:
Curly Braces Inside a _.find Lodash Statement in an AngularJS app
I inherited a monster mess of an AngularJS project at my new job. I've been trying to resolve a bug recently that has the following Lodash statement:

```<code> var group = _.find(groupList, {id: id});
</code>```

From the documentation available on https://lodash.com/docs/3.10.1#find, which is the closest I can find to version 3.7.0, the _.find function iterates over a collection and returns the first object that the statement is "truthy" for. The second item inside the expression would represent a function to be executed.

However, I am confused about what the {id: id} is doing in this instance. Is this an Angular expression? What is it doing here exactly? Any help would be much appreciated.

答:
It means - search for an object in the array, that has the property id, with the value of the variable id.

var groupList = [{ id: 21, name: 'cats' }, { id: 17, name: 'dogs' }, { id: 701, name: 'rats' }];

var id = 17;

var group = _.find(groupList, {id: id});

console.log(group);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
I inherited a monster mess of an AngularJS project at my new job. I've been trying to resolve a bug recently that has the following Lodash statement:

 var group = _.find(groupList, {id: id});

From the documentation available on https://lodash.com/docs/3.10.1#find, which is the closest I can find to version 3.7.0, the _.find function iterates over a collection and returns the first object that the statement is "truthy" for. The second item inside the expression would represent a function to be executed.

However, I am confused about what the {id: id} is doing in this instance. Is this an Angular expression? What is it doing here exactly? Any help would be much appreciated.

Body:
It means - search for an object in the array, that has the property id, with the value of the variable id.

var groupList = [{ id: 21, name: 'cats' }, { id: 17, name: 'dogs' }, { id: 701, name: 'rats' }];

var id = 17;

var group = _.find(groupList, {id: id});

console.log(group);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
How can below template class be generalized to call any function?
```<code>#include <map>
#include <functional>

template<typename... Args>
class Listner {
public:
    template<typename T>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(reinterpret_cast<void*>(t), [&t](Args... args){t->callback(args...); }));
    }

    template<typename T>
    void detachListner(T *t) {
        m_listenerCallbacks.erase(reinterpret_cast<void*>(t));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }
private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};
</code>```

Using above Listner class I am able to register objects which has a public method named callback. Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

答:
First of all: I strongly suggest to pass the t pointers by value, not by reference to the lambda function; so

```<code>m_listenerCallbacks.insert(
   std::make_pair(reinterpret_cast<void*>(t),i
                  [=](Args... args){t->callback(args...); }));
// ----------------^ (not &)
</code>```

Anyway...

Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

As template argument for the class of for the attachListner() method?

In first case, the best (?) I can imagine is a dirty C-macro like based solution (I know... C-macro are distilled evil... but sometimes...).

In the following example, suppose you want a Listner that call the bar() method in all the object registered; you have to call the Listner macro as follows

```<code>Listner(bar);
</code>```

This create a Listner_bar template class that can be used as follows

```<code>Listner_bar<int, std::string const &> l;
</code>```

The following is a full working example

```<code>#include <map>
#include <iostream>
#include <functional>

#define Listner(foo)                                                     \
                                                                         \
template <typename ... Args>                                             \
class Listner_##foo                                                      \
 {                                                                       \
   public:                                                               \
      template <typename T>                                              \
      void attachListner (T * t)                                         \
       { m_listenerCallbacks[reinterpret_cast<void*>(t)]                 \
            = [=](Args... args){(t->*(&T::foo))(args...);}; }            \
                                                                         \
      template <typename T>                                              \
      void detachListner (T * t)                                         \
       { m_listenerCallbacks.erase(reinterpret_cast<void*>(t)); }        \
                                                                         \
      void notify (Args ... args)                                        \
       { for (auto const & l : m_listenerCallbacks) l.second(args...); } \
                                                                         \
   private:                                                              \
      std::map<void*, std::function<void(Args...)>> m_listenerCallbacks; \
 }

struct A
 {
   void bar (int i, std::string const & s)
    { std::cout << "A::bar - " << i << ", " << s << std::endl; }
 };

struct B
 {
   void bar (int i, std::string const & s)
    { std::cout << "B::bar - " << i << ", " << s << std::endl; }
 };

Listner(bar);

int main ()
 {
   Listner_bar<int, std::string const &> l;

   A a;
   B b;

   l.attachListner(&a);
   l.attachListner(&b);

   l.notify(1, "one");

   l.detachListner(&a);

   l.notify(2, "two");
 }
</code>```

If you want that the method name is passed as template argument to attachListner() (so different names for different objects)... not exactly what you want, I suppose, but the best I can imagine is pass pointer method to attachListner() (without C-style macros, this time); something like

```<code>l.attachListner(&a, &A::foo);
</code>```

where a is an object of type A and you want call it's foo() method.

The following is a full working example

```<code>#include <map>
#include <iostream>
#include <functional>

template <typename ... Args>
class Listner
 {
   public:
      template <typename T, typename M>
      void attachListner (T * t, M m)
       { m_listenerCallbacks[reinterpret_cast<void*>(t)]
            = [=](Args... args){(t->*m)(args...);}; }

      template <typename T>
      void detachListner (T * t)
       { m_listenerCallbacks.erase(reinterpret_cast<void*>(t)); }

      void notify (Args ... args)
       { for (auto const & l : m_listenerCallbacks) l.second(args...); }

   private:
      std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
 };

struct A
 {
   void foo (int i, std::string const & s)
    { std::cout << "A::foo - " << i << ", " << s << std::endl; }
 };

struct B
 {
   void bar (int i, std::string const & s)
    { std::cout << "B::bar - " << i << ", " << s << std::endl; }
 };

int main ()
 {
   Listner<int, std::string const &> l;

   A a;
   B b;

   l.attachListner(&a, &A::foo);
   l.attachListner(&b, &B::bar);

   l.notify(1, "one");

   l.detachListner(&a);

   l.notify(2, "two");
 }
</code>```

-- EDIT -- As pointed by skypjack, the second solution work if the method called aren't overloaded. The skypjack answer propose a way to solve this problem.

Body:
#include <map>
#include <functional>

template<typename... Args>
class Listner {
public:
    template<typename T>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(reinterpret_cast<void*>(t), [&t](Args... args){t->callback(args...); }));
    }

    template<typename T>
    void detachListner(T *t) {
        m_listenerCallbacks.erase(reinterpret_cast<void*>(t));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }
private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};

Using above Listner class I am able to register objects which has a public method named callback. Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

Body:
First of all: I strongly suggest to pass the t pointers by value, not by reference to the lambda function; so

m_listenerCallbacks.insert(
   std::make_pair(reinterpret_cast<void*>(t),i
                  [=](Args... args){t->callback(args...); }));
// ----------------^ (not &)

Anyway...

Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

As template argument for the class of for the attachListner() method?

In first case, the best (?) I can imagine is a dirty C-macro like based solution (I know... C-macro are distilled evil... but sometimes...).

In the following example, suppose you want a Listner that call the bar() method in all the object registered; you have to call the Listner macro as follows

Listner(bar);

This create a Listner_bar template class that can be used as follows

Listner_bar<int, std::string const &> l;

The following is a full working example

#include <map>
#include <iostream>
#include <functional>

#define Listner(foo)                                                     \
                                                                         \
template <typename ... Args>                                             \
class Listner_##foo                                                      \
 {                                                                       \
   public:                                                               \
      template <typename T>                                              \
      void attachListner (T * t)                                         \
       { m_listenerCallbacks[reinterpret_cast<void*>(t)]                 \
            = [=](Args... args){(t->*(&T::foo))(args...);}; }            \
                                                                         \
      template <typename T>                                              \
      void detachListner (T * t)                                         \
       { m_listenerCallbacks.erase(reinterpret_cast<void*>(t)); }        \
                                                                         \
      void notify (Args ... args)                                        \
       { for (auto const & l : m_listenerCallbacks) l.second(args...); } \
                                                                         \
   private:                                                              \
      std::map<void*, std::function<void(Args...)>> m_listenerCallbacks; \
 }

struct A
 {
   void bar (int i, std::string const & s)
    { std::cout << "A::bar - " << i << ", " << s << std::endl; }
 };

struct B
 {
   void bar (int i, std::string const & s)
    { std::cout << "B::bar - " << i << ", " << s << std::endl; }
 };

Listner(bar);

int main ()
 {
   Listner_bar<int, std::string const &> l;

   A a;
   B b;

   l.attachListner(&a);
   l.attachListner(&b);

   l.notify(1, "one");

   l.detachListner(&a);

   l.notify(2, "two");
 }

If you want that the method name is passed as template argument to attachListner() (so different names for different objects)... not exactly what you want, I suppose, but the best I can imagine is pass pointer method to attachListner() (without C-style macros, this time); something like

l.attachListner(&a, &A::foo);

where a is an object of type A and you want call it's foo() method.

The following is a full working example

#include <map>
#include <iostream>
#include <functional>

template <typename ... Args>
class Listner
 {
   public:
      template <typename T, typename M>
      void attachListner (T * t, M m)
       { m_listenerCallbacks[reinterpret_cast<void*>(t)]
            = [=](Args... args){(t->*m)(args...);}; }

      template <typename T>
      void detachListner (T * t)
       { m_listenerCallbacks.erase(reinterpret_cast<void*>(t)); }

      void notify (Args ... args)
       { for (auto const & l : m_listenerCallbacks) l.second(args...); }

   private:
      std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
 };

struct A
 {
   void foo (int i, std::string const & s)
    { std::cout << "A::foo - " << i << ", " << s << std::endl; }
 };

struct B
 {
   void bar (int i, std::string const & s)
    { std::cout << "B::bar - " << i << ", " << s << std::endl; }
 };

int main ()
 {
   Listner<int, std::string const &> l;

   A a;
   B b;

   l.attachListner(&a, &A::foo);
   l.attachListner(&b, &B::bar);

   l.notify(1, "one");

   l.detachListner(&a);

   l.notify(2, "two");
 }

-- EDIT -- As pointed by skypjack, the second solution work if the method called aren't overloaded. The skypjack answer propose a way to solve this problem.


问:
Explicit vs implicit SQL joins
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

```<code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code>```

vs.

```<code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code>```

答: Personally I prefer the join syntax as its makes it clearer that the tables are joined and how they are joined. Try compare larger SQL queries where you selecting from 8 different tables and you have lots of filtering in the where. By using join syntax you separate out the parts where the tables are joined, to the part where you are filtering the rows.</p>

OwnerDisplayName: dmanxiii

Title: Explicit vs implicit SQL joins

Body:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: grom


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答:
Why don't you just use a client? They are a lot nicer in my opinion.

I love SQLyog because it supports a lot of MySQL features (stored procedures) but I used to use HeidiSQL and it was nice as well.

As for web based clients, I haven't got any suggestions unfortunately.

OwnerDisplayName: Siamak


问:
What is the equivalent of IE's removeNode
IE's removeNode
http://msdn.microsoft.com/en-us/library/ms536708(VS.85).aspx

helps me to decide whether I would like to remove childNodes or not.

I would like to know whether the same exists for Firefox, Opera, Chrome and Safari. If not, how can I achieve it?

答:
Didn't want just just copy code over, give this a read: http://www.sitepoint.com/forums//showthread.php?p=947385

Edit (but I, pst, have no shame -- code from above link ;-)

```<code>if ( window.Node )
Node.prototype.removeNode = function( removeChildren )
{
    var self = this;
    if ( Boolean( removeChildren ) )
    {
        return this.parentNode.removeChild( self );
    }
    else
    {
        var range = document.createRange();
        range.selectNodeContents( self );
        return this.parentNode.replaceChild( range.extractContents(), self );
    }
}
</code>```

Body:
Didn't want just just copy code over, give this a read: http://www.sitepoint.com/forums//showthread.php?p=947385

Edit (but I, pst, have no shame -- code from above link ;-)

if ( window.Node )
Node.prototype.removeNode = function( removeChildren )
{
    var self = this;
    if ( Boolean( removeChildren ) )
    {
        return this.parentNode.removeChild( self );
    }
    else
    {
        var range = document.createRange();
        range.selectNodeContents( self );
        return this.parentNode.replaceChild( range.extractContents(), self );
    }
}


问:
Using sed to extract element content of an XML file
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Header>
<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>
</Header>
<Body>
</Body>
</Envelope>
</code>```

so i want to get

```<code><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</code>```

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

```<code>sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt
</code>```

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

答:
It would be safier to use an xml parser but for some cases it can also be done with regex.

```<code>perl -0777 -ne 'print for m@<EncryptedKey(?!</EncryptedKey).*</EncryptedKey>@gs' <test.txt
</code>```

from perl -h

-0777 : specify record separator (octal, 777 is undef <=> read all file)

-n : assume "while (<>) { ... }" loop around program

modifiers

g: all matches

s: . matches \n

regex:

(?!..): negative look-ahead

Body:
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>

</Envelope>

so i want to get

<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

Body:
It would be safier to use an xml parser but for some cases it can also be done with regex.

perl -0777 -ne 'print for m@<EncryptedKey(?!</EncryptedKey).*</EncryptedKey>@gs' <test.txt

from perl -h

-0777 : specify record separator (octal, 777 is undef <=> read all file)

-n : assume "while (<>) { ... }" loop around program

modifiers

g: all matches

s: . matches \n

regex:

(?!..): negative look-ahead