问:
How to set first N children height to its parent max-height jQuery or CSS(preferred)?
I have dynamically prepended divs (.class-row-notification) to another div (.class-append-con).

Now I want to set first 5 divs height to its parent's max-height (Including margin, padding, bottom-border etc.).

UPDATE

Addition of first five div class (.class-row-notification)(children div) == max-height of class(.class-append-con)(parent div)

How to do that ? If through CSS, it should be cross browser.

I tried it through jQuery but everytime it gives me same height as 11px for the div.class-row-notification

EDIT:-

I removed the commented code from snippet and tried again, its working here but not in my project why?

I have following html -

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Shantaram :  Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Spring : How are you, Shantaram ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Suyog :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Balasaheb :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Ravi :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Nilesh :  Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "
"
                    +""
                      +""
                        +notificationData[i].message
                      +""
                      +""
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +""
                    +""
                  +"
";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert( "Height of "+(i+1)+" div     :-  " +$(this).outerHeight( true )+" \nHeight Addition   :-  "+ h );
    });
    $('.class-append-con').css('max-height', h);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}</code>```

```

答:
I removed the comments from question and tried again, its working here but not in my project why?

EDIT

WHY?

I found the ISSUE :-

I was not getting correct height because, my parent class .class-append-con (In this question), its parent class was hidden,

thats why I was getting height() as 0 and outerHeight( true ) as fixed to 11px

Solution

I have created new div out of viewport and then calculated height.

thank you people for your valuable time and efforts.

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Shantaram :  Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Spring : How are you, Shantaram ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Suyog :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Balasaheb :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Ravi :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Nilesh :  Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "
"
                    +""
                      +""
                        +notificationData[i].message
                      +""
                      +""
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +""
                    +""
                  +"
";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert(h +" : "+$(this).outerHeight( true ) +" : "+i);
    });
    $('.class-append-con').css('max-height', h);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}</code>```

```

Body:
I have dynamically prepended divs (.class-row-notification) to another div (.class-append-con).

Now I want to set first 5 divs height to its parent's max-height (Including margin, padding, bottom-border etc.).

UPDATE

Addition of first five div class (.class-row-notification)(children div) == max-height of class(.class-append-con)(parent div)

How to do that ? If through CSS, it should be cross browser.

I tried it through jQuery but everytime it gives me same height as 11px for the div.class-row-notification

EDIT:-

I removed the commented code from snippet and tried again, its working here but not in my project why?

I have following html -

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Shantaram :  Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Spring : How are you, Shantaram ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Suyog :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Balasaheb :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Ravi :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Nilesh :  Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "
"
                    +""
                      +""
                        +notificationData[i].message
                      +""
                      +""
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +""
                    +""
                  +"
";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert( "Height of "+(i+1)+" div     :-  " +$(this).outerHeight( true )+" \nHeight Addition   :-  "+ h );
    });
    $('.class-append-con').css('max-height', h);
}

.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}

Body:
I removed the comments from question and tried again, its working here but not in my project why?

EDIT

WHY?

I found the ISSUE :-

I was not getting correct height because, my parent class .class-append-con (In this question), its parent class was hidden,

thats why I was getting height() as 0 and outerHeight( true ) as fixed to 11px

Solution

I have created new div out of viewport and then calculated height.

thank you people for your valuable time and efforts.

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Shantaram : </b> Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Spring : </b>How are you, <b>Shantaram</b> ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Suyog : </b> Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Balasaheb : </b> Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Ravi : </b> Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"<b>Nilesh : </b> Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "<div class='class-row-notification'>"
                    +"<a href='"+notificationData[i].notificationLink+"' class='class-notification-link' target='mainfrm' >"
                      +"<span class='class-notification-message'>"
                        +notificationData[i].message
                      +"</span>"
                      +"<span class='class-notification-time'>"
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +"</span>"
                    +"</a>"
                  +"</div>";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert(h +" : "+$(this).outerHeight( true ) +" : "+i);
    });
    $('.class-append-con').css('max-height', h);
}

.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-append-con">
</div>


来源: stackexchange

问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
Since the result is supposed to be a list, you‘re not grouping but simply sorting (in the sense of changing the order according to a defined rule). The main obstacle is that you want the locations to be ordered after their first encounter in the original list.

The straight-forward approach is to fix this location order first, followed by a single sort operation:

```<code>Map<String,Integer> locationOrder = studlist.stream()
    .collect(HashMap::new,
             (m,s)->m.putIfAbsent(s.stud_location, m.size()),
             (m1,m2)->m2.keySet().forEach(l->m1.putIfAbsent(l, m1.size())));

studlist.sort(Comparator.comparingInt((Student s) -> locationOrder.get(s.stud_location))
                        .thenComparing(s -> s.stud_id));
</code>```

If you can not or do not want to modify the original list, you can simply use a copy:

```<code>List<Student> result = new ArrayList<>(studlist);
result.sort(Comparator.comparingInt((Student s) -> locationOrder.get(s.stud_location))
                      .thenComparing(s -> s.stud_id));
</code>```

It’s also possible to solve this with a grouping operation, but that’s not easier:

```<code>List<Student> result = studlist.stream()
    .collect(Collectors.collectingAndThen(
                Collectors.groupingBy(s -> s.stud_location,
                                      LinkedHashMap::new, Collectors.toList()),
                m -> m.values().stream()
                      .flatMap(l -> l.stream().sorted(Comparator.comparing(s->s.stud_id)))
                      .collect(Collectors.toList())));
</code>```

Note that you have to collect into a LinkedHashMap to ensure that the order of the groups is retained.

ContentLicense: CC BY-SA 3.0

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
Since the result is supposed to be a list, you‘re not grouping but simply sorting (in the sense of changing the order according to a defined rule). The main obstacle is that you want the locations to be ordered after their first encounter in the original list.

The straight-forward approach is to fix this location order first, followed by a single sort operation:

Map<String,Integer> locationOrder = studlist.stream()
    .collect(HashMap::new,
             (m,s)->m.putIfAbsent(s.stud_location, m.size()),
             (m1,m2)->m2.keySet().forEach(l->m1.putIfAbsent(l, m1.size())));

studlist.sort(Comparator.comparingInt((Student s) -> locationOrder.get(s.stud_location))
                        .thenComparing(s -> s.stud_id));

If you can not or do not want to modify the original list, you can simply use a copy:

List<Student> result = new ArrayList<>(studlist);
result.sort(Comparator.comparingInt((Student s) -> locationOrder.get(s.stud_location))
                      .thenComparing(s -> s.stud_id));

It’s also possible to solve this with a grouping operation, but that’s not easier:

List<Student> result = studlist.stream()
    .collect(Collectors.collectingAndThen(
                Collectors.groupingBy(s -> s.stud_location,
                                      LinkedHashMap::new, Collectors.toList()),
                m -> m.values().stream()
                      .flatMap(l -> l.stream().sorted(Comparator.comparing(s->s.stud_id)))
                      .collect(Collectors.toList())));

Note that you have to collect into a LinkedHashMap to ensure that the order of the groups is retained.


问:
String concatenation: concat() vs "+" operator
Assuming String a and b:

```<code>a += b
a = a.concat(b)
</code>```

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

```<code>public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}
</code>```

答:
How about some simple testing? Used the code below:

```<code>long start = System.currentTimeMillis();

String a = "a";

String b = "b";

for (int i = 0; i < 10000000; i++) { //ten million times
     String c = a.concat(b);
}

long end = System.currentTimeMillis();

System.out.println(end - start);
</code>```

The "a + b" version executed in 2500ms.

The a.concat(b) executed in 1200ms.

Tested several times. The concat() version execution took half of the time on average.

This result surprised me because the concat() method always creates a new string (it returns a "new String(result)". It's well known that:

```<code>String a = new String("a") // more than 20 times slower than String a = "a"
</code>```

Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation.
If you don't believe the statement above, test for your self.

OwnerDisplayName: shs

Body:
Assuming String a and b:

a += b
a = a.concat(b)

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

LastEditorDisplayName: shs

Body:
How about some simple testing? Used the code below:

long start = System.currentTimeMillis();

String a = "a";

String b = "b";

for (int i = 0; i < 10000000; i++) { //ten million times
     String c = a.concat(b);
}

long end = System.currentTimeMillis();

System.out.println(end - start);

The "a + b" version executed in 2500ms.

The a.concat(b) executed in 1200ms.

Tested several times. The concat() version execution took half of the time on average.

This result surprised me because the concat() method always creates a new string (it returns a "new String(result)". It's well known that:

String a = new String("a") // more than 20 times slower than String a = "a"

Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation.
If you don't believe the statement above, test for your self.

OwnerDisplayName: marcio

LastEditorDisplayName: marcio


问:
How to test for String = Enum.Value?
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

```<code>Enum A
     B=0
     C=1
     D=2
End Enum
</code>```

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

答:
The Enum.Parse method:

Converts the string representation of
  the name or numeric value of one or
  more enumerated constants to an
  equivalent enumerated object. A
  parameter specifies whether the
  operation is case-sensitive.

Here's the VB.NET example code from MSDN:

```<code>Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Try
            Dim colorValue As Colors = CType([Enum].Parse(GetType(Colors), colorString, True), Colors)
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)
            End If
         Catch e As ArgumentException
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End Try
      Next
   End Sub
End Module
</code>```

OwnerDisplayName: Middletone

ContentLicense: CC BY-SA 2.5

Title: How to test for String = Enum.Value?

Body:
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

Enum A
     B=0
     C=1
     D=2
End Enum

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

Body:
The Enum.Parse method:

Converts the string representation of
  the name or numeric value of one or
  more enumerated constants to an
  equivalent enumerated object. A
  parameter specifies whether the
  operation is case-sensitive.

Here's the VB.NET example code from MSDN:

Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Try
            Dim colorValue As Colors = CType([Enum].Parse(GetType(Colors), colorString, True), Colors)
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)
            End If
         Catch e As ArgumentException
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End Try
      Next
   End Sub
End Module

OwnerDisplayName: Mitch Wheat


问:
Updating dataframe column names based on values given in another dataframe
I am very new to python. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

```<code>A    B    C   D
1    2    3   4
</code>```

I have another table that looks like this' DataFrame2

```<code>Col1    Col2
A       E
B       Q
C       R
D       Z
</code>```

I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same.

```<code>E    Q    R    Z
1    2    3    4
</code>```

答:
Use map with get by setting index i.e </p>

```<code>df.columns = df.columns.map(df2.set_index('Col1')['Col2'].get)

   E  Q  R  Z
0  1  2  3  4
</code>```

Body:
I am very new to python. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

A    B    C   D
1    2    3   4

I have another table that looks like this' DataFrame2

Col1    Col2
A       E
B       Q
C       R
D       Z

I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same.

E    Q    R    Z
1    2    3    4

Body:
Use map with get by setting index i.e

df.columns = df.columns.map(df2.set_index('Col1')['Col2'].get)

   E  Q  R  Z
0  1  2  3  4


问:
Modal Register Panel Button Save Click
Objective: I have a register panel to sign up.

Problem:  Signup button click doesnt work.

When I removed id=register_panel it perfectly works but modal popup doesnt work.
I did not use ajax.
How can I make the button click event work on this modal popup?

Code :

```<code><div id="register_panel" class="mfp-hide loginbox-popup auth-popup" >
   <div class="inner-container register-panel auth-popup-panel">
      <h3 class="m_title m_title_ext text-custom auth-popup-title">YENİ HESAP</h3>
      <div class="register_panel" >
         <div class="form-group kl-fancy-form ">
            <asp:TextBox type="text" id="txtUsername" name="user_login" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="KULLANICI ADI" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="Zorunlu Alan" ForeColor="Red" ControlToValidate="txtUsername"
               runat="server" />
            <label class="kl-font-alt kl-fancy-form-label">AD SOYAD</label>
         </div>
         <div class="form-group kl-fancy-form ">
            <asp:TextBox type="text" id="txtTelefon" MaxLength="11"  name="user_login" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="532 532 32 32" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="Zorunlu Alan" ForeColor="Red" ControlToValidate="txtTelefon"
               runat="server" />
            <label class="kl-font-alt kl-fancy-form-label">TELEFON</label>
         </div>
         <div class="form-group kl-fancy-form">
            <asp:TextBox  type="text" id="txtEmail" name="user_email" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="your-email@website.com" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="*Zorunlu Alan" Display="Dynamic" ForeColor="Red"
               ControlToValidate="txtEmail" runat="server" />
            <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
               ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Geçersiz Mail Adresi." />
            <label class="kl-font-alt kl-fancy-form-label">EMAİL</label>
         </div>
         <div class="form-group kl-fancy-form">
            <asp:TextBox type="password" id="txtPassword" name="user_password" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="*****" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="*Zorunlu Alan" ForeColor="Red" ControlToValidate="txtPassword"
               runat="server" />
            <label class="kl-font-alt kl-fancy-form-label">PAROLA</label>
         </div>
         <div class="form-group kl-fancy-form">
            <asp:TextBox type="password" id="txtConfirmPassword" name="user_password2" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="*****" runat="server"></asp:TextBox>
            <asp:CompareValidator ErrorMessage="Parolalar eşleşmedi." ForeColor="Red" ControlToCompare="txtPassword"
               ControlToValidate="txtConfirmPassword" runat="server" />
            <label class="kl-font-alt kl-fancy-form-label">PAROLA(TEKRAR)</label>
         </div>
         <asp:Button  id="SignUp" OnClick="SignUp_Click1" class="btn-fullcolor"   runat="server" Text="KAYIT OL" />
         **here is button save click**
         <div class="links auth-popup-links">
            <a href="#login_panel" class="kl-login-box auth-popup-link">ZATEN BİR HESABINIZ MI VAR?</a>
         </div>
      </div>
   </div>
</div>
</code>```

答:
Try UseSubmitBehavior="false" property in your button:

```<code><asp:Button id="SignUp" UseSubmitBehavior="false"
    OnClick="SignUp_Click1" runat="server" Text="KAYIT OL" />
</code>```

Title: Modal Register Panel Button Save Click

Body:
Objective: I have a register panel to sign up.

Problem:  Signup button click doesnt work.

When I removed id=register_panel it perfectly works but modal popup doesnt work.
I did not use ajax.
How can I make the button click event work on this modal popup?

Code :

YENİ HESAP

            <asp:TextBox type="text" id="txtUsername" name="user_login" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="KULLANICI ADI" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="Zorunlu Alan" ForeColor="Red" ControlToValidate="txtUsername"
               runat="server" />
            AD SOYAD

            <asp:TextBox type="text" id="txtTelefon" MaxLength="11"  name="user_login" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="532 532 32 32" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="Zorunlu Alan" ForeColor="Red" ControlToValidate="txtTelefon"
               runat="server" />
            TELEFON

            <asp:TextBox  type="text" id="txtEmail" name="user_email" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="your-email@website.com" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="*Zorunlu Alan" Display="Dynamic" ForeColor="Red"
               ControlToValidate="txtEmail" runat="server" />
            <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
               ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Geçersiz Mail Adresi." />
            EMAİL

            <asp:TextBox type="password" id="txtPassword" name="user_password" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="*****" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ErrorMessage="*Zorunlu Alan" ForeColor="Red" ControlToValidate="txtPassword"
               runat="server" />
            PAROLA

            <asp:TextBox type="password" id="txtConfirmPassword" name="user_password2" class="form-control inputbox kl-fancy-form-input kl-fw-input" placeholder="*****" runat="server"></asp:TextBox>
            <asp:CompareValidator ErrorMessage="Parolalar eşleşmedi." ForeColor="Red" ControlToCompare="txtPassword"
               ControlToValidate="txtConfirmPassword" runat="server" />
            PAROLA(TEKRAR)

         <asp:Button  id="SignUp" OnClick="SignUp_Click1" class="btn-fullcolor"   runat="server" Text="KAYIT OL" />
         **here is button save click**

            ZATEN BİR HESABINIZ MI VAR?

Body:
Try UseSubmitBehavior="false" property in your button:

<asp:Button id="SignUp" UseSubmitBehavior="false"
    OnClick="SignUp_Click1" runat="server" Text="KAYIT OL" />


问:
How to run scripts from the control panel with a custom service?
Recently I tried to run a script from the control panel. The problem is that the script engine doesn't understand my custom service though I imported it.

```<code>"Unable to resolve class"
</code>```

How can I solve it?

Thanks.

答:
Use this PortletBeanLocatorUtil

Example:

```<code>def ser = com.liferay.portal.kernel.bean.PortletBeanLocatorUtil
       .locate("your-portlet-name-portlet",
        "com.example.yourclass.service.ItemLocalService")

def dq = ser.dynamicQuery()
</code>```

Body:
Recently I tried to run a script from the control panel. The problem is that the script engine doesn't understand my custom service though I imported it.

"Unable to resolve class"

How can I solve it?

Thanks.

Body:
Use this PortletBeanLocatorUtil

Example:

def ser = com.liferay.portal.kernel.bean.PortletBeanLocatorUtil
       .locate("your-portlet-name-portlet",
        "com.example.yourclass.service.ItemLocalService")

def dq = ser.dynamicQuery()


问:
How to change default name of buttons in datatable plugin?
I am using datatables plugin for by displaying data in my html page.
I have a requirement where I want to export the data inside the datatable.

Datatable supports this functionality by some plugins and a example can be seen here.

what I get on screen is that the export buttons with the fixed default names like below

I want to change the default names to custom names. eg. "Excel" to "Export to Excel"

How can I do that?

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} );
</code>```

In the above code if I change the default names , then my functionality breaks because datatable recognizes the functionality of button by its name. Is there any property which I should use which will help me achieve what I want or any other way out?

答:
```<code>buttons: [
    { extend: 'excel', text: 'Export to excel' }
]
</code>```

Body:
I am using datatables plugin for by displaying data in my html page.
I have a requirement where I want to export the data inside the datatable.

Datatable supports this functionality by some plugins and a example can be seen here.

what I get on screen is that the export buttons with the fixed default names like below

I want to change the default names to custom names. eg. "Excel" to "Export to Excel"

How can I do that?

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} );

In the above code if I change the default names , then my functionality breaks because datatable recognizes the functionality of button by its name. Is there any property which I should use which will help me achieve what I want or any other way out?


问:
How to get current caller view page file in HTML helper extension method?
I create HTML helper extension to combine script into one file like the following code. It will combine both jQuery and jQuery UI file into common.js file at specified location. I use ASP.NET caching with file dependency to monitor all combined files. If some file is changed, the method will re-generate combined file.

```<code>@(Html.CombinedFiles
(
    "~/Scripts/common.js",
    "~/Scripts/jquery-1.4.4.js",
    "~/Scripts/jquery-ui.js"
))
</code>```

Everything works perfectly. However, it has only one problem. When developer modify view page that call this function for adding or removing file to be combined. ASP.NET caching is still valid. Method will not re-generate combined file because I don't add caller view page to file dependency list.

I want to know. Is it possible to get view page to call this extension method? It must support both ASPX and Razor view engine.

Thanks,

PS. Documentation about this function in my Higgs RIA framework for more understanding this method.

答:
```<code>IView view = htmlHelper.ViewContext.View;
if (view is BuildManagerCompiledView)
{
    string viewUrl = ((BuildManagerCompiledView)view).ViewPath;
    // use viewUrl here
}
</code>```

Body:
I create HTML helper extension to combine script into one file like the following code. It will combine both jQuery and jQuery UI file into common.js file at specified location. I use ASP.NET caching with file dependency to monitor all combined files. If some file is changed, the method will re-generate combined file.

@(Html.CombinedFiles
(
    "~/Scripts/common.js",
    "~/Scripts/jquery-1.4.4.js",
    "~/Scripts/jquery-ui.js"
))

Everything works perfectly. However, it has only one problem. When developer modify view page that call this function for adding or removing file to be combined. ASP.NET caching is still valid. Method will not re-generate combined file because I don't add caller view page to file dependency list.

I want to know. Is it possible to get view page to call this extension method? It must support both ASPX and Razor view engine.

Thanks,

PS. Documentation about this function in my Higgs RIA framework for more understanding this method.


问:
Adding class angular 2
I am adding some animation on element, only problem beside style i need to add class also, this is what i have for now in my component.

```<code>@Component({
    selector: 'app-shipment-list',
    templateUrl: './shipment-list.component.html',
    styleUrls: ['./shipment-list.component.scss'],
    animations: [
        trigger('slideInOut', [
            state('in', style({
                transform: 'translate3d(0, 0, 0)'
            })),
            state('out', style({
                transform: 'translate3d(100%, 0, 0)'
            })),
            transition('in => out', animate('400ms ease-in-out')),
            transition('out => in', animate('400ms ease-in-out'))
        ]
})
</code>```

Only problem is that beside this attribute style i need to add class opened when is in and remove class opened when is out?

```<code> filtersState: string = 'out';
    toggleFilters() {
        // 1-line if statement that toggles the value:
        this.filtersState = this.filtersState === 'out' ? 'in' : 'out';
    }
</code>```

HTML

```<code><app-shipment-list-filters [@slideInOut]="filtersState"></app-shipment-list-filters>
<button type="button" (click)="toggleFilters()" class="btn btn-info">No filter active</button>
</code>```

答:
As stated here:

A class binding is a good way to add or remove a single class.

So, just try:

```<code><app-shipment-list-filters [@slideInOut]="filtersState"
                           [class.opened]="filtersState === 'in'">
</app-shipment-list-filters>
<button type="button"
        (click)="toggleFilters()"
        class="btn btn-info">No filter active</button>
</code>```

Title: Adding class angular 2

Body:
I am adding some animation on element, only problem beside style i need to add class also, this is what i have for now in my component.

@Component({
    selector: 'app-shipment-list',
    templateUrl: './shipment-list.component.html',
    styleUrls: ['./shipment-list.component.scss'],
    animations: [
        trigger('slideInOut', [
            state('in', style({
                transform: 'translate3d(0, 0, 0)'
            })),
            state('out', style({
                transform: 'translate3d(100%, 0, 0)'
            })),
            transition('in => out', animate('400ms ease-in-out')),
            transition('out => in', animate('400ms ease-in-out'))
        ]
})

Only problem is that beside this attribute style i need to add class opened when is in and remove class opened when is out?

 filtersState: string = 'out';
    toggleFilters() {
        // 1-line if statement that toggles the value:
        this.filtersState = this.filtersState === 'out' ? 'in' : 'out';
    }

HTML

<app-shipment-list-filters [@slideInOut]="filtersState"></app-shipment-list-filters>
<button type="button" (click)="toggleFilters()" class="btn btn-info">No filter active</button>

Body:
As stated here:

A class binding is a good way to add or remove a single class.

So, just try:

<app-shipment-list-filters [@slideInOut]="filtersState"
                           [class.opened]="filtersState === 'in'">
</app-shipment-list-filters>
<button type="button"
        (click)="toggleFilters()"
        class="btn btn-info">No filter active</button>


问:
Getting "Sorry, I didn't get any response." message when I tried Hand-off feature
When I tried Multi-surface conversations (Hand-off from Google Home to Android Google Assistant), I'm getting "Sorry, I didn't get any response."
I'm using Action SDK and locale is "ja".

Here is my response:

```<code>{
    "conversationToken": "(token)",
    "expectUserResponse": true,
    "isInSandbox": true,
    "expectedInputs": [
        {
            "possibleIntents": [
                {
                    "intent": "actions.intent.NEW_SURFACE",
                    "inputValueData": {
                        "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
                        "context": "Sure, I have some sample images for you.",
                        "notificationTitle": "Sample Images",
                        "capabilities": [
                            "actions.capability.SCREEN_OUTPUT"
                        ]
                    }
                }
            ],
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": {
                        "simpleResponse": {
                            "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
                        }
                    }
                }
            }
        }
    ]
}
</code>```

Does anyone know why?

答:
Turns out that this is not a bug in a certain locale, but that askForNewSurface is currently supported for english locales only.
This is what I got from AoG support:

Hi Jan,

Thank you for your interest in Actions on Google.
  askForNewSurface is indeed only available for English locales. We are in the process of changing the documentation to reflect those restrictions.
  Sorry for the confusion.
  We do not have any set det for the release of this feature in other locales.

Kind Regards,

Jean-Charles,
  Actions on Google Support Team.

Body:
When I tried Multi-surface conversations (Hand-off from Google Home to Android Google Assistant), I'm getting "Sorry, I didn't get any response."
I'm using Action SDK and locale is "ja".

Here is my response:

{
    "conversationToken": "(token)",
    "expectUserResponse": true,
    "isInSandbox": true,
    "expectedInputs": [
        {
            "possibleIntents": [
                {
                    "intent": "actions.intent.NEW_SURFACE",
                    "inputValueData": {
                        "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
                        "context": "Sure, I have some sample images for you.",
                        "notificationTitle": "Sample Images",
                        "capabilities": [
                            "actions.capability.SCREEN_OUTPUT"
                        ]
                    }
                }
            ],
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": {
                        "simpleResponse": {
                            "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
                        }
                    }
                }
            }
        }
    ]
}

Does anyone know why?


问:
PHP: Download incoming email from POP3 or IMAP, parse it, and mark it as read/delete on server
I'm trying to add incoming email to my web application. It's built on CodeIgniter and PHP, and as far as I can tell I haven't found any CI libraries to do this.

What I'd like to do is have a controller that connects to my mail box, via POP3 or IMAP, and retrieves the message, parses it then removes it from the server.

Piping mail from postfix/etc isn't going to work on my server setup.

Any suggestions would be immensely helpful.

Thanks!

答:
For a more independent approach you could build a Third party plugin with Zend framework (https://docs.zendframework.com/zend-mail/read/). I have used their ACL modules within Codeigniter and is a good way of getting the best of both frameworks.

This also allows you to parse the emails and extract attachments etc.


问:
How to generate correct RSA key for signing JWT?
I'm using this example, however it is slightly outdated. So, for, example SignedString(key), I guess, receives *rsa.PublicKey instead of []byte in case of RS256 signing method. I generated my private key using

```<code>openssl genrsa -out key.rsa 1024
</code>```

And now trying to parse it:

```<code>package main

import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
)

func main() {
    pem := []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCycI9LZT8qM/zCGH0CNxAi7gy7w1YjqZN1N8yFfbmv9toVC82S
bZDv8NVYVlFNhUbtUFg77TYhHmyPpr4hKqvPrVc0rqVFe4ggQYdXovDgLZhO1MxB
i4vw9tLRlAK8TYNFqaFiX6lFgRp8trd01GFhkBJMzZCMmBQFkcEgWqT6MQIDAQAB
AoGBAKSru5GYnfIUh+2XK8YfioSxqo6cdaHznGFQXS3UGMiKxjcl7VB0TI0hc8FR
5zXjCNF4k/S5tHpb2VO4TT3OYz55/JEOGAXvIMW2UYtL4TwR3+46TRJ95KKowq+c
3JndjmGjUbvWawtbNklkmgoEkLI8wYu9yss9293GBnff14ABAkEA1scxu0svrIZ1
R5YmpXOfrtGwsjbdowGNxZTedWlbJukBSNPSIpuUvkzF2PXlPBS80p5yxbYlp1gg
UhsfXWJwIQJBANSv7lEuHV0QnVVoYVtNijwEHIi7iG7xu7hDQ7bK/kwWV6wqnvfP
PZopZPDXCRlnxbubo0/RJz4LsaJflDJKiBECQC/3FFgrll4FOTPfiInypHq6QafL
MPwyYKL7eCLogH7UEoFdLNSlwjYtlxG4+JTOXMz8rc0RvJ7+w1kSzZJhZYECQHMU
DhqWnQSx7K89nw/L0LPQda/16Eg/O5bjrkvFYfrBTAa3uPPUijxTkW5Oq3m3kGGG
QML7JASKRz7YAFOFyEECQQCUBNONRYMMzzr4llGOcKISXJtewlOPTHGP++OiHWMB
rPzZDyi5ONNgySF8t/QnJMTRpRQ5axi0UhojL/OzUt/w
-----END RSA PRIVATE KEY-----`)

    key, err := jwt.ParseRSAPublicKeyFromPEM(pem)
    fmt.Println(key, err)
}
</code>```

But I get asn1: structure error: tags don't match (16 vs {class:0 tag:2 length:1 isCompound:false}) {optional:false explicit:false application:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} tbsCertificate @2 in response.

Is my key generating command somehow wrong? What should I read to be able to debug this? What asn1 has to do with it? Key has some particular syntax?

答: You are passing a RSA PRIVATE KEY but calling jwt.ParseRSAPublicKeyFromPEM. You should be calling jwt.ParseRSAPrivateKeyFromPEM instead.

Body:
I'm using this example, however it is slightly outdated. So, for, example SignedString(key), I guess, receives *rsa.PublicKey instead of []byte in case of RS256 signing method. I generated my private key using

openssl genrsa -out key.rsa 1024

And now trying to parse it:

package main

import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
)

func main() {
    pem := []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCycI9LZT8qM/zCGH0CNxAi7gy7w1YjqZN1N8yFfbmv9toVC82S
bZDv8NVYVlFNhUbtUFg77TYhHmyPpr4hKqvPrVc0rqVFe4ggQYdXovDgLZhO1MxB
i4vw9tLRlAK8TYNFqaFiX6lFgRp8trd01GFhkBJMzZCMmBQFkcEgWqT6MQIDAQAB
AoGBAKSru5GYnfIUh+2XK8YfioSxqo6cdaHznGFQXS3UGMiKxjcl7VB0TI0hc8FR
5zXjCNF4k/S5tHpb2VO4TT3OYz55/JEOGAXvIMW2UYtL4TwR3+46TRJ95KKowq+c
3JndjmGjUbvWawtbNklkmgoEkLI8wYu9yss9293GBnff14ABAkEA1scxu0svrIZ1
R5YmpXOfrtGwsjbdowGNxZTedWlbJukBSNPSIpuUvkzF2PXlPBS80p5yxbYlp1gg
UhsfXWJwIQJBANSv7lEuHV0QnVVoYVtNijwEHIi7iG7xu7hDQ7bK/kwWV6wqnvfP
PZopZPDXCRlnxbubo0/RJz4LsaJflDJKiBECQC/3FFgrll4FOTPfiInypHq6QafL
MPwyYKL7eCLogH7UEoFdLNSlwjYtlxG4+JTOXMz8rc0RvJ7+w1kSzZJhZYECQHMU
DhqWnQSx7K89nw/L0LPQda/16Eg/O5bjrkvFYfrBTAa3uPPUijxTkW5Oq3m3kGGG
QML7JASKRz7YAFOFyEECQQCUBNONRYMMzzr4llGOcKISXJtewlOPTHGP++OiHWMB
rPzZDyi5ONNgySF8t/QnJMTRpRQ5axi0UhojL/OzUt/w
-----END RSA PRIVATE KEY-----`)

    key, err := jwt.ParseRSAPublicKeyFromPEM(pem)
    fmt.Println(key, err)
}

But I get asn1: structure error: tags don't match (16 vs {class:0 tag:2 length:1 isCompound:false}) {optional:false explicit:false application:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} tbsCertificate @2 in response.

Is my key generating command somehow wrong? What should I read to be able to debug this? What asn1 has to do with it? Key has some particular syntax?


问:
if (view == null) issues in fragment
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view. </p>

```<code>@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }
</code>```

答: it 'll happen because i am adding animation when fragment change and return to back.. This problem facing because of Android 8.0(Oreo) rest os working fine so I removed the animation during fragment  change it 'll solved.</p>

Title: if (view == null) issues in fragment

Body:
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view.

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }


问:
how to change theme in Magento2
UPDATE: this could be a version issue, should I update to the non-stable 2.0.4?

I know this should seem obvious to someone, but clearly it's not.
as state in the documentation

In Admin, go to Stores > Configuration > Design.

but there is only a robot txt edit as seen in the below screen shot

I track down the issue on github #4251

All design configurations were moved to Content -> Design -> Configuration

when I get there, my custom theme successfully show up, but no button to change it, as seen below. there is no option to change from the default Luma theme to blank theme neither.

is it just me? or I am blind and missing something really obvious?
My Magento version is 2.0.0.

答:
The default theme in Magento 2 is called Magento Blank. To activate it, follow these steps:

1- Login into your admin panel and navigate to Stores->Settings ->Configuration section.

2- In the General tab press Design.

3- Select Magento Blank among the list of available themes in Design Theme option press the Save Config button in the top right.

4- Refresh the Magento cache.

5- Check how the new theme appears on the site frontend.

For pictorial or video representation go to the URL: https://www.templatemonster.com/help/magento-2-x-switch-store-default-theme.html

ContentLicense: CC BY-SA 4.0

Title: how to change theme in Magento2


问:
Vue.js: Binding a function to Template
I can't really explain this in words, but I want to bind my screen height to a calculated value. The code here does not work, so I'd like to know how to make it work.

```<code><template>
    <b-container id="notfound-container">
        <b-row align-v="center" v-bind:style="{ height : h + 'px' }">
            <b-col style="align-items:center">
                <h1>404 Error</h1>
                <p>The page you have requested does not exist.</p>
            </b-col>
        </b-row>
    </b-container>
</template>

<script>
    export default {
        name: 'tHome',
        data () {
            return {
                h: (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top)
            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    h1, h2 {
        font-weight: normal;
    }
    ul {
        list-style-type: none;
        padding: 0;
    }
    li {
        display: inline-block;
        margin: 0 10px;
    }
    a {
        color: #42b983;
    }
</style>
</code>```

The value does not need to be dynamically updated, but I'd like it to be calculated at least once.
Currently, I get the error that "h" is not initialized.

答:
data properties are evaluated before the DOM  is rendered. So perform your calculation logic after the DOM is mounted , i.e inside the mounted() lifecycle hook

```<code>data(){
    h: null
},
mounted(){
       this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
}
</code>```

EDIT:

You can add an event listener for wimdow resize in the mounted() hook itself:

```<code>data(){
    h: null
},
mounted(){
    window.addEventListener('resize', this.setHeight);
},
beforeDestroy(){
    //remove the resize listener
    window.removeEventListener('resize', this.setHeight);
},
methods:{
    setHeight(){
        this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
    }
}
</code>```

Title: Vue.js: Binding a function to Template

Body:
I can't really explain this in words, but I want to bind my screen height to a calculated value. The code here does not work, so I'd like to know how to make it work.

<template>

404 Error

The page you have requested does not exist.

</template>

The value does not need to be dynamically updated, but I'd like it to be calculated at least once.
Currently, I get the error that "h" is not initialized.

Body:
data properties are evaluated before the DOM  is rendered. So perform your calculation logic after the DOM is mounted , i.e inside the mounted() lifecycle hook

data(){
    h: null
},
mounted(){
       this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
}

EDIT:

You can add an event listener for wimdow resize in the mounted() hook itself:

data(){
    h: null
},
mounted(){
    window.addEventListener('resize', this.setHeight);
},
beforeDestroy(){
    //remove the resize listener
    window.removeEventListener('resize', this.setHeight);
},
methods:{
    setHeight(){
        this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
    }
}


问:
give a color to not a number
I have a matrix of integers, padded with nans

```<code>M=

 1     2     2     3     4     4
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
</code>```

I am plotting it using imagesc

```<code>imagesc(M)
</code>```

However, if I plot it this way, NaN and 1 are shown with the same color, which is confusing.

How to have different colors for NaNs in imagesc?

答:
You can replace NaN by 1 less than the minimum number in M:

```<code>t = M;
t(isnan(M)) = min(M(:))-1;
imagesc(t)
</code>```

Title: give a color to not a number

Body:
I have a matrix of integers, padded with nans

M=

 1     2     2     3     4     4
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN

I am plotting it using imagesc

imagesc(M)

However, if I plot it this way, NaN and 1 are shown with the same color, which is confusing.

How to have different colors for NaNs in imagesc?

Body:
You can replace NaN by 1 less than the minimum number in M:

t = M;
t(isnan(M)) = min(M(:))-1;
imagesc(t)


问:
Jmeter and Docker
I saw some blog posts where people talk about JMeter and Docker. I understand that Docker will be helpful for setting up a container with all the dependencies. But they all run/create the containers in the same host. So ideally all the containers will share the host resources. It is like you run multiple instances of jmeter in the same host. It will not be helpful to generate more load.

When a host has 12GB RAM, I think 1 instance of JMeter with 10GB heap can generate more load than running 10 containers with 1 jmeter instance in each container.

What is the point of running docker here?

答:
I made an automatic solution that can be easily integrated with Jenkins.

The dockerfile should be extended from java8 and add the JMeter build. This Docker image I will call jmeter-base:

```<code>FROM java:8

RUN mkdir /jmeter \
    && cd /jmeter/ \
    && wget https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.3.tgz \
    && tar -xvzf apache-jmeter-3.3.tgz \
    && rm apache-jmeter-3.3.tgz

ENV JMETER_HOME /jmeter/apache-jmeter-3.3/

# Add Jmeter to the Path
ENV PATH $JMETER_HOME/bin:$PATH
</code>```

If you want to use a master-slave solution, this is the jmeter master Dockerfile:

```<code>FROM jmeter-base

WORKDIR $JMETER_HOME
# Ports to be exposed from the container for JMeter Master
RUN mkdir scripts

EXPOSE 60000
</code>```

And this is the jmeter slave Dockerfile:

```<code>FROM jmeter-base

# Ports to be exposed from the container for JMeter Slaves/Server
EXPOSE 1099 50000

# Application to run on starting the container
ENTRYPOINT $JMETER_HOME/bin/jmeter-server \
                        -Dserver.rmi.localport=50000 \
-Dserver_port=1099
</code>```

Now, with the both images, you should execute a script to execute you should know all slave IPs. This script make all the job:

```<code>#!/bin/bash

COUNT=${1-1}

docker build -t jmeter-base jmeter-base
docker-compose build && docker-compose up -d && docker-compose scale master=1 slave=$COUNT

SLAVE_IP=$(docker inspect -f '{{.Name}} {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) | grep slave | awk -F' ' '{print $2}' | tr '\n' ',' | sed 's/.$//')
WDIR=`docker exec -it master /bin/pwd | tr -d '\r'`
mkdir -p results
for filename in scripts/*.jmx; do
    NAME=$(basename $filename)
    NAME="${NAME%.*}"
    eval "docker cp $filename master:$WDIR/scripts/"
    eval "docker exec -it master /bin/bash -c 'mkdir $NAME && cd $NAME && ../bin/jmeter -n -t ../$filename -R$SLAVE_IP'"
    eval "docker cp master:$WDIR/$NAME results/"
done

docker-compose stop && docker-compose rm -f
</code>```

Title: Jmeter and Docker

Body:
I made an automatic solution that can be easily integrated with Jenkins.

The dockerfile should be extended from java8 and add the JMeter build. This Docker image I will call jmeter-base:

FROM java:8

RUN mkdir /jmeter \
    && cd /jmeter/ \
    && wget https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.3.tgz \
    && tar -xvzf apache-jmeter-3.3.tgz \
    && rm apache-jmeter-3.3.tgz

ENV JMETER_HOME /jmeter/apache-jmeter-3.3/

# Add Jmeter to the Path
ENV PATH $JMETER_HOME/bin:$PATH

If you want to use a master-slave solution, this is the jmeter master Dockerfile:

FROM jmeter-base

WORKDIR $JMETER_HOME
# Ports to be exposed from the container for JMeter Master
RUN mkdir scripts

EXPOSE 60000

And this is the jmeter slave Dockerfile:

FROM jmeter-base

# Ports to be exposed from the container for JMeter Slaves/Server
EXPOSE 1099 50000

# Application to run on starting the container
ENTRYPOINT $JMETER_HOME/bin/jmeter-server \
                        -Dserver.rmi.localport=50000 \
-Dserver_port=1099

Now, with the both images, you should execute a script to execute you should know all slave IPs. This script make all the job:

#!/bin/bash

COUNT=${1-1}

docker build -t jmeter-base jmeter-base
docker-compose build && docker-compose up -d && docker-compose scale master=1 slave=$COUNT

SLAVE_IP=$(docker inspect -f '{{.Name}} {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) | grep slave | awk -F' ' '{print $2}' | tr '\n' ',' | sed 's/.$//')
WDIR=`docker exec -it master /bin/pwd | tr -d '\r'`
mkdir -p results
for filename in scripts/*.jmx; do
    NAME=$(basename $filename)
    NAME="${NAME%.*}"
    eval "docker cp $filename master:$WDIR/scripts/"
    eval "docker exec -it master /bin/bash -c 'mkdir $NAME && cd $NAME && ../bin/jmeter -n -t ../$filename -R$SLAVE_IP'"
    eval "docker cp master:$WDIR/$NAME results/"
done

docker-compose stop && docker-compose rm -f


问:
What's the best strategy to provide different comparison operators for the same class?
Consider this simple class storing a value and a time.

```<code>class A
{
public:
    boost::posix_time::ptime when;
    double value;
};
</code>```

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

答:
short answer: don't
I explained why in a comment, the main reason is, it introduces ambiguity in your code and reduces readability which is the opposite of what operators are meant to do. Just use different methods and provide ways to pick which one to use for this sort (like comparers). While I was typing this, people posted good examples of that, even some using a bit of metaprogramming.

however, for science, you kinda can. While you can't add a parameter to an operator (a binary operator is a binary operator, and there doesn't seem to be a syntax to add this third argument somewhere) you can make your operator mean different things in different contexts (c++ context, for a line of code or for a block delimited by '{}')

here done very quickly using construction/destruction order (similar implementation to a trivial lock with no consideration for thread safety):

the comparison looks like:

```<code>Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), Thing{1, 2} < Thing{3, 4};
</code>```

run this example online: http://cpp.sh/3ggrq

```<code>#include <iostream>

struct Thing {
    struct thingSortingMode {
        enum mode {
            defaultMode,
            alternateMode
        };

        mode myLastMode;

        thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "\nmode: " << aMode << "\n"; }
        ~thingSortingMode() { Thing::ourSortingMode = myLastMode; std::cout << "\nmode: " << myLastMode << "\n";}
    };

    bool operator < (Thing another) {
        switch (ourSortingMode) //I use an enum, to make the example more accessible, you can use a functor instead if you want
        {
            case thingSortingMode::alternateMode:
                return myValueB < another.myValueB;
                break;

            default:
                return myValueA < another.myValueA;
                break;
        }
    }

    static thingSortingMode::mode ourSortingMode;

    int myValueA;
    int myValueB;
};

Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;

int main()
{
  Thing a{1, 1}, b{0, 2}; // b < a in default mode, a < b in alternate mode

  std::cout << (a < b); //false

  {
    Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);

    std::cout << (a < b); //true
    Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), std::cout << (a < b), //false
        Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), std::cout << (a < b); //true

    std::cout << (a < b); //true
  }

  std::cout << (a < b); //false
}
</code>```

Note that this construction/destruction trick can manage any kind of contextual state, here is a richer example with 4 states and more nested contexts

run this example online: http://cpp.sh/2x5rj

```<code>#include <iostream>

struct Thing {
    struct thingSortingMode {
        enum mode {
            defaultMode = 1,
            alternateMode,
            mode3,
            mode4,
        };

        mode myLastMode;

        thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "\nmode: " << myLastMode << " -> " << aMode << "\n"; }
        ~thingSortingMode() { std::cout << "\nmode: " << Thing::ourSortingMode << " -> " << myLastMode << "\n"; Thing::ourSortingMode = myLastMode; }
    };

    static thingSortingMode::mode ourSortingMode;
};

Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;

int main()
{
    Thing::thingSortingMode ctx(Thing::thingSortingMode::mode3);
    {
        Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);
        {
            Thing::thingSortingMode ctx(Thing::thingSortingMode::mode4);
            {
                Thing::thingSortingMode ctx(Thing::thingSortingMode::defaultMode);
                std::cout << "end sub 3 (mode 1)\n";
            }

            std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this is the kind of things that might behave strangely\n") <<
                (Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluated\n"); //note though that arguments are still constructed in the right state

            std::cout << "end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous line\n";
        }

        std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this on the other hand (mode 2)\n"),
        std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "works (mode 1)\n"); //but pay attention to the comma and in which order things are deleted

        std::cout << "end sub 1 (mode 2)\n";
    }
    std::cout << "end main (mode 3)\n";
}
</code>```

output:

```<code>mode: 1 -> 3

mode: 3 -> 2

mode: 2 -> 4

mode: 4 -> 1
end sub 3 (mode 1)

mode: 1 -> 4

mode: 4 -> 1

mode: 1 -> 2
this is the kind of things that might behave strangely
here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluated

mode: 2 -> 1

mode: 1 -> 4
end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous line

mode: 4 -> 2

mode: 2 -> 2
this on the other hand (mode 2)

mode: 2 -> 1
works (mode 1)

mode: 1 -> 2

mode: 2 -> 2
end sub 1 (mode 2)

mode: 2 -> 3
end main (mode 3)

mode: 3 -> 1
</code>```

Body:
Consider this simple class storing a value and a time.

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

Body:
short answer: don't
I explained why in a comment, the main reason is, it introduces ambiguity in your code and reduces readability which is the opposite of what operators are meant to do. Just use different methods and provide ways to pick which one to use for this sort (like comparers). While I was typing this, people posted good examples of that, even some using a bit of metaprogramming.

however, for science, you kinda can. While you can't add a parameter to an operator (a binary operator is a binary operator, and there doesn't seem to be a syntax to add this third argument somewhere) you can make your operator mean different things in different contexts (c++ context, for a line of code or for a block delimited by '{}')

here done very quickly using construction/destruction order (similar implementation to a trivial lock with no consideration for thread safety):

the comparison looks like:

Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), Thing{1, 2} < Thing{3, 4};

run this example online: http://cpp.sh/3ggrq

#include <iostream>

struct Thing {
    struct thingSortingMode {
        enum mode {
            defaultMode,
            alternateMode
        };

        mode myLastMode;

        thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "\nmode: " << aMode << "\n"; }
        ~thingSortingMode() { Thing::ourSortingMode = myLastMode; std::cout << "\nmode: " << myLastMode << "\n";}
    };

    bool operator < (Thing another) {
        switch (ourSortingMode) //I use an enum, to make the example more accessible, you can use a functor instead if you want
        {
            case thingSortingMode::alternateMode:
                return myValueB < another.myValueB;
                break;

            default:
                return myValueA < another.myValueA;
                break;
        }
    }

    static thingSortingMode::mode ourSortingMode;

    int myValueA;
    int myValueB;
};

Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;

int main()
{
  Thing a{1, 1}, b{0, 2}; // b < a in default mode, a < b in alternate mode

  std::cout << (a < b); //false

  {
    Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);

    std::cout << (a < b); //true
    Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), std::cout << (a < b), //false
        Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), std::cout << (a < b); //true

    std::cout << (a < b); //true
  }

  std::cout << (a < b); //false
}

Note that this construction/destruction trick can manage any kind of contextual state, here is a richer example with 4 states and more nested contexts

run this example online: http://cpp.sh/2x5rj

#include <iostream>

struct Thing {
    struct thingSortingMode {
        enum mode {
            defaultMode = 1,
            alternateMode,
            mode3,
            mode4,
        };

        mode myLastMode;

        thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "\nmode: " << myLastMode << " -> " << aMode << "\n"; }
        ~thingSortingMode() { std::cout << "\nmode: " << Thing::ourSortingMode << " -> " << myLastMode << "\n"; Thing::ourSortingMode = myLastMode; }
    };

    static thingSortingMode::mode ourSortingMode;
};

Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;

int main()
{
    Thing::thingSortingMode ctx(Thing::thingSortingMode::mode3);
    {
        Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);
        {
            Thing::thingSortingMode ctx(Thing::thingSortingMode::mode4);
            {
                Thing::thingSortingMode ctx(Thing::thingSortingMode::defaultMode);
                std::cout << "end sub 3 (mode 1)\n";
            }

            std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this is the kind of things that might behave strangely\n") <<
                (Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluated\n"); //note though that arguments are still constructed in the right state

            std::cout << "end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous line\n";
        }

        std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this on the other hand (mode 2)\n"),
        std::cout <<
                (Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "works (mode 1)\n"); //but pay attention to the comma and in which order things are deleted

        std::cout << "end sub 1 (mode 2)\n";
    }
    std::cout << "end main (mode 3)\n";
}

output:

mode: 1 -> 3

mode: 3 -> 2

mode: 2 -> 4

mode: 4 -> 1
end sub 3 (mode 1)

mode: 1 -> 4

mode: 4 -> 1

mode: 1 -> 2
this is the kind of things that might behave strangely
here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluated

mode: 2 -> 1

mode: 1 -> 4
end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous line

mode: 4 -> 2

mode: 2 -> 2
this on the other hand (mode 2)

mode: 2 -> 1
works (mode 1)

mode: 1 -> 2

mode: 2 -> 2
end sub 1 (mode 2)

mode: 2 -> 3
end main (mode 3)

mode: 3 -> 1


问:
issue with understanding macros in C programming
what is the output of the below code if i give '1' as an input and why ?

FYI ::iam using gcc to build the code.

```<code>#include <stdio.h>
int main()
{
    // k integer to hold user input
    int k=0;

    scanf("%d",&k);

    switch(k)
    {
        case 1 :
        #define first_case
        break;
        case 2 :
         #define second_case
        break;
        case 3 :
         #define third_case
        break;
        case 4 :
        #define fourth_case
        break;
    }
</code>```

#ifdef first_case
        printf(" first_case\n");
  #endif

#ifdef second_case
        printf(" second_case\n");
  #endif

#ifdef third_case
        printf(" third_case\n");
 #endif

#ifdef fourth_case
        printf(" fourth_case\n");
 #endif

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

答:
Macros (#define MACRO ...) are processed by the C preprocessor before the actuel compile process takes place.

So the compiler only "sees" this once the file has been preprocessed:

```<code>int main()
{
  // your code goes here
  int k = 0;

  scanf("%d", &k);
  switch (k)
  {
  case 1:
    break;
  case 2:
    break;
  case 3:
    break;
  case 4:
    break;
  }

  printf("typed first_case\n");
  printf("typed second_case\n");
  printf("typed third_case\n");
  printf("typed fourth_case\n");
}
</code>```

You could write your program like this, and the outcome would be exactly the same:

```<code>#define first_case
#define second_case
#define third_case
#define fourth_case

/* Find the longest line among the giving inputs and print it */

#include <stdio.h>
int main()
{
  // your code goes here
  int k = 0;

  scanf("%d", &k);
  switch (k)
  {
  case 1:
    printf("case 1\n");
    break;
  case 2:
    break;
  case 3:
    break;
  case 4:
    break;
  }

#ifdef first_case
  printf("typed first_case\n");
#endif
#ifdef second_case
  printf("typed second_case\n");
#endif

#ifdef third_case
  printf("typed third_case\n");
#endif
#ifdef fourth_case
  printf("typed fourth_case\n");
#endif

}
</code>```

Body:
what is the output of the below code if i give '1' as an input and why ?

FYI ::iam using gcc to build the code.

#include <stdio.h>
int main()
{
    // k integer to hold user input
    int k=0;

    scanf("%d",&k);

    switch(k)
    {
        case 1 :
        #define first_case
        break;
        case 2 :
         #define second_case
        break;
        case 3 :
         #define third_case
        break;
        case 4 :
        #define fourth_case
        break;
    }

#ifdef first_case
        printf(" first_case\n");
  #endif

#ifdef second_case
        printf(" second_case\n");
  #endif

#ifdef third_case
        printf(" third_case\n");
 #endif

#ifdef fourth_case
        printf(" fourth_case\n");
 #endif

}

Body:
Macros (#define MACRO ...) are processed by the C preprocessor before the actuel compile process takes place.

So the compiler only "sees" this once the file has been preprocessed:

int main()
{
  // your code goes here
  int k = 0;

  scanf("%d", &k);
  switch (k)
  {
  case 1:
    break;
  case 2:
    break;
  case 3:
    break;
  case 4:
    break;
  }

  printf("typed first_case\n");
  printf("typed second_case\n");
  printf("typed third_case\n");
  printf("typed fourth_case\n");
}

You could write your program like this, and the outcome would be exactly the same:

#define first_case
#define second_case
#define third_case
#define fourth_case

/* Find the longest line among the giving inputs and print it */

#include <stdio.h>
int main()
{
  // your code goes here
  int k = 0;

  scanf("%d", &k);
  switch (k)
  {
  case 1:
    printf("case 1\n");
    break;
  case 2:
    break;
  case 3:
    break;
  case 4:
    break;
  }

#ifdef first_case
  printf("typed first_case\n");
#endif
#ifdef second_case
  printf("typed second_case\n");
#endif

#ifdef third_case
  printf("typed third_case\n");
#endif
#ifdef fourth_case
  printf("typed fourth_case\n");
#endif

}


问:
Sample code use for (moa PairedLearners)
Hello I am new into using MOA and WEKA,

I need to test paired learners concept using this code and I have been able to locate the code but I cannot find any example online and
I am having a hard time figuring how to pas my data into the code and run a test and see my results.
Pls can anyone point my in a right direction or give me a few pointers that I could follow to implement this.

moa/moa/src/main/java/moa/classifiers/meta/PairedLearners.java

Trying to use a similar code like this:
https://groups.google.com/forum/#!topic/moa-development/3IKcguR2kOk

Best Regards.
//Sample code below

```<code>import moa.classifiers.meta.pairedLearner;

Public class SamplePairedlearner{
public static void main(String[] args) {
    FileStream fStream = new FileStream();
    fStream.arffFileOption.setValue("test.arff");// set the ARFF file name
    fStream.normalizeOption.setValue(false);// set normalized to be true or false
    fStream.prepareForUse();
int numLines = 0;
PairedLearner learners = PairedLearners();
learners.resetLearning();
learners.resetLearningImpl(); //this is where i get an error message
ClusteringStream stream = fStream;
    while (stream.hasMoreInstances()) {
        Instance curr = stream.nextInstance().getData();
        learners.trainOnInstanceImpl(curr)//this line also generates an error
        numLines++;
    }
    Clustering resDstream = dstream.getClusteringResult();
    dstream.getMicroClusteringResult();
    System.out.println("Size of result from Dstream: " + resDstream.size());
    System.out.println(numLines + " lines have been read");
}
}
</code>```

答:
I could fix the code that you have there, but it wouldn't do you much good. MOA has it's own selection of tasks and evaluators for running these experiments at a much higher level. This is how to run evaluations properly and not dive too deeply into the code. I'll assume a few things:

We use PairedLearners as our classifier.

We evaluate stream classification performance.

We evaluate in predictive sequential (prequential) fashion, i.e. train, then test on each example in the sequence.

Therefore, we can define our task quite simply, as follows.

```<code>public class PairedLearnersExample {

    public static void main(String[] args) {

        ArffFileStream fs = new ArffFileStream(PairedLearnersExample.class.getResource("abalone.arff").getFile(), -1);
        fs.prepareForUse();

        PairedLearners learners = new PairedLearners();

        BasicClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator();

        EvaluatePrequential task = new EvaluatePrequential();
        task.learnerOption.setCurrentObject(learners);
        task.streamOption.setCurrentObject(fs);
        task.evaluatorOption.setCurrentObject(evaluator);

        task.prepareForUse();

        LearningCurve le = (LearningCurve) task.doTask();

        System.out.println(le);

    }

}
</code>```

If you want to do other tasks, you can quite happily swap out the evaluator, stream and learner to achieve whatever it is you want to do.

If you refer to the MOA Manual you'll see that all I'm doing is imitating the command line commands - you could equally perform this evaluation at the command line if you wished.

For example,

```<code>java -cp .:moa.jar:weka.jar -javaagent:sizeofag.jar moa.DoTask \
"EvaluatePrequential -l PairedLearners \
-e BasicClassificationPerformanceEvaluator \
-s (ArffFileStream -f abalone.arff) \
-i 100000000 -f 1000000" > plresult_abalone.csv
</code>```

Body:
Hello I am new into using MOA and WEKA,

I need to test paired learners concept using this code and I have been able to locate the code but I cannot find any example online and
I am having a hard time figuring how to pas my data into the code and run a test and see my results.
Pls can anyone point my in a right direction or give me a few pointers that I could follow to implement this.

moa/moa/src/main/java/moa/classifiers/meta/PairedLearners.java

Trying to use a similar code like this:
https://groups.google.com/forum/#!topic/moa-development/3IKcguR2kOk

Best Regards.
//Sample code below

import moa.classifiers.meta.pairedLearner;

Public class SamplePairedlearner{
public static void main(String[] args) {
    FileStream fStream = new FileStream();
    fStream.arffFileOption.setValue("test.arff");// set the ARFF file name
    fStream.normalizeOption.setValue(false);// set normalized to be true or false
    fStream.prepareForUse();
int numLines = 0;
PairedLearner learners = PairedLearners();
learners.resetLearning();
learners.resetLearningImpl(); //this is where i get an error message
ClusteringStream stream = fStream;
    while (stream.hasMoreInstances()) {
        Instance curr = stream.nextInstance().getData();
        learners.trainOnInstanceImpl(curr)//this line also generates an error
        numLines++;
    }
    Clustering resDstream = dstream.getClusteringResult();
    dstream.getMicroClusteringResult();
    System.out.println("Size of result from Dstream: " + resDstream.size());
    System.out.println(numLines + " lines have been read");
}
}

Body:
I could fix the code that you have there, but it wouldn't do you much good. MOA has it's own selection of tasks and evaluators for running these experiments at a much higher level. This is how to run evaluations properly and not dive too deeply into the code. I'll assume a few things:

We use PairedLearners as our classifier.

We evaluate stream classification performance.

We evaluate in predictive sequential (prequential) fashion, i.e. train, then test on each example in the sequence.

Therefore, we can define our task quite simply, as follows.

public class PairedLearnersExample {

    public static void main(String[] args) {

        ArffFileStream fs = new ArffFileStream(PairedLearnersExample.class.getResource("abalone.arff").getFile(), -1);
        fs.prepareForUse();

        PairedLearners learners = new PairedLearners();

        BasicClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator();

        EvaluatePrequential task = new EvaluatePrequential();
        task.learnerOption.setCurrentObject(learners);
        task.streamOption.setCurrentObject(fs);
        task.evaluatorOption.setCurrentObject(evaluator);

        task.prepareForUse();

        LearningCurve le = (LearningCurve) task.doTask();

        System.out.println(le);

    }

}

If you want to do other tasks, you can quite happily swap out the evaluator, stream and learner to achieve whatever it is you want to do.

If you refer to the MOA Manual you'll see that all I'm doing is imitating the command line commands - you could equally perform this evaluation at the command line if you wished.

For example,

java -cp .:moa.jar:weka.jar -javaagent:sizeofag.jar moa.DoTask \
"EvaluatePrequential -l PairedLearners \
-e BasicClassificationPerformanceEvaluator \
-s (ArffFileStream -f abalone.arff) \
-i 100000000 -f 1000000" > plresult_abalone.csv


问:
multi tenancy using Spring3
I am developing a multi-tenancy application using spring 3.0 and have need to upload the download the files into/from FTP server depending upon the tenant. We have different FTP location in the same FTP server for each tenant. Can you please help me how to configure/change the FTP location depending upon the tenant using spring 3.?</p>

答:
You somehow have tenant resolver and/or tenant context. E.g. as described here or see here

So all you need is to get tenant identifier - String representing the tenant. Then you can have a Map where key is tenant identifier and values is the required path or organize some logic to get the path from DB by tenant identifier.

Title: multi tenancy using Spring3


问:
How do I "apply" to results of a parameter-less function
This works:

```<code>List(3, 1, 2).sorted apply 1
res1: Int = 2
</code>```

And this works:

```<code>var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2
</code>```

but this doesn't:

```<code>List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^
</code>```

And even parentheses don't clue the parser in to what I want:

```<code>(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)
</code>```

It seems like a natural expression.  What am I doing wrong?

答:
I think you have to keep the apply. The reason is that sorted isn't "parameterless", it's defined as

```<code>def sorted [B >: A] (implicit ord: Ordering[B]) : List[A]
</code>```

As this is an implicit parameter, the Ordering[Int] is normally provided automatically, but if you use parens, the compiler thinks you want to specify another Ordering[Int] (let's say backwards).

Body:
This works:

List(3, 1, 2).sorted apply 1
res1: Int = 2

And this works:

var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2

but this doesn't:

List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^

And even parentheses don't clue the parser in to what I want:

(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)

It seems like a natural expression.  What am I doing wrong?

Body:
I think you have to keep the apply. The reason is that sorted isn't "parameterless", it's defined as

def sorted [B >: A] (implicit ord: Ordering[B]) : List[A]

As this is an implicit parameter, the Ordering[Int] is normally provided automatically, but if you use parens, the compiler thinks you want to specify another Ordering[Int] (let's say backwards).