问:
how do I paginate records am displaying and filtering using ajax
I have a page that lists all properties on page. This records are filtered based on check boxes clicked. How do I go about pagination. When no filter is applied, I want the records paginated. When filtering is also applied, I want pagination also applied on the records displayed. How do I go about this?.Below is a
sample code that does the filtering. Thank you.

page look like this

This the pagination code I have so far. But how do I apply it on filtered records?

```<code>$totalProperty = "SELECT * FROM property_listing WHERE property_status = 'approved' ";

$allProperty = mysqli_query($connection, $totalProperty);

 $totalProperties = mysqli_num_rows($allProperty);

                        $showRecordPerPage = 4;

                        if(isset($_GET['page']) && !empty($_GET['page'])){
                        $currentPage = $_GET['page'];
                        }else{
                        $currentPage = 1;
                        }
                        $startFrom = ($currentPage * $showRecordPerPage) -
                        $showRecordPerPage;

                        $lastPage = ceil
                        ($totalProperties/$showRecordPerPage);
                        $firstPage = 1;
                        $nextPage = $currentPage + 1;
                        $previousPage = $currentPage - 1;
</code>```

Pagination:

```<code><div class="pagination">
                <nav aria-label="Page navigation example">
                    <ul class="pagination">
                    <?php if($currentPage != $firstPage) { ?>
                    <li class="page-item">
                    <a class="page-link" href="?page=<?php echo $firstPage ?>" tabindex="-1" aria-label="Previous">
                    <span aria-hidden="true">«</span>
                    </a>
                    </li>
                    <?php } ?>
                    <?php if($currentPage >= 2) { ?>
                    <li class="page-item"><a class="page-link" href="?page=<?php echo $previousPage ?>"><?php echo $previousPage ?></a></li>
                    <?php } ?>
                    <li class="page-item active"><a class="page-link" href="?page=<?php echo $currentPage ?>"><?php echo $currentPage ?></a></li>
                    <?php if($currentPage != $lastPage) { ?>
                    <li class="page-item"><a class="page-link" href="?page=<?php echo $nextPage ?>"><?php echo $nextPage ?></a></li>
                    <li class="page-item">
                    <a class="page-link" href="?page=<?php echo $lastPage ?>" aria-label="Next">
                    <span aria-hidden="true">»</span>
                    </a>
                    </li>
                    <?php } ?>
                    </ul>
                </nav>
            </div>

<?php

// This part displays records when filtering is applied
if(isset($_POST["action"])){
    $query = "SELECT * FROM property_listing WHERE property_status ='approved'";

    // This part filters records based on price range (product prices)
    if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"])){
        $query .= " AND property_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'";
    }

    // This part filters records based in product brand
    if(isset($_POST["brand"])){
        $brand_filter = implode("','", $_POST["brand"]);
        $query .= " AND property_type IN('".$brand_filter."')";
    }

    // This part filters records based in product ram
    if(isset($_POST["ram"])){
        $ram_filter = implode("','", $_POST["ram"]);
        $query .= " AND property_category IN('".$ram_filter."')";
     }
 }

                        $select_all_property = mysqli_query($connection, $query);
                        $totalcount = mysqli_num_rows($select_all_property);

                        if($totalcount>0){
                                while($row = mysqli_fetch_assoc($select_all_property)){

                                    $property_id =  $row['property_id'];
                                    $property_link_id =  $row['property_link_id'];
                                    $property_title = $row['property_title'];
                                    $property_city = $row['property_city'];
                                    $property_bed = $row['property_bed'];
                                    $property_bath = $row['property_bath'];
                                    $property_date = $row['property_date'];
                                    $property_location = $row['property_location'];
                                    $gallery1 = $row['gallery1'];
                                    $property_price = number_format($row['property_price'],2);
                                    $property_category = $row['property_category'];
                                    $property_type = $row['property_type'];
                                    $property_ad_status = $row['property_ad_status'];

                                    $timeago=get_timeago($property_date);

                                    ?>

        <div class="item">
            <div class="row">
              <div class="col-lg-5">
                <div class="item-image"> <a href="property_single.php?p_id=<?php echo $property_id; ?>&property_cat=<?php echo $property_category; ?>"><img src="images/property_images/<?php echo $gallery1; ?>" class="img-fluid" alt="">
                  <div class="item-badges">
                  <?php  if($property_ad_status == "featured"){
                             echo       "<div class='item-badge-left'>Sponsored</div>";
                            } ?>
                  <div class="item-badge-right">For <?php echo $property_category; ?></div>
                  </div>
                  <div class="item-meta">
                  <div class="item-price">¢<?php echo $property_price; ?>
                  <small>$777 / sq m</small>
                  </div>
                  </div>
                  </a>
                  <a href="#" class="save-item"><i class="fa fa-star"></i></a> </div>
              </div>
              <div class="col-lg-7">
              <div class="item-info">
                <h3 class="item-title"><a href="property_single.php?p_id=<?php echo $property_id; ?>&property_cat=<?php echo $property_category; ?>"><?php echo $property_title; ?></a></h3>
                <div class="item-location"><i class="fa fa-map-marker"></i> <?php echo $property_location; ?>, <?php echo $property_city; ?></div>
                <div class="item-details-i"> <span class="bedrooms" data-toggle="tooltip" title="3 Bedrooms"><?php echo $property_bed; ?> <i class="fa fa-bed"></i></span> <span class="bathrooms" data-toggle="tooltip" title="2 Bathrooms"><?php echo $property_bath; ?> <i class="fa fa-bath"></i></span> </div>
                <div class="item-details">
                  <ul>
                    <li>Sq Ft <span>730-2600</span></li>
                    <li>Type <span><?php echo $property_type; ?></span></li>
                  </ul>
                </div>
             </div>
                <div class="row">
                <div class="col-md-6">
                                    <div class="added-on">Listed <?php echo $timeago; ?> </div>

                </div>
                <div class="col-md-6">
                                     <a href="#" class="added-by">by John Doe</a>

                </div>
                </div>
              </div>
            </div>
          </div>

<?php }}else{

        echo "<h3>No Data Found</h3>";

        }

} ?>
 ?>
</code>```

Below is also the ajax code for filtering

```<code>$(document).ready(function(){

filter_data();

function filter_data()
{
    $('.filter_data').html('<div id="loading" style="" ></div>');
    var action = 'fetch_data';
    var limit = 4;
    var start = 0;
    var actions = 'inactive';
    var minimum_price = $('#hidden_minimum_price').val();
    var maximum_price = $('#hidden_maximum_price').val();
    var brand = get_filter('type');
    var ram = get_filter('feature');
    $.ajax({
        url:"fetch_data.php",
        method:"POST",
        data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram,},
        success:function(data){
            $('.filter_data').html(data);
        }
    });
}

function get_filter(class_name)
{
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });
    return filter;
}

$('.common_selector').click(function(){
    filter_data();
});

$('#price_range').slider({
    range:true,
    min:100,
    max:9000000,
    values:[100, 9000000],
    step:100,
    stop:function(event, ui)
    {
        $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
        $('#hidden_minimum_price').val(ui.values[0]);
        $('#hidden_maximum_price').val(ui.values[1]);
        filter_data();
    }
});

});
</code>```

答:
To generate paging, use LIMIT clause which will take two arguments. First argument as OFFSET and second argument how many records should be returned from the database.

Here is the Reference : www.tutorialspoint.com

Body:
I have a page that lists all properties on page. This records are filtered based on check boxes clicked. How do I go about pagination. When no filter is applied, I want the records paginated. When filtering is also applied, I want pagination also applied on the records displayed. How do I go about this?.Below is a
sample code that does the filtering. Thank you.

page look like this

This the pagination code I have so far. But how do I apply it on filtered records?

$totalProperty = "SELECT * FROM property_listing WHERE property_status = 'approved' ";

$allProperty = mysqli_query($connection, $totalProperty);

 $totalProperties = mysqli_num_rows($allProperty);

                        $showRecordPerPage = 4;

                        if(isset($_GET['page']) && !empty($_GET['page'])){
                        $currentPage = $_GET['page'];
                        }else{
                        $currentPage = 1;
                        }
                        $startFrom = ($currentPage * $showRecordPerPage) -
                        $showRecordPerPage;

                        $lastPage = ceil
                        ($totalProperties/$showRecordPerPage);
                        $firstPage = 1;
                        $nextPage = $currentPage + 1;
                        $previousPage = $currentPage - 1;

Pagination:

                    <?php if($currentPage != $firstPage) { ?>

                    <a class="page-link" href="?page=<?php echo $firstPage ?>" tabindex="-1" aria-label="Previous">
                    «

                    <?php } ?>
                    <?php if($currentPage >= 2) { ?>

<a class="page-link" href="?page=<?php echo $previousPage ?>"><?php echo $previousPage ?>

                    <?php } ?>

<a class="page-link" href="?page=<?php echo $currentPage ?>"><?php echo $currentPage ?>

                    <?php if($currentPage != $lastPage) { ?>

<a class="page-link" href="?page=<?php echo $nextPage ?>"><?php echo $nextPage ?>

                    <a class="page-link" href="?page=<?php echo $lastPage ?>" aria-label="Next">
                    »

                    <?php } ?>

<?php

// This part displays records when filtering is applied
if(isset($_POST["action"])){
    $query = "SELECT * FROM property_listing WHERE property_status ='approved'";

    // This part filters records based on price range (product prices)
    if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"])){
        $query .= " AND property_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'";
    }

    // This part filters records based in product brand
    if(isset($_POST["brand"])){
        $brand_filter = implode("','", $_POST["brand"]);
        $query .= " AND property_type IN('".$brand_filter."')";
    }

    // This part filters records based in product ram
    if(isset($_POST["ram"])){
        $ram_filter = implode("','", $_POST["ram"]);
        $query .= " AND property_category IN('".$ram_filter."')";
     }
 }

                        $select_all_property = mysqli_query($connection, $query);
                        $totalcount = mysqli_num_rows($select_all_property);

                        if($totalcount>0){
                                while($row = mysqli_fetch_assoc($select_all_property)){

                                    $property_id =  $row['property_id'];
                                    $property_link_id =  $row['property_link_id'];
                                    $property_title = $row['property_title'];
                                    $property_city = $row['property_city'];
                                    $property_bed = $row['property_bed'];
                                    $property_bath = $row['property_bath'];
                                    $property_date = $row['property_date'];
                                    $property_location = $row['property_location'];
                                    $gallery1 = $row['gallery1'];
                                    $property_price = number_format($row['property_price'],2);
                                    $property_category = $row['property_category'];
                                    $property_type = $row['property_type'];
                                    $property_ad_status = $row['property_ad_status'];

                                    $timeago=get_timeago($property_date);

                                    ?>

 <a href="property_single.php?p_id=<?php echo $property_id; ?>&property_cat=<?php echo $property_category; ?>"><img src="images/property_images/<?php echo $gallery1; ?>" class="img-fluid" alt="">

                  <?php  if($property_ad_status == "featured"){
                             echo       "
Sponsored
";
                            } ?>

For <?php echo $property_category; ?>

¢<?php echo $property_price; ?>
                  $777 / sq m

<a href="property_single.php?p_id=<?php echo $property_id; ?>&property_cat=<?php echo $property_category; ?>"><?php echo $property_title; ?>

 <?php echo $property_location; ?>, <?php echo $property_city; ?>

 <?php echo $property_bed; ?>  <?php echo $property_bath; ?>

Sq Ft 730-2600

Type <?php echo $property_type; ?>

Listed <?php echo $timeago; ?>

                                     by John Doe

<?php }}else{

        echo "
No Data Found
";

        }

} ?>
 ?>

Below is also the ajax code for filtering

$(document).ready(function(){

filter_data();

function filter_data()
{
    $('.filter_data').html('

');
    var action = 'fetch_data';
    var limit = 4;
    var start = 0;
    var actions = 'inactive';
    var minimum_price = $('#hidden_minimum_price').val();
    var maximum_price = $('#hidden_maximum_price').val();
    var brand = get_filter('type');
    var ram = get_filter('feature');
    $.ajax({
        url:"fetch_data.php",
        method:"POST",
        data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram,},
        success:function(data){
            $('.filter_data').html(data);
        }
    });
}

function get_filter(class_name)
{
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });
    return filter;
}

$('.common_selector').click(function(){
    filter_data();
});

$('#price_range').slider({
    range:true,
    min:100,
    max:9000000,
    values:[100, 9000000],
    step:100,
    stop:function(event, ui)
    {
        $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
        $('#hidden_minimum_price').val(ui.values[0]);
        $('#hidden_maximum_price').val(ui.values[1]);
        filter_data();
    }
});

});


来源: stackexchange

问:
How to declare an object and assign its properties later
I have the example below that creates a google maps Rectangle Object. I want to only declare the Object, something like 'rectangle = new google.maps.Rectangle()' and then access its properties like 'rectangle.bounds' but seem that this doesn't work</p>

```<code>rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});
</code>```

答:
According to the docs the Rectangle class accepts an optional parameter of type google.maps.RectangleOptions This is the object which actually holds the properties like bounds, editable, and so on.

If you instantiate a new instance of Rectangle like

```<code>rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});
</code>```

only the three properties you defined actually exist. Furthermore the bounds property will be undefined since it's assigned a bounds variable which does not exist.

Unfortunately Google doesn't offer a direct way to create such a RectangleOptions object.

So the proper way would be to create a new general object with all those properties available for a RectangleOptions object and feed those to the constructor of Rectangle.

```<code>var options = {
  bounds: new google.maps.LatLngBounds(),
  clickable: true,
  draggable: false,
  editable: false,
  fillColor: '#FF0000',
  fillOpacity: 1,
  map: new google.maps.Map(""),
  strokeColor: '#FF0000',
  strokeOpacity: 1,
  strokePosition: google.maps.StrokePosition.CENTER,
  strokeWeight: 1,
  visible: true,
  zIndex: 1
}
var rectangle = new google.maps.Rectangle(options);
console.log(rectangle.bounds);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the example below that creates a google maps Rectangle Object. I want to only declare the Object, something like 'rectangle = new google.maps.Rectangle()' and then access its properties like 'rectangle.bounds' but seem that this doesn't work

rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});

Body:
According to the docs the Rectangle class accepts an optional parameter of type google.maps.RectangleOptions This is the object which actually holds the properties like bounds, editable, and so on.

If you instantiate a new instance of Rectangle like

rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});

only the three properties you defined actually exist. Furthermore the bounds property will be undefined since it's assigned a bounds variable which does not exist.

Unfortunately Google doesn't offer a direct way to create such a RectangleOptions object.

So the proper way would be to create a new general object with all those properties available for a RectangleOptions object and feed those to the constructor of Rectangle.

var options = {
  bounds: new google.maps.LatLngBounds(),
  clickable: true,
  draggable: false,
  editable: false,
  fillColor: '#FF0000',
  fillOpacity: 1,
  map: new google.maps.Map(""),
  strokeColor: '#FF0000',
  strokeOpacity: 1,
  strokePosition: google.maps.StrokePosition.CENTER,
  strokeWeight: 1,
  visible: true,
  zIndex: 1
}
var rectangle = new google.maps.Rectangle(options);
console.log(rectangle.bounds);


问:
Specific file name changes en masse
I need some regular expressions help. The scope of this is changing file names. Here is the pattern.

```<code>Super subject - Subject - Subsubject - Extra History - #number--hash.mp4
</code>```

As you can see in the following two examples, the super subject is not always present. I would like to move the #number after the subject and remove the hash at the end.

I need a bash command or script that will accomplish this.

```<code>Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4
Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4
</code>```

I am looking for the output of:

```<code>Africa - Zulu Empire 3 - Diamonds in South Africa - Extra History.mp4
Simón Bolívar 4 - Defeat is Not Surrender - Extra History.mp4
</code>```

I ask this question this way because I know that regex is very specific and I have not learned regex. If there is a specific tool that I can solve this myself, please let me know. This tool needs to be easy to use, please.

答:
If a perl one-liner an option for you, you can do:

Inside the directory that owns the files

```<code>perl -e '@l=glob("*.mp4");for(@l){$old=$_;@e=split(/ - /,$_);($n)=$e[-1]=~/(\d+)/;$_=($e[-5]?"$e[-5] - ":"")."$e[-4] $n - $e[-3] - $e[-2].mp4";rename$old,$_}'
</code>```

Explanation:

```<code>perl -e '                                   # invoke perl
@l=glob("*.mp4");                           # search all mp4 in current directory
for(@l){                                    # for each file found
  $old=$_;                                  # save old name
  @e=split(/ - /,$_);                       # explode filename on ' - '
  ($n)=$e[-1]=~/(\d+)/;                     # extract the number from last element
  $_=                                       # new name
    ($e[-5]?"$e[-5] - ":"").                # first element if exists
    "$e[-4] $n - $e[-3] - $e[-2].mp4";      # all other element except the last
  rename$old,$_                             # rename the file
}'                                          # end script
</code>```

I suggest you to save the original directory before running this

In action with your 2 examples:

```<code>~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:13 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
~/devel/tmp$touch "Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4"
~/devel/tmp$touch "Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4"
~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:13 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4
~/devel/tmp$perl -e '@l=glob("*.mp4");for(@l){$old=$_;@e=split(/ - /,$_);($n)=$e[-1]=~/(\d+)/;$_=($e[-5]?"$e[-5] - ":"")."$e[-4] $n - $e[-3] - $e[-2].mp4";rename$old,$_}'
~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:14 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Africa - Zulu Empire 3 - Diamonds in South Africa - Extra History.mp4
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Simón Bolívar 4 - Defeat is Not Surrender - Extra History.mp4
</code>```

Title: Specific file name changes en masse

Body:
I need some regular expressions help. The scope of this is changing file names. Here is the pattern.

Super subject - Subject - Subsubject - Extra History - #number--hash.mp4

As you can see in the following two examples, the super subject is not always present. I would like to move the #number after the subject and remove the hash at the end.

I need a bash command or script that will accomplish this.

Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4
Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4

I am looking for the output of:

Africa - Zulu Empire 3 - Diamonds in South Africa - Extra History.mp4
Simón Bolívar 4 - Defeat is Not Surrender - Extra History.mp4

I ask this question this way because I know that regex is very specific and I have not learned regex. If there is a specific tool that I can solve this myself, please let me know. This tool needs to be easy to use, please.

Body:
If a perl one-liner an option for you, you can do:

Inside the directory that owns the files

perl -e '@l=glob("*.mp4");for(@l){$old=$_;@e=split(/ - /,$_);($n)=$e[-1]=~/(\d+)/;$_=($e[-5]?"$e[-5] - ":"")."$e[-4] $n - $e[-3] - $e[-2].mp4";rename$old,$_}'

Explanation:

perl -e '                                   # invoke perl
@l=glob("*.mp4");                           # search all mp4 in current directory
for(@l){                                    # for each file found
  $old=$_;                                  # save old name
  @e=split(/ - /,$_);                       # explode filename on ' - '
  ($n)=$e[-1]=~/(\d+)/;                     # extract the number from last element
  $_=                                       # new name
    ($e[-5]?"$e[-5] - ":"").                # first element if exists
    "$e[-4] $n - $e[-3] - $e[-2].mp4";      # all other element except the last
  rename$old,$_                             # rename the file
}'                                          # end script

I suggest you to save the original directory before running this

In action with your 2 examples:

~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:13 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
~/devel/tmp$touch "Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4"
~/devel/tmp$touch "Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4"
~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:13 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Africa - Zulu Empire - Diamonds in South Africa - Extra History - #3--JG-5otw0O8.mp4
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Simón Bolívar - Defeat is Not Surrender - Extra History - #4-Ie0IoiQQFKA.mp4
~/devel/tmp$perl -e '@l=glob("*.mp4");for(@l){$old=$_;@e=split(/ - /,$_);($n)=$e[-1]=~/(\d+)/;$_=($e[-5]?"$e[-5] - ":"")."$e[-4] $n - $e[-3] - $e[-2].mp4";rename$old,$_}'
~/devel/tmp$ll
total 8
drwxr-xr-x 2 olivier olivier 4096 mai   28 17:14 ./
drwxr-xr-x 6 olivier olivier 4096 nov.  19  2018 ../
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Africa - Zulu Empire 3 - Diamonds in South Africa - Extra History.mp4
-rw-r--r-- 1 olivier olivier    0 mai   28 17:13 Simón Bolívar 4 - Defeat is Not Surrender - Extra History.mp4


问:
Comparator for sort, specialization
In a template function a std::vector shall get sorted. T can be a simple type or a std::pair e.g.,

```<code>std::vector<double> or
std::vector<std::pair<int,Something> >
</code>```

When T is a pair then only the first element shall be compared. How can I implement the comparator for the two cases?

I have tried:

```<code>template<typename T>
inline bool smaller(const T& a,const T& b)
{
    return a<b;
}

template<typename T,typename S>
inline bool smaller(
    const std::pair<T,S>& a,
    const std::pair<T,S>& b
    )
{
    return a.first<b.first;
}

template<typename T> inline void function(std::vector<T >& vVec)
{
...bla...
sort(vVec.begin(),vVec.end(),smaller<T>);
...bla...
}
</code>```

but it does not work this way. I have also tried specialization but I do not find the right syntax to specialize the smaller() function.

答:
You could just wrap it in a lambda:</p>

```<code>std::sort(vVec.begin(),vVec.end(), [](const auto& a, const auto& b) { return smaller(a, b); });
</code>```

Title: Comparator for sort, specialization

Body:
In a template function a std::vector shall get sorted. T can be a simple type or a std::pair e.g.,

std::vector<double> or
std::vector<std::pair<int,Something> >

When T is a pair then only the first element shall be compared. How can I implement the comparator for the two cases?

I have tried:

template<typename T>
inline bool smaller(const T& a,const T& b)
{
    return a<b;
}

template<typename T,typename S>
inline bool smaller(
    const std::pair<T,S>& a,
    const std::pair<T,S>& b
    )
{
    return a.first<b.first;
}

template<typename T> inline void function(std::vector<T >& vVec)
{
...bla...
sort(vVec.begin(),vVec.end(),smaller<T>);
...bla...
}

but it does not work this way. I have also tried specialization but I do not find the right syntax to specialize the smaller() function.

Body:
You could just wrap it in a lambda:

std::sort(vVec.begin(),vVec.end(), [](const auto& a, const auto& b) { return smaller(a, b); });


问:
Is it possible to use the HTTP schema in APICONNECT APIs?
I have tried in the api manager and in bluemix, returns this error:

API level schemes must be set to use only "https"
enter image description here
la URL de mi API es: http://54.91.49.213:9443/desarrollo/catalog/ordencompra/v1/grabar.

Is it possible to configure this in the datapower? , if yes, how would the configuration be?

答: If you are using the free ApiConnect available in IBM Cloud, you must use https for every URL in any node (invoke, proxy and for publish URL too), also you can't modify anything in the datapower running below that public  IBM Api Connect.</p>


答:
One easy work around is to make both of your smaller functions opeator()'s of a smaller struct.  Using

```<code>struct smaller
{
    template<typename T>
    bool operator()(const T& a,const T& b)
    {
        return a < b;
    }

    template<typename T, typename S>
    bool operator() (const std::pair<T, S>& a, const std::pair<T, S>& b)
    {
        return a.first < b.first;
    }
};
</code>```

allows you to just pass a smaller to sort like

```<code>template<typename T> inline void function(std::vector<T >& vVec)
{
    sort(vVec.begin(),vVec.end(),smaller{});
}
</code>```

and in sort overload resolution will kick in on the two operator() smaller has and for any std::vector<std::pair>, the std::pair overload will be called.

Title: Comparator for sort, specialization

Body:
One easy work around is to make both of your smaller functions opeator()'s of a smaller struct.  Using

struct smaller
{
    template<typename T>
    bool operator()(const T& a,const T& b)
    {
        return a < b;
    }

    template<typename T, typename S>
    bool operator() (const std::pair<T, S>& a, const std::pair<T, S>& b)
    {
        return a.first < b.first;
    }
};

allows you to just pass a smaller to sort like

template<typename T> inline void function(std::vector<T >& vVec)
{
    sort(vVec.begin(),vVec.end(),smaller{});
}

and in sort overload resolution will kick in on the two operator() smaller has and for any std::vector<std::pair>, the std::pair overload will be called.


问:
changing object keys acording to an array
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

```<code>    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]
</code>```

expected outcome

```<code>    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}
</code>```

答:
You can use reduce:

const object = {
  name1: "some value",
  name3: "some value",
  name2: "some value",
}
const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const newObj = arr1.reduce((acc, value, index) => {
   acc[arr2[index]] = object[value]
   return acc
}, {})

console.log(newObj)```
</div>
</div>
</p>

<p>Reduce will loop over the array 1, use the same index from the second array to assign the key, and compare the value from the first array against the key from the object, and then assign it to the new object.</p>

<p>If readability isn't an issue, you can write the reduce in one line:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const object = {
  name1: "some value",
  name3: "some value",
  name2: "some value",
}
const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const newObj = arr1.reduce((a, v, i) => (a[arr2[i]] = object[v], a), {})

console.log(newObj)</code>```

Body:
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]

expected outcome

    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}

Body:
You can use reduce:

const object = {
  name1: "some value",
  name3: "some value",
  name2: "some value",
}
const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const newObj = arr1.reduce((acc, value, index) => {
   acc[arr2[index]] = object[value]
   return acc
}, {})

console.log(newObj)

Reduce will loop over the array 1, use the same index from the second array to assign the key, and compare the value from the first array against the key from the object, and then assign it to the new object.

If readability isn't an issue, you can write the reduce in one line:

const object = {
  name1: "some value",
  name3: "some value",
  name2: "some value",
}
const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const newObj = arr1.reduce((a, v, i) => (a[arr2[i]] = object[v], a), {})

console.log(newObj)


问:
What’s the function of map()?
What’s is the function of map() in my code?</p>

```<code>squares = list(map(lambda x: x**2, range(10)))
</code>```

答:
In simple terms,

map executes the function for the given iterable objects

Definition:

map() function is used to apply a function on all the elements of
  specified iterable and return map object. Python map object is an
  iterator, so we can iterate over its elements

In your code,

```<code>squares = list(map(lambda x: x**2, range(10)))
</code>```

Function : lambda x: x**2

Ex:

```<code>f = lambda x: x**2
</code>```

f(2) gives 4 as output

Iterable object : range(10)

Ex:
it creates a iterable object of range 0 to 9

```<code>0,1,2,3,4,5,6,7,8,9
</code>```

What map doing is, calling the function for all elements in range,

like f(0), f(1), ... , f(9)

and then You have created the list with output elements.

Title: What’s the function of map()?

Body:
What’s is the function of map() in my code?

squares = list(map(lambda x: x**2, range(10)))

Body:
In simple terms,

map executes the function for the given iterable objects

Definition:

map() function is used to apply a function on all the elements of
  specified iterable and return map object. Python map object is an
  iterator, so we can iterate over its elements

In your code,

squares = list(map(lambda x: x**2, range(10)))

Function : lambda x: x**2

Ex:

f = lambda x: x**2

f(2) gives 4 as output

Iterable object : range(10)

Ex:
it creates a iterable object of range 0 to 9

0,1,2,3,4,5,6,7,8,9

What map doing is, calling the function for all elements in range,

like f(0), f(1), ... , f(9)

and then You have created the list with output elements.


问:
How to get rows of a most recent day in the ascending order of time way when reading csv file?
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

```<code>    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4
</code>```

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

```<code>#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4
</code>```

Could anyone help me?

Thanks in advence.

答:
I'm assuming you can't read the entire file into memory, and the file is in a random order. You can read the file in chunks and iterate through the chunks. </p>

```<code># read 50,000 lines of the file at a time
reader = pd.read_csv(
    'csv_file.csv',
    parse_dates=True,
    chunksize=5e5,
    header=0
)

recent_day=pd.datetime(2019,4,4)
next_day=recent_day + pd.Timedelta(days=1)
df_list=[]

for chunk in reader:
    #check if any rows match the date range
    date_rows = chunk.loc[
        (chunk['operTime'] >= recent_day]) &\
        (chunk['operTime'] < next_day)
    ]
    #append dataframe of matching rows to the list
    if date_rows.empty:
        pass
    else:
        df_list.append(date_rows)

final_df = pd.concat(df_list)
final_df = final_df.sort_values('operTime')
</code>```

Body:
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4

Could anyone help me?

Thanks in advence.

Body:
I'm assuming you can't read the entire file into memory, and the file is in a random order. You can read the file in chunks and iterate through the chunks.

# read 50,000 lines of the file at a time
reader = pd.read_csv(
    'csv_file.csv',
    parse_dates=True,
    chunksize=5e5,
    header=0
)

recent_day=pd.datetime(2019,4,4)
next_day=recent_day + pd.Timedelta(days=1)
df_list=[]

for chunk in reader:
    #check if any rows match the date range
    date_rows = chunk.loc[
        (chunk['operTime'] >= recent_day]) &\
        (chunk['operTime'] < next_day)
    ]
    #append dataframe of matching rows to the list
    if date_rows.empty:
        pass
    else:
        df_list.append(date_rows)

final_df = pd.concat(df_list)
final_df = final_df.sort_values('operTime')


问:
amp-mustache Success/Error Messages Not Displaying
So, I posted this issue last week regarding duplicating headers. I have fixed this issue I do believe but now it's kicking back a new error that I can't seem to solve. I fixed my last issue by stripping out the headers being added a second time inside the PHP of the form submit function and only allowing them to exist in the htaccess.

The only header that exists in the form submit PHP is the setting of the Content-Type to be application/json.

When I submit my form, the submitting message pops up fine. Then when the form submits/fails it does not pass back the message contained within the amp-mustache template tags.

      <template type="amp-mustache">
        Form submitting... Thank you for waiting.
      </template>

      <template type="amp-mustache">
        Thanks, your message has been sent successfully.
      </template>

      <template type="amp-mustache">
        Unfortunately your message could not be sent. Please try again later.
      </template>

```

<p>After a bit of looking around it seems to indicate that my <code>Content-Type</code> is not set to <code>application/json</code> on my PHP that submits the form but when I check the Network tab in Chrome all appears well as far as the headers are concerned.</p>

<p>Response Headers for PHP (xhr-contact-test.php) that submits the form:</p>

```access-control-allow-credentials: true
access-control-allow-headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token
access-control-allow-methods: POST, GET, OPTIONS
access-control-allow-source-origin: https://www.craigattachments.com
access-control-expose-headers: AMP-Access-Control-Allow-Source-Origin
amp-access-control-allow-source-origin: https://www.craigattachments.com
cache-control: max-age=604800
cf-railgun: 4d68972973 0.01 0.656948 0030 cc99
cf-ray: 4de04cf54e22ccfe-EWR
content-encoding: br
content-security-policy: default-src * data: blob:; img-src * 'self' data: https: https://static.craigmanufacturing.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.ampproject.org/v0.js https://cdn.ampproject.org/v0/ https://cdn.ampproject.org/viewer/ https://cdn.ampproject.org/v/ https://cdn.ampproject.org/rtv/ https://static.craigmanufacturing.com *.google.com https://maps.googleapis.com/maps/api/js/ https://maps.googleapis.com/maps/api/place/js/ https://cdn.polyfill.io https://cdnjs.cloudflare.com/ajax/; object-src 'self' https://www.craigattachments.com/pdf/; media-src 'self' https://www.craigattachments.com/pdf/; plugin-types application/pdf; style-src 'self' 'unsafe-inline' https://static.craigmanufacturing.com https://cdn.ampproject.org/rtv/ https://fonts.googleapis.com/; base-uri 'self';
content-type: application/json
date: Tue, 28 May 2019 12:41:04 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
expires: Tue, 04 Jun 2019 12:41:03 GMT
feature-policy: microphone 'none'; payment 'none'; geolocation *; sync-xhr 'self' https://www.craigattachments.com
referrer-policy: same-origin
server: cloudflare
status: 200
strict-transport-security: max-age=31536000
vary: User-Agent
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
```

The error it's passing back is below and points to line 1073 on the amp-form.js which is the function that sets the i-amphtml-rendered attribute on the appropriate amp-mustache template tag. Looking into that is what lead me to thinking the content-type is what was causing the issue but that now appears to be set correctly and the error persists.

Uncaught (in promise) TypeError: b.setAttribute is not a function

I have opened up my testing contact form at this link: https://www.craigattachments.com/contact-us-test/.

Any thoughts on where I should go next? I have tried a few things such as testing for the existence of certain headers, setting the Content-Type inside my htaccess and setting my headers only in the PHP.

Solution for anyone else that gets hung up on this... If you echo out your email as an array such as echo json_encode(array($email)); this error occurs. Taking the array out of the equation seems to fix it for me anyway - echo json_encode($email);

Update 2019/06/12: Huge thanks to Aaron. This issue has been given some better error handling parameters should anyone run up against this in the future: https://github.com/ampproject/amphtml/pull/22576

答:
I took a quick look and it looks like the returned object from the renderTemplate method is an array as opposed to an element.

https://github.com/ampproject/amphtml/blob/master/extensions/amp-form/0.1/amp-form.js#L1121

Possible there is a bug in the code. Inspecting the divs, it looks they are all the same success message as well. Is it possible to reproduce this is a much simpler form demo, with just just the bare minimum to reproduce. e.g. just the form
Thanks

Body:
So, I posted this issue last week regarding duplicating headers. I have fixed this issue I do believe but now it's kicking back a new error that I can't seem to solve. I fixed my last issue by stripping out the headers being added a second time inside the PHP of the form submit function and only allowing them to exist in the htaccess.

The only header that exists in the form submit PHP is the setting of the Content-Type to be application/json.

When I submit my form, the submitting message pops up fine. Then when the form submits/fails it does not pass back the message contained within the amp-mustache template tags.

      <template type="amp-mustache">
        Form submitting... Thank you for waiting.
      </template>

      <template type="amp-mustache">
        Thanks, your message has been sent successfully.
      </template>

      <template type="amp-mustache">
        Unfortunately your message could not be sent. Please try again later.
      </template>

After a bit of looking around it seems to indicate that my Content-Type is not set to application/json on my PHP that submits the form but when I check the Network tab in Chrome all appears well as far as the headers are concerned.

Response Headers for PHP (xhr-contact-test.php) that submits the form:

access-control-allow-credentials: true
access-control-allow-headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token
access-control-allow-methods: POST, GET, OPTIONS
access-control-allow-source-origin: https://www.craigattachments.com
access-control-expose-headers: AMP-Access-Control-Allow-Source-Origin
amp-access-control-allow-source-origin: https://www.craigattachments.com
cache-control: max-age=604800
cf-railgun: 4d68972973 0.01 0.656948 0030 cc99
cf-ray: 4de04cf54e22ccfe-EWR
content-encoding: br
content-security-policy: default-src * data: blob:; img-src * 'self' data: https: https://static.craigmanufacturing.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.ampproject.org/v0.js https://cdn.ampproject.org/v0/ https://cdn.ampproject.org/viewer/ https://cdn.ampproject.org/v/ https://cdn.ampproject.org/rtv/ https://static.craigmanufacturing.com *.google.com https://maps.googleapis.com/maps/api/js/ https://maps.googleapis.com/maps/api/place/js/ https://cdn.polyfill.io https://cdnjs.cloudflare.com/ajax/; object-src 'self' https://www.craigattachments.com/pdf/; media-src 'self' https://www.craigattachments.com/pdf/; plugin-types application/pdf; style-src 'self' 'unsafe-inline' https://static.craigmanufacturing.com https://cdn.ampproject.org/rtv/ https://fonts.googleapis.com/; base-uri 'self';
content-type: application/json
date: Tue, 28 May 2019 12:41:04 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
expires: Tue, 04 Jun 2019 12:41:03 GMT
feature-policy: microphone 'none'; payment 'none'; geolocation *; sync-xhr 'self' https://www.craigattachments.com
referrer-policy: same-origin
server: cloudflare
status: 200
strict-transport-security: max-age=31536000
vary: User-Agent
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block

The error it's passing back is below and points to line 1073 on the amp-form.js which is the function that sets the i-amphtml-rendered attribute on the appropriate amp-mustache template tag. Looking into that is what lead me to thinking the content-type is what was causing the issue but that now appears to be set correctly and the error persists.

Uncaught (in promise) TypeError: b.setAttribute is not a function

I have opened up my testing contact form at this link: https://www.craigattachments.com/contact-us-test/.

Any thoughts on where I should go next? I have tried a few things such as testing for the existence of certain headers, setting the Content-Type inside my htaccess and setting my headers only in the PHP.

Solution for anyone else that gets hung up on this... If you echo out your email as an array such as echo json_encode(array($email)); this error occurs. Taking the array out of the equation seems to fix it for me anyway - echo json_encode($email);

Update 2019/06/12: Huge thanks to Aaron. This issue has been given some better error handling parameters should anyone run up against this in the future: https://github.com/ampproject/amphtml/pull/22576


问:
How to write response filter?
Is there a way to handle only response in a filter .

Is the code written below correct ?

```<code>  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }
</code>```

答:
The code you show is not entirely correct, but with a necessary simplification of the terminology - it is. You can "handle" a request even after chain.doFilter(..) (and response before it).

What chain.doFilter(..) means is that the process is passed to the desired target, and when the method returns, the target has completed its output.

So to be more precise - it is 'before' and 'after' the request has been processed and a response - generated.

ContentLicense: CC BY-SA 3.0

Title: How to write response filter?

Body:
Is there a way to handle only response in a filter .

Is the code written below correct ?

  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }


问:
Converting row to columns in mysql
My table is coming from the output of a stored procedure. It looks like :

```<code>col1
A
B
C
D
</code>```

It can have less than or equal to 5 rows.

I want it to look like this

```<code>Column1  Column2 Column3  Column4  column5
A          B      C         D       NULL
</code>```

Is there a way to achieve this in MYSQL?

答:
Below MySQL 8.0 the approach becomes much more complex..

The simple explainment about the hard part the first query

The subquery within

```<code>  SELECT
     GROUP_CONCAT(t.col1 ORDER BY col1 ASC) AS cvs
   , COUNT(*) AS t_count
  FROM
   t
</code>```

is making a comma separated values list.
Then the SQL number generator in combination with nested SUBSTRING_INDEX() functions is splitting the comma separated values into records.
Which is then merged into one string by GROUP_CONCAT() into the user variable basically iam generating dynamic SQL which lookes like '<value>' AS Column<number>[, ...] that is what SELECT @aggregateSQLPart; shows you

Query

```<code>SET @aggregateSQLPart = NULL;

# set max of GROUP_CONCAT higher as it defaults to 1024 bytes.
SET SESSION group_concat_max_len = @@max_allowed_packet;

SELECT
 DISTINCT
   GROUP_CONCAT(CONCAT("'",
    SUBSTRING_INDEX(
       SUBSTRING_INDEX(
          t.cvs
         , ','
       , number_generator.number
      )
      , ','
      , -1
    ) , "'" , " AS Column", number_generator.number
 ))
INTO @aggregateSQLPart
FROM (
   SELECT
     @row := @row + 1 AS number
   FROM (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
      ) row1
      CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION  SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) row2
    CROSS JOIN (
      SELECT @row := 0
    ) init_user_params
  ) AS number_generator
 CROSS JOIN (
  SELECT
     GROUP_CONCAT(t.col1 ORDER BY col1 ASC) AS cvs
   , COUNT(*) AS t_count
  FROM
   t
 ) AS t

WHERE
 number BETWEEN 1 AND t_count;

SELECT @aggregateSQLPart;

SET @SQL = CONCAT("
 SELECT
 "
 , @aggregateSQLPart
);

SELECT @SQL;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Result

```<code>| Column1 | Column2 | Column3 | Column4 | Column5 |
| ------- | ------- | ------- | ------- | ------- |
| A       | B       | C       | D       | E       |
</code>```

see demo

Note do not doubt about performance it runs in about a average off 5-10 ms in total on a "test" server.. Also note i select the user variables so you can see whats happing in between.

Title: Converting row to columns in mysql

Body:
My table is coming from the output of a stored procedure. It looks like :

col1
A
B
C
D

It can have less than or equal to 5 rows.

I want it to look like this

Column1  Column2 Column3  Column4  column5
A          B      C         D       NULL

Is there a way to achieve this in MYSQL?

Body:
Below MySQL 8.0 the approach becomes much more complex..

The simple explainment about the hard part the first query

The subquery within

  SELECT
     GROUP_CONCAT(t.col1 ORDER BY col1 ASC) AS cvs
   , COUNT(*) AS t_count
  FROM
   t

is making a comma separated values list.
Then the SQL number generator in combination with nested SUBSTRING_INDEX() functions is splitting the comma separated values into records.
Which is then merged into one string by GROUP_CONCAT() into the user variable basically iam generating dynamic SQL which lookes like '<value>' AS Column<number>[, ...] that is what SELECT @aggregateSQLPart; shows you

Query

SET @aggregateSQLPart = NULL;

# set max of GROUP_CONCAT higher as it defaults to 1024 bytes.
SET SESSION group_concat_max_len = @@max_allowed_packet;

SELECT
 DISTINCT
   GROUP_CONCAT(CONCAT("'",
    SUBSTRING_INDEX(
       SUBSTRING_INDEX(
          t.cvs
         , ','
       , number_generator.number
      )
      , ','
      , -1
    ) , "'" , " AS Column", number_generator.number
 ))
INTO @aggregateSQLPart
FROM (
   SELECT
     @row := @row + 1 AS number
   FROM (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
      ) row1
      CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION  SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) row2
    CROSS JOIN (
      SELECT @row := 0
    ) init_user_params
  ) AS number_generator
 CROSS JOIN (
  SELECT
     GROUP_CONCAT(t.col1 ORDER BY col1 ASC) AS cvs
   , COUNT(*) AS t_count
  FROM
   t
 ) AS t

WHERE
 number BETWEEN 1 AND t_count;

SELECT @aggregateSQLPart;

SET @SQL = CONCAT("
 SELECT
 "
 , @aggregateSQLPart
);

SELECT @SQL;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Result

| Column1 | Column2 | Column3 | Column4 | Column5 |
| ------- | ------- | ------- | ------- | ------- |
| A       | B       | C       | D       | E       |

see demo

Note do not doubt about performance it runs in about a average off 5-10 ms in total on a "test" server.. Also note i select the user variables so you can see whats happing in between.


问:
Angular - matDatepicker not working properly
I have 3 components

main.component.html

mobile-main.component.html

desktop-main.component.html

Based on device width i want to load different view(totally different UI) using MediaMatcher & ChangeDetectorRef

My problem is when using matDatepicker it's not working properly.
When I change orientation Desktop / Mobile UI loaded working properly, But when I click on date picker it's not popping up after changing orientation(but popping up from 2nd click onwards).

We can use chrome toggle-device-toolbar to simulate.

main.component.html

<app-desktop-main *ngIf="!mobileQuery.matches"></app-desktop-main>
<app-mobile-main *ngIf="mobileQuery.matches"></app-mobile-main>
```

<p><strong>main.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export class MainComponent implements OnInit, OnDestroy {

  mobileQuery: MediaQueryList;

  _mobileQueryListener: () => void;

constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 760px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

}
</code>```

mobile-main.component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
```

<p><strong>mobile-main.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export class MobileMainComponent implements OnInit, OnDestroy {

constructor() {

  }

}
</code>```

desktop-main.component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
```

<p><strong>desktop-main.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export class DesktopMainComponent implements OnInit, OnDestroy {

constructor() {

  }

}
</code>```

答:
Material datepicker has an option for touch ui. For your mobile component add touchUi for what was the dropdown element:

```<code><mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker touchUi #picker></mat-datepicker>
</mat-form-field>
</code>```

I'm not sure that will help the weird behavior you are noticing, but since you are not using something that is optimized for mobile it may solve the issue.

Body:
I have 3 components

main.component.html

mobile-main.component.html

desktop-main.component.html

Based on device width i want to load different view(totally different UI) using MediaMatcher & ChangeDetectorRef

My problem is when using matDatepicker it's not working properly.
When I change orientation Desktop / Mobile UI loaded working properly, But when I click on date picker it's not popping up after changing orientation(but popping up from 2nd click onwards).

We can use chrome toggle-device-toolbar to simulate.

main.component.html

<app-desktop-main *ngIf="!mobileQuery.matches"></app-desktop-main>
<app-mobile-main *ngIf="mobileQuery.matches"></app-mobile-main>

main.component.ts

export class MainComponent implements OnInit, OnDestroy {

  mobileQuery: MediaQueryList;

  _mobileQueryListener: () => void;

constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 760px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

}

mobile-main.component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

mobile-main.component.ts

export class MobileMainComponent implements OnInit, OnDestroy {

constructor() {

  }

}

desktop-main.component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

desktop-main.component.ts

export class DesktopMainComponent implements OnInit, OnDestroy {

constructor() {

  }

}

Body:
Material datepicker has an option for touch ui. For your mobile component add touchUi for what was the dropdown element:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker touchUi #picker></mat-datepicker>
</mat-form-field>

I'm not sure that will help the weird behavior you are noticing, but since you are not using something that is optimized for mobile it may solve the issue.


问:
Differentiating staging and production admin pages by colour in Magento 2
I often have the admin pages for my staging sites and my production site open simultaneously. There's a big risk I'll inadvertently take an action on the wrong site so I manually edit the admin css files for each to make the toolbar a different colour in each. That way I can see instantly which site I'm on.

I was wondering whether there's a way of injecting a class (or something similar) from the htaccess file for each site. This is something fixed for each site so wouldn't need me to edit the css file each time I make a change that affects it.

答: You could include an empty css file in your admin theme, then put it on gitignore and fill in your desired deviation on the staging system. Just make sure you override the default css that is not on gitignore.</p>


问:
What is the easiest way to keep a Sharepoint and Epicor database in sync?
I have a programming internship at a small manufacturing company, and I have been tasked with adding customizations to the company's Epicor ERP and Sharepoint online platforms that will link databases from both platforms to each other.

I believe the best way forward would be to build a customization for one of the platforms using Odata REST API, and set it to sync the databases daily.  Unfortunately, while I have built basic Sharepoint webparts already, I have not worked with Epicor ERP before, and it seems to be difficult to find documentation for the platform.

I think it may be preferable to use an Epicor customization, since we don't host our Sharepoint site directly, and the company does not have a permanent developer who can make sure a webpart keeps up with Sharepoint online's automatic updates.

All that being said, how should I proceed with this task?

答:
This is more of a broad integration question between SharePoint and Epicor ERP, but here is one possible approach breaking down the components of your issue.  What is "Easiest" will be subjective based on your skillset and experience with configuring security certificates, but I'll assume both your SharePoint and Epicor ERP REST APIs are readily accessible.

Problem Statement:

Push part data in one-direction from SharePoint into Epicor ERP.

Components of Solution:

Create component to gather SharePoint Source Data

Create component to write Epicor ERP data

Create scheduling or real time monitoring component.

One possible solution:

Write a class or program which reads new SharePoint data via the SharePoint REST endpoint and writes that information into a row in a database.

Write a class or program which reads information from your database row and writes it to your Epicor ERP system through your Epicor ERP REST endpoint.

Write a class or program to execute your other two classes/programs and provide status updates or failure notifications to a configurable distribution list.  Schedule this program to run nightly.

Suggestion Additional Info:

SharePoint has a REST API that can be used to access documents and metadata. If this is insufficient to gather the data you need in order to write to Epicor ERP, you may need to perform further processing based on records retrieved using the SharePoint API.

Epicor ERP uses encapsulated business logic to write to the database. If your REST API service has been configured, you will find it at a swagger endpoint similar to the following: https://[YourServer]/[YourAppServer]/api/help This will give you a full searchable service listing.  You will need Erp.BO.PartSvc as the primary service for your work.  However, if you also need to configure Bill of Materials, you will need Erp.BO.EngWorkBenchSvc.  If you are unaware of the steps that need to be performed in order to create the part in Epicor, you can perform a trace within the application by enabling server side tracing in order to obtain the service calls so that you can replicate the functionality by passing data in JSON objects over the REST API. Business object and customization documentation is not in the public domain, though as an Epicor customer, they are accessible via your EpicWeb portal.  The following documents will provide additional information to you:

EpicorApplication_UserGuide - Explains how to perform part-related activities using the normal application logic

EpicorCustomization_UserGuide - Explains how to perform any customizations within the application as well as how to enable tracing

EpicorICETools_UserGuide - Explains how to use Epicor proprietary query and server-side customization tools.

ERP_BO_Ref.chm - Provides a full Epicor ERP BO Service Listing and details on what each method does

You should be able to run a program on a trigger as a SharePoint object is modified, but I would recommend decoupling the systems and performing the data integration asynchronously on a schedule during off-hours just in case the number of parts puts a heavy load on your ERP system and could potentially impact MES users and your manufacturing work floor.


问:
Opening a Report based on two date values on a form if they exist
I have a form (frmReports) that has two unbound textboxes which are used to enter dates.  One is FROM, one is TO.

These are used to filter out a report (rptAllCommissions).  If there are values in the textboxes, it filters.  If there aren't, or if there's one date and not both, it creates a WHERE statement for opening the report.  Here is the code:

```<code>Private Sub cmdCommissions_Click()
    Dim strDateFrom As String
    Dim strDateTo As String
    Dim strWhere As String

    Const strcJetDate = "\#mm\/dd\/yyyy\#"

    strDateFrom = "[ClosingDate]"

    If IsDate(Me.txtFrom) Then
        strWhere = "(" & strDateFrom & " >=" & Format(Me.txtFrom, strcJetDate) & ")"
    End If
    If IsDate(Me.txtTo) Then

        If strWhere <> vbNullString Then
            strWhere = strWhere & " AND "
        End If

        strWhere = strWhere & "(" & strDateFrom & " <= " & Format(Me.txtTo + 1, strcJetDate) & ")"
    End If

    If CurrentProject.AllReports("rptAllCommissions").IsLoaded Then
        DoCmd.Close acReport, "rptAllCommissions"
    End If
    Debug.Print strWhere

    DoCmd.OpenReport "rptAllCommissions", acViewReport, strWhere

Exit_Handler:
    Exit Sub

Err_Handler:
    If Err.Number <> 2501 Then
        MsgBox "Error" & Err.Number & ": " & Err.Description, vbExclamation, "Cannot Open Report!"
    End If
    Resume Exit_Handler

End Sub
</code>```

The problem I'm having is no matter what I try, the report never filters the records based on the WHERE statement created by the above routine.  Trying debugging, it outputs:

If two dates are entered: ([ClosingDate] >=#04/01/2019#) AND ([ClosingDate] <= #05/25/2019#)

If one date is entered: ([ClosingDate] >=#05/13/2019#)

That seems right to me, but it's not filtering.  What the heck am I doing wrong?

EDIT: I should give credit the person who wrote the original routine, but I can't for the life of me find where I got it.  Sorry!  But whoever it was that originally wrote the routine, THANKS!

答:
The WhereCondition should be the 4th argument in the OpenReport method. You have it in the FilterName argument's spot.

OpenReport

Body:
I have a form (frmReports) that has two unbound textboxes which are used to enter dates.  One is FROM, one is TO.

These are used to filter out a report (rptAllCommissions).  If there are values in the textboxes, it filters.  If there aren't, or if there's one date and not both, it creates a WHERE statement for opening the report.  Here is the code:

Private Sub cmdCommissions_Click()
    Dim strDateFrom As String
    Dim strDateTo As String
    Dim strWhere As String

    Const strcJetDate = "\#mm\/dd\/yyyy\#"

    strDateFrom = "[ClosingDate]"

    If IsDate(Me.txtFrom) Then
        strWhere = "(" & strDateFrom & " >=" & Format(Me.txtFrom, strcJetDate) & ")"
    End If
    If IsDate(Me.txtTo) Then

        If strWhere <> vbNullString Then
            strWhere = strWhere & " AND "
        End If

        strWhere = strWhere & "(" & strDateFrom & " <= " & Format(Me.txtTo + 1, strcJetDate) & ")"
    End If

    If CurrentProject.AllReports("rptAllCommissions").IsLoaded Then
        DoCmd.Close acReport, "rptAllCommissions"
    End If
    Debug.Print strWhere

    DoCmd.OpenReport "rptAllCommissions", acViewReport, strWhere

Exit_Handler:
    Exit Sub

Err_Handler:
    If Err.Number <> 2501 Then
        MsgBox "Error" & Err.Number & ": " & Err.Description, vbExclamation, "Cannot Open Report!"
    End If
    Resume Exit_Handler

End Sub

The problem I'm having is no matter what I try, the report never filters the records based on the WHERE statement created by the above routine.  Trying debugging, it outputs:

If two dates are entered: ([ClosingDate] >=#04/01/2019#) AND ([ClosingDate] <= #05/25/2019#)

If one date is entered: ([ClosingDate] >=#05/13/2019#)

That seems right to me, but it's not filtering.  What the heck am I doing wrong?

EDIT: I should give credit the person who wrote the original routine, but I can't for the life of me find where I got it.  Sorry!  But whoever it was that originally wrote the routine, THANKS!


问:
Override "readonly" attribute of a field in one2many relation
Let's suppose the following code :

```<code><field name="object_ids" attrs="{'readonly': [('state', 'not in', ['A', 'B'])]}">
    <form string="My object" version="7.0">
        <field name="object_name"/>
        <field name="object_description"/>
    </form>
</field>
</code>```

This is an example, just to illustrate a definition of a form view for a one2many field.

Is there a way to override the readonly attribute set in the object_ids child fields (object_name) ?

In this case, my whole form view will be readonly for the states specified, but I would like to bypass / override this attribute for a specific field. For example :

```<code>...
<field name="object_name" attrs="{'readonly': False}"> <!-- overrides the readonly set -->
...
</code>```

Is there a way to do this ? Or do I have to remove the attribute from the one2many field and add it to each field ? The goal here is to avoid having this attribute repeated for each field (time consuming, error prone because of inherits of views).

答: From the comment of @EasyOdoo below, this seems not possible without redefining attributes of the one2many field.

Body:
Let's suppose the following code :

<field name="object_ids" attrs="{'readonly': [('state', 'not in', ['A', 'B'])]}">
    <form string="My object" version="7.0">
        <field name="object_name"/>
        <field name="object_description"/>
    </form>
</field>

This is an example, just to illustrate a definition of a form view for a one2many field.

Is there a way to override the readonly attribute set in the object_ids child fields (object_name) ?

In this case, my whole form view will be readonly for the states specified, but I would like to bypass / override this attribute for a specific field. For example :

...
<field name="object_name" attrs="{'readonly': False}">
...

Is there a way to do this ? Or do I have to remove the attribute from the one2many field and add it to each field ? The goal here is to avoid having this attribute repeated for each field (time consuming, error prone because of inherits of views).


问:
Why is splice method removing only first array index in React?
I'm making a small application in React with the PokeAPI and am having issues with using the splice() method to remove an element (pokemon) from the array (team). No matter which element I pick to remove it only removes the first element in the array.

This is the function -- which is being passed down through props -- I'm using in order to delete the item.

```<code>removePokemon = (index) => {
  const team = [...this.state.team]
   team.splice(index, 1)
   this.setState({team})
  }
</code>```

And here is the Team component where it's actually being used.

```<code>import React, { Component } from 'react';
import Button from 'react-bootstrap/Button'

class Team extends Component {
    render() {
        return (
            <div>
                <h2>{this.props.trainer && <p>{this.props.trainer}'s Team</p>}</h2>
                {this.props.team &&
                <div>
                    {this.props.team.map((pokemon, i) => (
                        <div key={pokemon.id}>
                            <span className='cardHeader'>#{pokemon.id} - {pokemon.name}</span>
                            <img src={pokemon.sprites.front_default} alt={pokemon.name}/>
                            <Button onClick={this.props.removePokemon}>Remove from team</Button>
                        </div>
                    ))}
                </div>
                }

            </div>
        );
    }
}

export default Team;
</code>```

答:
You don't pass an argument index to your function removePokemon:

You need to edit one row:

```<code><Button onClick={() => this.props.removePokemon(i)}>Remove from team</Button>
</code>```

Body:
I'm making a small application in React with the PokeAPI and am having issues with using the splice() method to remove an element (pokemon) from the array (team). No matter which element I pick to remove it only removes the first element in the array.

This is the function -- which is being passed down through props -- I'm using in order to delete the item.

removePokemon = (index) => {
  const team = [...this.state.team]
   team.splice(index, 1)
   this.setState({team})
  }

And here is the Team component where it's actually being used.

import React, { Component } from 'react';
import Button from 'react-bootstrap/Button'

class Team extends Component {
    render() {
        return (

{this.props.trainer &&
{this.props.trainer}'s Team
}

                {this.props.team &&

                    {this.props.team.map((pokemon, i) => (

                            #{pokemon.id} - {pokemon.name}

                            <Button onClick={this.props.removePokemon}>Remove from team</Button>

                    ))}

                }

        );
    }
}

export default Team;

Body:
You don't pass an argument index to your function removePokemon:

You need to edit one row:

<Button onClick={() => this.props.removePokemon(i)}>Remove from team</Button>


答: The map function is function used to apply on elements specified in the iteration. In your example, the iteration is range(10) (0 to 9) and applying the function square of each number from 0 to 9. Map returns a list of squared numbers from 0 to 81.</p>

Title: What’s the function of map()?


问:
Unique ID for TaskItem in Outlook
I'm importing all the tasks from outlook into a database.

To flag those that are different since the last import I need a unique ID for each task item object that does not change.

I've looked at TaskItem.EntryID. The microsoft documentation says it's only unique to each storage location which is fine as these tasks won't be moved.

The trouble is with recurrences:

I make a recurrent task due on 28/05/2019 which has an ID of ..D890000

I complete the task and outlook creates the new task for the next scheduled day.

The original task for 28/05/2019 now has a DIFFERENT ID of ..D8A0000
The new task for 29/05/2019 has the original ID of ..D890000

I have also tried using PR_SEARCH_KEY which is the same across these tasks.

Would anyone be able to tell me how to get a unique ID for each TaskItem that persists.

Or would you be able to confirm that the only time it will change is in the event of recursive tasks?

Many Thanks

答: It works as expected - when an instance of a recurring task is completed, Outlook creates a completed task for the current date and advances the existing recurring task to the next day while decrementing the recurrence count.</p>

Title: Unique ID for TaskItem in Outlook


问:
AWS ELB return 404 for https://domain_name:8000 but accessible via public_ip:8000
I'm a beginner to deploying web apps on AWS and I believe I have a similar issue to AWS forward port 8000 from elb to port 8000 of EC2 where I have a reactjs frontend and golang api running on aws ec2 and the golang api is running on port 8000 which is accessible via my public_ip:8000 and gaves me messages saying my golang api is operational when I access public_ip:8000. I created the public_ip using Elastic IPs.

I used load balancers to get HTTPS as I have certain features that only work with HTTPS. However when I use my https://domain_name:8000 to send requests to my own API, it says it isn't there and gives me 404 errors when I used an Application Load Balancer.

My domain name uses AWS's Route 53 and AWS nameservers and should have no issues as I am being directed to my normal domain properly. I've added an A record pointing to my load balancer as well.

I've checked the security group used and I have opened up the ports to my IP address.

My Instance Status Checks:

Below is how I've configured my Application Load Balancer's Target Group:

and for my Listeners I've used HTTP 80, HTTPS 443 and HTTPS 8000 to forward to my target group.

I have tried using classic load balancers as mentioned in the link but they all timeout when I use my domain_name.

Anyone know either a better way to connect or a better way to structure my reactjs frontend and golang backend app on AWS that might need other ports open for api access.

My Classic Load balancer port forwarding config:

EDIT: I've noticed the problem might be my target group as it says that port 8000 is unhealthy and that the request timed out

答:
It was taking forever to figure out the ports and none of the google searches or AWS documentation was helpful so I put my reactjs frontend in one EC2 Instance running on port 80 and my server/golang API into another EC2 instance running on port 80 and then set up the Application Load Balancer to forward to a target group with the frontend if HTTP:80 or HTTPS:443 is called and forward to the target group with the golang API if HTTPS:8000 is called.

Make sure that the instances are in the same availability zone as the load balancer or else it won't work properly and also ensure everything is healthy.


问:
Connect Google sheets to azure Sql Database
HI i would like to connect my google sheets to azure and update my table automatically as any changes done in google sheets

i have try using Microsoft flow but doesn't work

答:
Check out SeekWell, you can schedule refreshes from Sheets to your database up to every 5 minutes.

Disclaimer - I'm a cofounder at SeekWell.


问:
Wildcard in JVM options
I have a jar which is pulled in to a build via Maven, and consequently the version is included in the name of the jar, for example:

newrelic-agent-5.0.0.jar

When exporting the JVM options, in order to run the jar this file needs to be included, however this has caused a problem if we want the JVM options to be agnostic of the version number, and accept whatever version is in the build.

If the JVM options are as follows:

export JVM_OPTS="... -javaagent:/path/to/lib/newrelic-agent. ? .jar"

What can the ? be replaced with such that the JVM options find the jar in question without specifying the version of the dependency? Assuming that there will only ever be one jar that will match this file name pattern.

答:
No glob (*, ?, or something like that) works inside quotes ("…"). You have to unquote the part with the glob. However, "… -javaagent:/path/to/lib/newrelic-agent-"*".jar" won't work since the glob would then try to find a file starting with … -javaagent:.

Therefore, glob the jar in a separate variable and use that variable. Since there could be no or multiple versions of the library you might want to use a check and warn the user

```<code>#! /bin/bash
lib=("/path/to/lib/newrelic-agent-"*.jar)
if [ "${#lib[@]}" != 1 ]; then
    echo "Found no or multiple versions of lib newrelic agent"
    exit 1
fi
export JVM_OPTS="... -javaagent:$lib"
</code>```

This works only in bash-like shells that support arrays array=(…). If you need a posix version use

```<code>#! /bin/sh
exactlyOne() {
  if [ "$#" != 1 ]; then
      echo "Found no or multiple matches"
      exit 1
  fi
  echo "$1"
}
lib=$(exactlyOne "/path/to/lib/newrelic-agent-"*.jar)
export JVM_OPTS="... -javaagent:$lib"
</code>```

Title: Wildcard in JVM options

Body:
No glob (*, ?, or something like that) works inside quotes ("…"). You have to unquote the part with the glob. However, "… -javaagent:/path/to/lib/newrelic-agent-"*".jar" won't work since the glob would then try to find a file starting with … -javaagent:.

Therefore, glob the jar in a separate variable and use that variable. Since there could be no or multiple versions of the library you might want to use a check and warn the user

#! /bin/bash
lib=("/path/to/lib/newrelic-agent-"*.jar)
if [ "${#lib[@]}" != 1 ]; then
    echo "Found no or multiple versions of lib newrelic agent"
    exit 1
fi
export JVM_OPTS="... -javaagent:$lib"

This works only in bash-like shells that support arrays array=(…). If you need a posix version use

#! /bin/sh
exactlyOne() {
  if [ "$#" != 1 ]; then
      echo "Found no or multiple matches"
      exit 1
  fi
  echo "$1"
}
lib=$(exactlyOne "/path/to/lib/newrelic-agent-"*.jar)
export JVM_OPTS="... -javaagent:$lib"


答:
It is a map-function:

In many programming languages, map is the name of a higher-order function that applies a given function to each element of a functor, e.g. a list, returning a list of results in the same order. It is often called apply-to-all when considered in functional form.

From Python docs:

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

In simple words, it is a function that applies a given function to each element of given container:

```<code>a = [1,2,3,4,5]
l = lambda x: x + 10
list(map(l, a))
</code>```

will return:

[11, 12, 13, 14, 15]

Title: What’s the function of map()?

Body:
It is a map-function:

In many programming languages, map is the name of a higher-order function that applies a given function to each element of a functor, e.g. a list, returning a list of results in the same order. It is often called apply-to-all when considered in functional form.

From Python docs:

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

In simple words, it is a function that applies a given function to each element of given container:

a = [1,2,3,4,5]
l = lambda x: x + 10
list(map(l, a))

will return:

[11, 12, 13, 14, 15]


问:
Displaying GIF image from URL retrived as JSON array response
I am getting JSON array as response from external API which contains list of GIFs. Now I have the GIF URLs as part of this response which I want to show as images on Angular front end html page.

I tried iterating over the response using  but that doesn't seem to work.

JSON response

```<code>0: {…}

analytics: Object { onload: {…}, onclick: {…}, onsent: {…} }

bitly_gif_url: "https://gph.is/YC1q17"

bitly_url: "https://gph.is/YC1q17"

content_url: ""

embed_url: "https://giphy.com/embed/6XeQfKBcO3K6c"

id: "6XeQfKBcO3K6c"

images: Object { fixed_height_still: {…}, original_still: {…}, fixed_width: {…}, … }

import_datetime: "1970-01-01 00:00:00"

is_sticker: 0

rating: "g"

slug: "hello-waving-movie-6XeQfKBcO3K6c"

source: ""

source_post_url: ""

source_tld: ""

title: "ryan gosling hello GIF"

trending_datetime: "2017-02-27 21:45:01"

type: "gif"

url: "https://giphy.com/gifs/hello-waving-movie-6XeQfKBcO3K6c"

username: ""
</code>```

I just want the list of images (say 20) coming as response to be shown in row column mode in UI.

答:
I got the actual GIF image URL by getting the complete JSON response details.

To display it simply calling the complete URL for the image,

```<code><div class="gifs-card-container"  *ngFor="let item of data">
  <img src={{item.images.original.url}}>
</div>
</code>```

Body:
I am getting JSON array as response from external API which contains list of GIFs. Now I have the GIF URLs as part of this response which I want to show as images on Angular front end html page.

I tried iterating over the response using  but that doesn't seem to work.

JSON response

0: {…}

analytics: Object { onload: {…}, onclick: {…}, onsent: {…} }

bitly_gif_url: "https://gph.is/YC1q17"

bitly_url: "https://gph.is/YC1q17"

content_url: ""

embed_url: "https://giphy.com/embed/6XeQfKBcO3K6c"

id: "6XeQfKBcO3K6c"

images: Object { fixed_height_still: {…}, original_still: {…}, fixed_width: {…}, … }

import_datetime: "1970-01-01 00:00:00"

is_sticker: 0

rating: "g"

slug: "hello-waving-movie-6XeQfKBcO3K6c"

source: ""

source_post_url: ""

source_tld: ""

title: "ryan gosling hello GIF"

trending_datetime: "2017-02-27 21:45:01"

type: "gif"

url: "https://giphy.com/gifs/hello-waving-movie-6XeQfKBcO3K6c"

username: ""

I just want the list of images (say 20) coming as response to be shown in row column mode in UI.

Body:
I got the actual GIF image URL by getting the complete JSON response details.

To display it simply calling the complete URL for the image,

<div class="gifs-card-container"  *ngFor="let item of data">
  <img src={{item.images.original.url}}>
</div>


问:
One UIPickerView with multiple textfields
Can I use one UIPickerView with many UITextFields, or should I create many pickerviews, one for each UITextField (I have all the UITextFields in the same view)?</p>

答:
I think one Picker view with multiple textfields would be enough. You can easily tag the textfields and process them according to your needs.

Multiple sources for UIPickerView on textfield editing

http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/12952-tutorial-uipickerview-basics-basic-tip-calculator.html

Will help you get started


问:
How can I check if a method is defined?
I try to set the value of my variable to "", in the case that getLove is not defined:

```<code>`$money = $dollar->getCash()->getLove ?? "";`
</code>```

But I get still the error message:

Attempted to call an undefined method named "getLove" of class
  "Proxies__CG__\App\Entity\Happiness".

答: Using method_exists, note that this does not take "__call()" in consideration.</p>

Title: How can I check if a method is defined?

Body:
I try to set the value of my variable to "", in the case that getLove is not defined:

`$money = $dollar->getCash()->getLove ?? "";`

But I get still the error message:

Attempted to call an undefined method named "getLove" of class
  "Proxies__CG__\App\Entity\Happiness".


答:
Since you have not passed index as argument to onClick={this.props.removePokemon}.

index inside removePokemon method refers the event object. So the code

team.splice(index, 1) evaluates to team.splice(eventObject, 1).

That's why splice is removing first  element of the array.

You can change to onClick={() => this.props.removePokemon(i)}to remove the element you want.

Title: Why is splice method removing only first array index in React?


问:
Xamarin AppCenter Crashes.TrackError not showing details I expect in AppCenter
I have this code:

```<code>    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if ((string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Name", DeviceInfo.Name },
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }
</code>```

There was an exception and I was expecting to see information such as the ex string (more than a few words),  Device Name and Model.

But AppCenter only tells me:

Stack traces Button.ChangeTheColours (System.Object sender,
  System.EventArgs e) Templates/Button/Button.xaml.cs:83

and doesn't give any more information about the exception or the Device Name and Model.

Is there something I am doing incorrectly with trying to detect crashes like this?  Note that I realise a throw would normally be needed but this is a special case for this error.

答:
Couple things. First, I think that this page might explain why your exception message is cut a little short. I'm not quite sure if the 125 character limit applies to the exception itself.

Second, you don't see much data without looking at the individual error report. To view a specific instance -

Click "Diagnostics" in the left nav

Select the Error you are trying to inspect

Near the top, select "Reports", this shows the individual instances with timestamps

Select an instance

Near the bottom, you will see an area titled "Error Properties" that should show your dictionary data you included in your error.

Body:
I have this code:

    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if ((string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Name", DeviceInfo.Name },
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }

There was an exception and I was expecting to see information such as the ex string (more than a few words),  Device Name and Model.

But AppCenter only tells me:

Stack traces Button.ChangeTheColours (System.Object sender,
  System.EventArgs e) Templates/Button/Button.xaml.cs:83

and doesn't give any more information about the exception or the Device Name and Model.

Is there something I am doing incorrectly with trying to detect crashes like this?  Note that I realise a throw would normally be needed but this is a special case for this error.


问:
Execution flow of React + Node.js application deployed on AWS Cloudfront?
I am developing a web application in React with a Node.js back-end. I would like to host the images and static files built for the React application on Cloudfront. However, the React application relies on the Node.js server to obtain some changing data to populate the views.

I need to have a thorough understanding of the flow of the application in order to come up with a reasonable design. Here is what I think happens:

User enters URL in the browser

Client is directed to the closest Cloudfront edge location

Cloudfront serves the HTML and images to the browser

The React application bootstraps in the browser

An API call is made to the Node.js server, which returns the required data

The browser renders the React application.

Am I understanding this correctly? Is there a better way to architect my web application?

I am not able to find the information I require online and would appreciate any help!

答:
Your architecture is correct.
Just to be clear, CloudFront is not hosting your files.  CloudFront is a cache and will fetch your files from an Origin, typically an Amazon S3 bucket.

Using React && AWS Amplify, you can create a serverless architecture for this type of setup with minimal work.  You can get started by following the instructions at https://aws-amplify.github.io/docs/

In a nutshel :

Install with:

```<code>npm install -g @aws-amplify/cli
$ amplify configure
</code>```

Then in your project :

amplify init
amplify add api #this will create your API as AWS Lambda functions exposed through Amazon API Gateway)
amplify add hosting #this will create the Amazon S3 bucket for hosting and the cloudfront distribution)
amplify push #to create all this on your AWS account for you
```

If you search for 'aws amplify react' you will easily find a dozen blog posting showing you how to get started.  There are so many I can not recommend one in particular.

Body:
Your architecture is correct.
Just to be clear, CloudFront is not hosting your files.  CloudFront is a cache and will fetch your files from an Origin, typically an Amazon S3 bucket.

Using React && AWS Amplify, you can create a serverless architecture for this type of setup with minimal work.  You can get started by following the instructions at https://aws-amplify.github.io/docs/

In a nutshel :

Install with:

npm install -g @aws-amplify/cli
$ amplify configure

Then in your project :

amplify init
amplify add api #this will create your API as AWS Lambda functions exposed through Amazon API Gateway)
amplify add hosting #this will create the Amazon S3 bucket for hosting and the cloudfront distribution)
amplify push #to create all this on your AWS account for you

If you search for 'aws amplify react' you will easily find a dozen blog posting showing you how to get started.  There are so many I can not recommend one in particular.


问:
IF condition on a group of record using mysql
Suppose I have a table t1 with two columns, Student_ID and Grade. The data shown like this;

```<code>Student_ID, Grade (1,'A'),(1,'C'),(1,'F'),(1,'A'),(2,'B'),(2,'A'),(2,'C'),(2,'A').
</code>```

Now I have to group the Student_ID with a new column named 'Result'. Student_ID 1 have one grade 'F' so consider failed and Student_ID 2 have no 'F' grade so consider passed. Require result should be like this.

```<code>Student_ID     Result
    1          Failed
    2          Passed
</code>```

Because the table have 500 records so can not manually enter 'Passed" or 'Failed'.

```<code>SELECT `Student_ID`, (IF(`Grade`='F',"Failed","Passed")) AS `Result`
FROM t1 group by `Student_ID`;
</code>```

Above code will not work as the column Grade has 4 values not 1.

So code will be some thing like this.

```<code>SELECT `Student_ID`, (IF(`Grade` CONTAINS 'F',"Failed","Passed")) AS `Result` FROM t1 group by `Student_ID`;
</code>```

There is no such thing CONTAINS in sql but may be HAVING or IN but how to use them here?

答:
You can use CASE statement with EXISTS:

```<code>select DISTINCT
  t.Student_ID,
  case
    when exists (
      select 1 from t1 where Student_ID = t.Student_ID and Grade = 'F'
    ) then 'Failed'
    else 'Passed'
  end Result
from t1 t
</code>```

See the demo.

Results:

```<code>| Student_ID | Result |
| ---------- | ------ |
| 1          | Failed |
| 2          | Passed |
</code>```

You can also do it by evaluating each Grade to 1 or 0 for 'F' or not 'F' and then grouping by Student_ID:

```<code>select
  t.Student_ID,
  case sum(t.Result)
    when 0 then 'Passed'
    else 'Failed'
  end Result
from (select Student_ID, Grade = 'F' Result from t1) t
group by t.Student_ID
</code>```

See the demo.

Body:
Suppose I have a table t1 with two columns, Student_ID and Grade. The data shown like this;

Student_ID, Grade (1,'A'),(1,'C'),(1,'F'),(1,'A'),(2,'B'),(2,'A'),(2,'C'),(2,'A').

Now I have to group the Student_ID with a new column named 'Result'. Student_ID 1 have one grade 'F' so consider failed and Student_ID 2 have no 'F' grade so consider passed. Require result should be like this.

Student_ID     Result
    1          Failed
    2          Passed

Because the table have 500 records so can not manually enter 'Passed" or 'Failed'.

SELECT `Student_ID`, (IF(`Grade`='F',"Failed","Passed")) AS `Result`
FROM t1 group by `Student_ID`;

Above code will not work as the column Grade has 4 values not 1.

So code will be some thing like this.

SELECT `Student_ID`, (IF(`Grade` CONTAINS 'F',"Failed","Passed")) AS `Result` FROM t1 group by `Student_ID`;

There is no such thing CONTAINS in sql but may be HAVING or IN but how to use them here?

Body:
You can use CASE statement with EXISTS:

select DISTINCT
  t.Student_ID,
  case
    when exists (
      select 1 from t1 where Student_ID = t.Student_ID and Grade = 'F'
    ) then 'Failed'
    else 'Passed'
  end Result
from t1 t

See the demo.

Results:

| Student_ID | Result |
| ---------- | ------ |
| 1          | Failed |
| 2          | Passed |

You can also do it by evaluating each Grade to 1 or 0 for 'F' or not 'F' and then grouping by Student_ID:

select
  t.Student_ID,
  case sum(t.Result)
    when 0 then 'Passed'
    else 'Failed'
  end Result
from (select Student_ID, Grade = 'F' Result from t1) t
group by t.Student_ID

See the demo.