问:
Frequency count for Comma delimited categories within a column
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

```<code>Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
</code>```

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

答:
If you insist on the output format as shown in the screenshot, here is a base R solution (no additional R libraries):</p>

```<code>df <- read.table(text =
    "Zip Make
     12325 Toyota,Honda,Toyota,Mitsubishi,Mercedes
     85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan
     56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda",
     header = T, stringsAsFactors = F)

df$Frequency <- sapply(lapply(strsplit(df$Make, ","), function(x)
    paste0(apply(as.data.frame(table(x)), 1, paste, collapse = "("), ")")),
    paste, collapse = ",");

df$top <- sapply(lapply(strsplit(df$Make, ","), function(x)
    names(table(x)[order(-table(x))][1:3])),
    paste, collapse = ",");

df;
#    Zip
#1 12325
#2 85271
#3 56098
#                                                                       Make
#1                                   Toyota,Honda,Toyota,Mitsubishi,Mercedes
#2 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan
#3  Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda
#                                               Frequency                    top
#1           Honda(1),Mercedes(1),Mitsubishi(1),Toyota(2)  Toyota,Honda,Mercedes
#2                  Honda(2),Nissan(4),Toyota(4),Volvo(1)    Nissan,Toyota,Honda
#3 Acura(1),Chevrolet(3),Honda(2),Mitsubishi(1),Toyota(2) Chevrolet,Honda,Toyota
</code>```

Body:
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

Body:
If you insist on the output format as shown in the screenshot, here is a base R solution (no additional R libraries):

df <- read.table(text =
    "Zip Make
     12325 Toyota,Honda,Toyota,Mitsubishi,Mercedes
     85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan
     56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda",
     header = T, stringsAsFactors = F)

df$Frequency <- sapply(lapply(strsplit(df$Make, ","), function(x)
    paste0(apply(as.data.frame(table(x)), 1, paste, collapse = "("), ")")),
    paste, collapse = ",");

df$top <- sapply(lapply(strsplit(df$Make, ","), function(x)
    names(table(x)[order(-table(x))][1:3])),
    paste, collapse = ",");

df;
#    Zip
#1 12325
#2 85271
#3 56098
#                                                                       Make
#1                                   Toyota,Honda,Toyota,Mitsubishi,Mercedes
#2 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan
#3  Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda
#                                               Frequency                    top
#1           Honda(1),Mercedes(1),Mitsubishi(1),Toyota(2)  Toyota,Honda,Mercedes
#2                  Honda(2),Nissan(4),Toyota(4),Volvo(1)    Nissan,Toyota,Honda
#3 Acura(1),Chevrolet(3),Honda(2),Mitsubishi(1),Toyota(2) Chevrolet,Honda,Toyota


来源: stackexchange

问:
How to keep the state of input checkbox on page reload
How do I store a cookie for input checkbox current state? Every time when the page reloads, the state is restored to default (unchecked) and I've been buzzing my head with this. I even used a library without any success

https://github.com/js-cookie/js-cookie Cookie.set() and Cookie.get() but without success.

I've been also reading about localStorage JavaScript API but can't seem to getting working.

jQuery code:

```<code>$(function () {
    $('input[type="checkbox"]').click( () => {
        if ($(this).is(':checked')) {
            $('input[type="checkbox"]').prop('checked', true, localStorage.getItem('checked')).attr('checked', 'checked');
            localStorage.setItem('checked', 'checked');
            $('img').attr('src', '/full_logo_transparent.png');
            $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css');
            console.log('Dark Mode enabled');
        } else {
            $('input[type="checkbox"]').prop('checked', false);
            $('link#hueman-main-style-css').attr('href', '/main.min.css');
        }
    })
});
</code>```

This is suppose to remember the state of the input checkbox and save it upon page reload so that it doesn't have to be toggled every single time (It loads additional CSS file)

Am I missing something? Is the order correct?

The site is https://itmagazin.info and on the right you will find input:checkbox with the name "Noćni Režim" which activates the dark mode, but it doesn't stay that way after you click on any article.

Any help is appreciated.

答:
This is much simpler than you are doing. Just get the last stored value upon page load and set it appropriately based on the state of the checkbox after being clicked.

The following code won't work in the Stack Overflow snippet environment, due to sandboxing, but you can test it here.

$(function () {
  // Reset the checkbox to the last state on the last visit
  // The value in localStorage will be the strings "true", "false" or
  // it won't be there at all, in which case "" will be returned.
  // The opposite of "true" (or !"true") is the Boolean false and the
  // opposite of that (!!"true") is the Boolean true.  The opposite of
  // "" (!"") is the Boolean true and the opposite of that (!!"") is the
  // Boolean false
  $('#check').prop("checked", !!localStorage.getItem("darkMode"));

  $('#check').on("click", function() {
    if ($(this).is(":checked")) {
      localStorage.setItem('darkMode', 'true');
      $('img').attr('src', '/full_logo_transparent.png');
      $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css');
      console.log('Dark Mode enabled');
    } else {
      localStorage.setItem('darkMode', 'false');
      $('link#hueman-main-style-css').attr('href', '/main.min.css');
      console.log("No Dark Mode");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="test" id="check"><label for="check">Item</label></code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I store a cookie for input checkbox current state? Every time when the page reloads, the state is restored to default (unchecked) and I've been buzzing my head with this. I even used a library without any success

https://github.com/js-cookie/js-cookie Cookie.set() and Cookie.get() but without success.

I've been also reading about localStorage JavaScript API but can't seem to getting working.

jQuery code:

$(function () {
    $('input[type="checkbox"]').click( () => {
        if ($(this).is(':checked')) {
            $('input[type="checkbox"]').prop('checked', true, localStorage.getItem('checked')).attr('checked', 'checked');
            localStorage.setItem('checked', 'checked');
            $('img').attr('src', '/full_logo_transparent.png');
            $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css');
            console.log('Dark Mode enabled');
        } else {
            $('input[type="checkbox"]').prop('checked', false);
            $('link#hueman-main-style-css').attr('href', '/main.min.css');
        }
    })
});

This is suppose to remember the state of the input checkbox and save it upon page reload so that it doesn't have to be toggled every single time (It loads additional CSS file)

Am I missing something? Is the order correct?

The site is https://itmagazin.info and on the right you will find input:checkbox with the name "Noćni Režim" which activates the dark mode, but it doesn't stay that way after you click on any article.

Any help is appreciated.

Body:
This is much simpler than you are doing. Just get the last stored value upon page load and set it appropriately based on the state of the checkbox after being clicked.

The following code won't work in the Stack Overflow snippet environment, due to sandboxing, but you can test it here.

$(function () {
  // Reset the checkbox to the last state on the last visit
  // The value in localStorage will be the strings "true", "false" or
  // it won't be there at all, in which case "" will be returned.
  // The opposite of "true" (or !"true") is the Boolean false and the
  // opposite of that (!!"true") is the Boolean true.  The opposite of
  // "" (!"") is the Boolean true and the opposite of that (!!"") is the
  // Boolean false
  $('#check').prop("checked", !!localStorage.getItem("darkMode"));

  $('#check').on("click", function() {
    if ($(this).is(":checked")) {
      localStorage.setItem('darkMode', 'true');
      $('img').attr('src', '/full_logo_transparent.png');
      $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css');
      console.log('Dark Mode enabled');
    } else {
      localStorage.setItem('darkMode', 'false');
      $('link#hueman-main-style-css').attr('href', '/main.min.css');
      console.log("No Dark Mode");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="test" id="check"><label for="check">Item</label>


问:
Show div in order when key down
I'm new in coding and sometimes it's hard to find the right term when you search something. I've come a long way but stuck on this piece. Hopefully, someone can help me with the right search term or function.

I've created a responsive grid 2x3 fullscreen, and now when the key is pressed, for example 'a'. A live video will show (opacity from 0 to 1) at the top left box in the grid. 's' key for the second box with another live video and so on for all the six boxes.

But I want to create when one key is pressed, that one video will be played (and it doesn't matter which one of the six) on the top left the box. When a second key is pressed at the same time it will show up in the second box. When a third key is pressed at the same time, it will show up at the third box.

So, the place were it shows depends on the order of the pressed keys. I've tried to search the internet but couldn't find a thing, can someone help me with this? I've created this in Javascript. Thanks!

```<code> document.addEventListener("keyup", keyupFunction);
 document.addEventListener("keydown", keydownFunction);

function keydownFunction(e) {
if(e.which == 65){/* a */
    document.getElementById("video1").style.opacity = "1";
    myAudio.volume = 1.0;

 } else if (e.which == 83) {/* s */
    document.getElementById("video2").style.opacity = "1";
    myAudio2.volume = 1.0;

 } else if (e.which == 68) {/* d */
    document.getElementById("video3").style.opacity = "1";
    myAudio3.volume = 1.0;

 } else if (e.which == 70) {/* f */
    document.getElementById("video4").style.opacity = "1";
    myAudio4.volume = 1.0;

 } else if (e.which == 71) {/* g */
    document.getElementById("video5").style.opacity = "1";
    myAudio5.volume = 1.0;

 } else if (e.which == 72) {/* h */
    document.getElementById("video6").style.opacity = "1";
    myAudio6.volume = 1.0;
</code>```

```<code>    <div class="container-fluid items" id="items">
<div class="row menusrow">
    <div class="col-md-12">
        <div class="row">
            <div class="col-xs-4 video-container">
        <img id="video1" src="http://105.198.227.126:8080/cgi-
bin/camera?">
            </div>

            <div class="col-xs-4 video-container">
        <img id="video2" src="http://24.222.39.230:8082/mjpeg.cgi">
            </div>

            <div class="col-xs-4 video-container">
    <img id="video3" src="http://182.150.46.230:8000/oneshotimage1?
1511867998">
            </div>
        </div>

        <div class="row">
            <div class="col-xs-4 video-container">
    <img id="video4" src="http://77.20.35.33:80/mjpg/video.mjpg?
COUNTER">
            </div>

            <div class="col-xs-4 video-container">
    <img id="video5" src="http://122.166.104.28:89/SnapshotJPEG?
Resolution=640x480&Quality=Clarity&1511867938">
            </div>

            <div class="col-xs-4 video-container">
    <img id="video6" src="http://117.102.176.209:50000/cgi-bin/camera?resolution=640&quality=1&Language=0&1511873906">
            </div>
        </div>
    </div>
</div>
</code>```

```<code>.video-container {
height: 100%;
position:relative;
padding-left: 0px;
padding-right: 0px;

#video1 {
opacity: 0;
height: 100%;
width: 100%;
}

#video2 {
opacity: 0;
height: 100%;
width: 100%;
}
</code>```

and so on until video6.

答:
Alright, this code listens for key pressing and releasing. Pressing increments a counter; releasing decrements that counter. Based on the value n of the counter, n items are made visible.

window.onload = function() {
  var keys = [];
  for (var i = 0; i < 256; i++) keys.push(false);
  var numDown = 0;

  var refocus = function() {
    var items = document.getElementsByClassName('item');

    // Unfocus all
    for (var i = 0; i < items.length; i++)
      items[i].classList.remove('active');

    // Now focus the appropriate amount
    for (var i = 0; i < Math.min(numDown, items.length); i++)
      items[i].classList.add('active');
  };

  var items = document.getElementById('items');
  items.onfocus = function() {
    items.classList.add('focused');
  };
  items.onblur = function() {
    items.classList.remove('focused');
  };

  items.onkeydown = function(e) {
    if (e.keyCode < 65 || e.keyCode > 90 || keys[e.keyCode]) return;
    keys[e.keyCode] = true;
    numDown++;
    refocus();
  };
  items.onkeyup = function(e) {
    if (e.keyCode < 65 || e.keyCode > 90 || !keys[e.keyCode]) return;
    keys[e.keyCode] = false;
    numDown--;
    refocus();
  };

  items.focus();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.items {
  position: absolute;
  width: 100%; height: 100%;
  left: 0; top: 0;
  overflow: hidden;
  margin: 0; padding: 0;
  font-size: 0; /* remove spaces */
  background-color: #ffffff;
}
.item {
  box-sizing: border-box;
  display: inline-block;
  width: 33.333%; height: 50%;
  border: 1px solid #ff0000;
  background-color: #a0a0a0;
  transition: background-color 1000ms linear;
}
.item.active {
  background-color: #7070f0;
}
.items.focused > .item {
  border: 1px solid #ffffff;
}</code>```

```

Please let me know if this is what you were looking for! Also note there's a bit of the extra code making it obvious whether or not the controls are focused (listening for keypresses)

Note this obviously isn't a full answer, but I think it's the piece of the puzzle you need in order to do the rest yourself.

Note that many keyboards will fail to register many simultaneous keypresses! I find that the left side of my keyboard can only register max 4 inputs at a time; same with the right side. I can only register a max of 8 total simultaneous inputs on my keyboard by maxing out both sides.

Title: Show div in order when key down

Body:
I'm new in coding and sometimes it's hard to find the right term when you search something. I've come a long way but stuck on this piece. Hopefully, someone can help me with the right search term or function.

I've created a responsive grid 2x3 fullscreen, and now when the key is pressed, for example 'a'. A live video will show (opacity from 0 to 1) at the top left box in the grid. 's' key for the second box with another live video and so on for all the six boxes.

But I want to create when one key is pressed, that one video will be played (and it doesn't matter which one of the six) on the top left the box. When a second key is pressed at the same time it will show up in the second box. When a third key is pressed at the same time, it will show up at the third box.

So, the place were it shows depends on the order of the pressed keys. I've tried to search the internet but couldn't find a thing, can someone help me with this? I've created this in Javascript. Thanks!

 document.addEventListener("keyup", keyupFunction);
 document.addEventListener("keydown", keydownFunction);

function keydownFunction(e) {
if(e.which == 65){/* a */
    document.getElementById("video1").style.opacity = "1";
    myAudio.volume = 1.0;

 } else if (e.which == 83) {/* s */
    document.getElementById("video2").style.opacity = "1";
    myAudio2.volume = 1.0;

 } else if (e.which == 68) {/* d */
    document.getElementById("video3").style.opacity = "1";
    myAudio3.volume = 1.0;

 } else if (e.which == 70) {/* f */
    document.getElementById("video4").style.opacity = "1";
    myAudio4.volume = 1.0;

 } else if (e.which == 71) {/* g */
    document.getElementById("video5").style.opacity = "1";
    myAudio5.volume = 1.0;

 } else if (e.which == 72) {/* h */
    document.getElementById("video6").style.opacity = "1";
    myAudio6.volume = 1.0;

.video-container {
height: 100%;
position:relative;
padding-left: 0px;
padding-right: 0px;

#video1 {
opacity: 0;
height: 100%;
width: 100%;
}

#video2 {
opacity: 0;
height: 100%;
width: 100%;
}

and so on until video6.

Body:
Alright, this code listens for key pressing and releasing. Pressing increments a counter; releasing decrements that counter. Based on the value n of the counter, n items are made visible.

window.onload = function() {
  var keys = [];
  for (var i = 0; i < 256; i++) keys.push(false);
  var numDown = 0;

  var refocus = function() {
    var items = document.getElementsByClassName('item');

    // Unfocus all
    for (var i = 0; i < items.length; i++)
      items[i].classList.remove('active');

    // Now focus the appropriate amount
    for (var i = 0; i < Math.min(numDown, items.length); i++)
      items[i].classList.add('active');
  };

  var items = document.getElementById('items');
  items.onfocus = function() {
    items.classList.add('focused');
  };
  items.onblur = function() {
    items.classList.remove('focused');
  };

  items.onkeydown = function(e) {
    if (e.keyCode < 65 || e.keyCode > 90 || keys[e.keyCode]) return;
    keys[e.keyCode] = true;
    numDown++;
    refocus();
  };
  items.onkeyup = function(e) {
    if (e.keyCode < 65 || e.keyCode > 90 || !keys[e.keyCode]) return;
    keys[e.keyCode] = false;
    numDown--;
    refocus();
  };

  items.focus();
};

.items {
  position: absolute;
  width: 100%; height: 100%;
  left: 0; top: 0;
  overflow: hidden;
  margin: 0; padding: 0;
  font-size: 0; /* remove spaces */
  background-color: #ffffff;
}
.item {
  box-sizing: border-box;
  display: inline-block;
  width: 33.333%; height: 50%;
  border: 1px solid #ff0000;
  background-color: #a0a0a0;
  transition: background-color 1000ms linear;
}
.item.active {
  background-color: #7070f0;
}
.items.focused > .item {
  border: 1px solid #ffffff;
}

<div class="items" id="items" tabindex="-1">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Please let me know if this is what you were looking for! Also note there's a bit of the extra code making it obvious whether or not the controls are focused (listening for keypresses)

Note this obviously isn't a full answer, but I think it's the piece of the puzzle you need in order to do the rest yourself.

Note that many keyboards will fail to register many simultaneous keypresses! I find that the left side of my keyboard can only register max 4 inputs at a time; same with the right side. I can only register a max of 8 total simultaneous inputs on my keyboard by maxing out both sides.


问:
MDX Excel Pivot formula
Would appreciate any help with this, I’m struggling with the MDX  trying to calculate BMI ( Body Mass Index = Weight / Height Squared ), as a Calculated Member in PivotTable Tools -> Analyze -> OLAP Tools -> MDX Calculated Member.

I believe I need an IF, as Height might be 0 in some cases, and hence /DIV0 issues.

IF [Height] IS > 0 THEN ( [Weight] / ( [Height] * [Height] ) ELSE 0 END IF

Thanks in advance for any help.

Thanks
Gav

答:
If you need mdx then the operator if does not exist - you should use iif:

```<code>IIF(
  [Measures].[Height] = 0
 ,NULL
 ,DIVIDE(
     [Measures].[Weight]
   , ( [Measures].[Height] * [Measures].[Height] )
 )
)
</code>```

As you are creating a measure I think this needs to be wrapped in an Aggregate function:

```<code>SUM(
IIF(
  [Measures].[Height] = 0
 ,NULL
 ,DIVIDE(
     [Measures].[Weight]
   , ( [Measures].[Height] * [Measures].[Height] )
 )
 )
)
</code>```

Title: MDX Excel Pivot formula

Body:
If you need mdx then the operator if does not exist - you should use iif:

IIF(
  [Measures].[Height] = 0
 ,NULL
 ,DIVIDE(
     [Measures].[Weight]
   , ( [Measures].[Height] * [Measures].[Height] )
 )
)

As you are creating a measure I think this needs to be wrapped in an Aggregate function:

SUM(
IIF(
  [Measures].[Height] = 0
 ,NULL
 ,DIVIDE(
     [Measures].[Weight]
   , ( [Measures].[Height] * [Measures].[Height] )
 )
 )
)


问:
SQL - Can this relation have a primary key?
The relationship between bands and members, 'MemberOf', includes a member id (Mid), band id (Bid), 'StartYear', 'EndYear' and 'Instrument' played. Mid and Bid are both foreign keys to Member and Band relations respectively but I am struggling to identify the primary key in this situation for the 'MemberOf' relation.

Note: start year can be null if a member was in a band from the start and end year can also be null if a member is still in the band.

In this situation, start and end year cannot be used as PK's as they may contain null values, but the member id and band id is not enough information to be unique - e.g. the same member returns to the same band at a later date.

Does this mean no primary key exists? Thanks.

答:
You are right that the dates cannot be considered part of the PK as they are data that will change over time.  I think you have two options:

1) Split the MemberOf record into a parent child pair with the child table, maybe called MemberOfYears, containing Mid, Bid, and a Year and the parent, MemberOf, just becomes Mid & Bid.  So one MemberOfYears record would be included of each Year the member was a member of that particular band.

2) Add an artificial key to the MemberOf relationship table and use it as the primary.

ContentLicense: CC BY-SA 2.5


问:
Matlab heatmap: Making a uniform colorscale for all subplots
I have 4 different dataset A,B,C,Dto generate 4 heatmaps in a subplot

```<code>xvalues = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'};
yvalues = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'};

subplot(2,2,1)
HA = heatmap(xvalues,yvalues,A);
HA.Title = 'A';
HA.XLabel = 'area';
HA.YLabel = 'area';

subplot(2,2,2)
HB = heatmap(xvalues,yvalues,B);
HB.Title = 'B';
HB.XLabel = 'area';
HB.YLabel = 'area';

subplot(2,2,3)
HC = heatmap(xvalues,yvalues,C);
HC.Title = 'C';
HC.XLabel = 'area';
HC.YLabel = 'area';

subplot(2,2,4)
HD = heatmap(xvalues,yvalues,D);
HD.Title = 'D';
HD.XLabel = 'area';
HD.YLabel = 'area';
</code>```

Since each dataset has a different max and min value, the heatmap used the corresponding min and max values of each dataset for its color scale, so all 4 plots looked similar to each other. Is there a way to make a color scale so that it's uniformly used across all subplots? (will be easier to see the differences between the subplots)

答:
You first want to get the minimum and maximum values across all of the data sets, then use these to set the 'ColorLimits' property of each heatmap:

```<code>minValue = min([A(:); B(:); C(:); D(:)]);
maxValue = max([A(:); B(:); C(:); D(:)]);
HA.ColorLimits = [minValue maxValue];
HB.ColorLimits = [minValue maxValue];
HC.ColorLimits = [minValue maxValue];
HD.ColorLimits = [minValue maxValue];
</code>```

You could also use the caxis function (as you typically would for other plots), although you have to target each heatmap object since they each have their own colormap:

```<code>caxis(HA, [minValue maxValue]);
caxis(HB, [minValue maxValue]);
caxis(HC, [minValue maxValue]);
caxis(HD, [minValue maxValue]);
</code>```

Body:
I have 4 different dataset A,B,C,Dto generate 4 heatmaps in a subplot

xvalues = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'};
yvalues = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'};

subplot(2,2,1)
HA = heatmap(xvalues,yvalues,A);
HA.Title = 'A';
HA.XLabel = 'area';
HA.YLabel = 'area';

subplot(2,2,2)
HB = heatmap(xvalues,yvalues,B);
HB.Title = 'B';
HB.XLabel = 'area';
HB.YLabel = 'area';

subplot(2,2,3)
HC = heatmap(xvalues,yvalues,C);
HC.Title = 'C';
HC.XLabel = 'area';
HC.YLabel = 'area';

subplot(2,2,4)
HD = heatmap(xvalues,yvalues,D);
HD.Title = 'D';
HD.XLabel = 'area';
HD.YLabel = 'area';

Since each dataset has a different max and min value, the heatmap used the corresponding min and max values of each dataset for its color scale, so all 4 plots looked similar to each other. Is there a way to make a color scale so that it's uniformly used across all subplots? (will be easier to see the differences between the subplots)

Body:
You first want to get the minimum and maximum values across all of the data sets, then use these to set the 'ColorLimits' property of each heatmap:

minValue = min([A(:); B(:); C(:); D(:)]);
maxValue = max([A(:); B(:); C(:); D(:)]);
HA.ColorLimits = [minValue maxValue];
HB.ColorLimits = [minValue maxValue];
HC.ColorLimits = [minValue maxValue];
HD.ColorLimits = [minValue maxValue];

You could also use the caxis function (as you typically would for other plots), although you have to target each heatmap object since they each have their own colormap:

caxis(HA, [minValue maxValue]);
caxis(HB, [minValue maxValue]);
caxis(HC, [minValue maxValue]);
caxis(HD, [minValue maxValue]);


问:
How to get value from a multi-array?
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

```<code>print_r($myarray);
</code>```

gives array like this:

```<code>Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)
</code>```

I am trying to get customer number if the ID matches with 21

```<code>foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}
</code>```

答:
Since you are looping through the array you already have a single item. So just do it this way

```<code>foreach ($myarray as $array) {
  if ($array["id"] == "21") {
    return $array["customer_id"];
  }
}
</code>```

Title: How to get value from a multi-array?

Body:
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

print_r($myarray);

gives array like this:

Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)

I am trying to get customer number if the ID matches with 21

foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}

Body:
Since you are looping through the array you already have a single item. So just do it this way

foreach ($myarray as $array) {
  if ($array["id"] == "21") {
    return $array["customer_id"];
  }
}


问:
When is referential constraint mandatory
I created a service using expanded entity set method. There were two entities in the entity model connected by association. I did not keep any referential constraint between them, but it worked.

Could anybody kindly explain me when is a referential constraint mandatory in SAP netweaver gateway?

答: I had a discussion about this with one of my coworkers and i looked into the OData v2 specification and didnt find anything it being mandatory. Runtime wise (expanded entity in your example) it doesnt change anything from what i have seen so far. I just use it if i really have a superset of key properties in the depended entity, because this constraint gets written into the $metadata xml file. I had a discussion about with my coworker because they demanded a constraint on some association because else it wasnt able for them to mock data via a JS(or UI5?) mockserver. So i looked in the specification to see if i did something wrong but didnt find anything about it. so i think its optional, as generation via SEGW also doesnt seem to care wether its there or not. My advise would be to use it if it makes sense, else dont</p>

ContentLicense: CC BY-SA 4.0


问:
Array is giving an undefined in jquery
I want to get the id of each button and keep it in array. but the array looks undefined. why

Jquery CODE :

```<code>var arr = new Array();

$(".button").each(function () {
     arr.push($(this).attr('id'));
})

console.log(arr);//undefined

 }
</code>```

HTML CODE :

```<code>    <div id="1" class="button" data-bind="dxButton: { }"></div>
    <div id="2" class="button" data-bind="dxButton: { }"></div>
    <div id="3" class="button" data-bind="dxButton: { }"></div>
    <div id="4" class="button" data-bind="dxButton: { }"></div>
</code>```

答:
Using the map() function is mor efficient in this case.

NOTE : Your code should work try just to insert it inside theready function to ensure that the button's in your DOM are fully loaded :

```<code>$(function(){
   //Your logic here
});
</code>```

Hopet his helps.

$(function() {
  var arr = $(".button").map(function() {
    return this.id;
  }).get();

  console.log(arr);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="1" class="button" data-bind="dxButton: { }"></div>
<div id="2" class="button" data-bind="dxButton: { }"></div>
<div id="3" class="button" data-bind="dxButton: { }"></div>
<div id="4" class="button" data-bind="dxButton: { }"></div></code>```

Title: Array is giving an undefined in jquery

Body:
I want to get the id of each button and keep it in array. but the array looks undefined. why

Jquery CODE :

var arr = new Array();

$(".button").each(function () {
     arr.push($(this).attr('id'));
})

console.log(arr);//undefined

 }

HTML CODE :

Body:
Using the map() function is mor efficient in this case.

NOTE : Your code should work try just to insert it inside theready function to ensure that the button's in your DOM are fully loaded :

$(function(){
   //Your logic here
});

Hopet his helps.

$(function() {
  var arr = $(".button").map(function() {
    return this.id;
  }).get();

  console.log(arr);
})

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

<div id="1" class="button" data-bind="dxButton: { }"></div>
<div id="2" class="button" data-bind="dxButton: { }"></div>
<div id="3" class="button" data-bind="dxButton: { }"></div>
<div id="4" class="button" data-bind="dxButton: { }"></div>


问:
How do I pass variables through different classes or root widgets in kivy?
I'm creating an app where I determine a variable in one class and need to transfer it to a different class. I wanted to use id but that doesn't work for different root widgets. Then I found out about factory and it seemed promising and it seems to work somewhat but when I update the variable in the PopupColor class it doesn't update in my DrawScreen class.

Here's the code.

py:

```<code>class PopupColor(Popup):
    color = [0,0,0,1]
    def on_press_dismiss(self, colorpicker, *args):
        print(self.color)
        self.dismiss()
        self.color = colorpicker.color
        print(self.color)

class DrawScreen(Screen):
    def testy(self):
        self.color = Factory.PopupColor().color
        print(self.color)
</code>```

kv:

```<code><PopupColor>:
    title: 'Pick a Color'
    size_hint: 0.75, 0.75
    id: popupcolor

    BoxLayout:
        padding: 5
        spacing: 5
        orientation: 'vertical'

        ColorPicker:
            id: colorpicker
            size_hint: 1.0, 1.0

        Button:
            text: 'Choose Color'
            size_hint: 1, 0.2
            on_release: popupcolor.on_press_dismiss(colorpicker)

<DrawScreen>:

    Button:
        size_hint: 0.2,0.1
        font_size: 30
        text: "Back"
        on_release: Factory.PopupColor().open()

    ColorButton:
        text: "Test"
        pos_hint:{"center_x":0.5, "y":0.1}
        on_release: root.testy()
</code>```

So how can I do this and how far off am I?

EDIT: So it seems like the error isn't really the factory part but more so that the variable in PopupColor doesn't change permanently.

答:
The problem is that when you change the attribute, you use self, which refers to this instance.

But since you create a new PopupColor object, each time you open the popup, you need to treat color as a shared variable.

So you could change color like this:

```<code>PopupColor.color = colorpicker.color
</code>```

That way you treat the attribute color as shared with all PopupColor objects.

Body:
I'm creating an app where I determine a variable in one class and need to transfer it to a different class. I wanted to use id but that doesn't work for different root widgets. Then I found out about factory and it seemed promising and it seems to work somewhat but when I update the variable in the PopupColor class it doesn't update in my DrawScreen class.

Here's the code.

py:

class PopupColor(Popup):
    color = [0,0,0,1]
    def on_press_dismiss(self, colorpicker, *args):
        print(self.color)
        self.dismiss()
        self.color = colorpicker.color
        print(self.color)

class DrawScreen(Screen):
    def testy(self):
        self.color = Factory.PopupColor().color
        print(self.color)

kv:

<PopupColor>:
    title: 'Pick a Color'
    size_hint: 0.75, 0.75
    id: popupcolor

    BoxLayout:
        padding: 5
        spacing: 5
        orientation: 'vertical'

        ColorPicker:
            id: colorpicker
            size_hint: 1.0, 1.0

        Button:
            text: 'Choose Color'
            size_hint: 1, 0.2
            on_release: popupcolor.on_press_dismiss(colorpicker)

<DrawScreen>:

    Button:
        size_hint: 0.2,0.1
        font_size: 30
        text: "Back"
        on_release: Factory.PopupColor().open()

    ColorButton:
        text: "Test"
        pos_hint:{"center_x":0.5, "y":0.1}
        on_release: root.testy()

So how can I do this and how far off am I?

EDIT: So it seems like the error isn't really the factory part but more so that the variable in PopupColor doesn't change permanently.

Body:
The problem is that when you change the attribute, you use self, which refers to this instance.

But since you create a new PopupColor object, each time you open the popup, you need to treat color as a shared variable.

So you could change color like this:

PopupColor.color = colorpicker.color

That way you treat the attribute color as shared with all PopupColor objects.


问:
adb shell input text with space
How to send text with spaces like "some text" using adb shell input text ?

Found following solution

adb shell input text "some%stext" is working fine. But any easy way to replace space with %s?

Example:

```<code>$ adb shell input text "some text"
Error: Invalid arguments for command: text
Usage: input [<source>] <command> [<arg>...]

The sources are:
      keyboard
      mouse
      joystick
      touchnavigation
      touchpad
      trackball
      dpad
      stylus
      gamepad
      touchscreen

The commands and default sources are:
      text <string> (Default: touchscreen)
      keyevent [--longpress] <key code number or name> ... (Default: keyboard)
      tap <x> <y> (Default: touchscreen)
      swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll <dx> <dy> (Default: trackball)
</code>```

答:
You can send your text like:

```<code>Text = "some text with spaces"
</code>```

Replace blanks with %s

```<code>adb shell input text some%stext%swith%sspaces
</code>```

Title: adb shell input text with space

Body:
How to send text with spaces like "some text" using adb shell input text ?

Found following solution

adb shell input text "some%stext" is working fine. But any easy way to replace space with %s?

Example:

$ adb shell input text "some text"
Error: Invalid arguments for command: text
Usage: input [<source>] <command> [<arg>...]

The sources are:
      keyboard
      mouse
      joystick
      touchnavigation
      touchpad
      trackball
      dpad
      stylus
      gamepad
      touchscreen

The commands and default sources are:
      text <string> (Default: touchscreen)
      keyevent [--longpress] <key code number or name> ... (Default: keyboard)
      tap <x> <y> (Default: touchscreen)
      swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll <dx> <dy> (Default: trackball)

Body:
You can send your text like:

Text = "some text with spaces"

Replace blanks with %s

adb shell input text some%stext%swith%sspaces


问:
Using gcov to test a c++ program
I am using gcov for the first time to analyze my program (C++)
The program consists of three classes and I have built the project using Code::Blocks.
When I am invoking the program using the following command:

C:\Users\XXX\Documents\Test\TreeObjModel\src>gcc
  -fprofile-arcs -ftest-coverage Tree.cpp

I receive the following error:

Tree.cpp:1:18: fatal error: Tree.h: No such file or directory
  compilation terminated

While the cpp files are in the directory "C:\Users\XXX\Documents\Test\TreeObjModel\src\" , the header files are in directory "C:\Users\XXX\Documents\Test\TreeObjModel\include\"

Do we need to have both the code and header files in the same directory?

Thanks in advance.

答:
You have at least two options to instruct the compiler where to find the header files (includes).

-Ipath_to_includes as parameter for gcc compiler. E.g. -I../include

When including in your program, specify the directory. E.g. #include "../include/foo.h"

My strategy would be to just compile my project successfully and only then try to use some other stuff, like flags for code coverage. I say this because your error does not have anything to do with gcov, and trying to instrument your program to get code coverage before your program even compiles, makes things more complicated for you. One step at a time ;)

Title: Using gcov to test a c++ program


问:
About Uploading photo to AWS
I am developing a software on AWS DynamoDB. I got some UIImages. Where should upload them? S3?

I try to use S3, but it says it needs my photo to be a bundle resource. But what I got is an UIImage.

How can I convert UIImagge to NSBUNDLE?

答:
You need to setup and execute an upload request:

```<code>// Configure the authentication
import AWSS3

// configure S3
let S3BucketName = "<#bucket#>"

// configure authentication with Cognito
let CognitoPoolID = "<#cognito-pool-id#>"
let Region = AWSRegionType.<#region#>
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region,
    identityPoolId:CognitoPoolID)
let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

// Point to the image you want to upload
let ext = "png"
let imageURL = NSBundle.mainBundle().URLForResource("<#image-name#>", withExtension: ext)!

// Setup the upload request
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = imageURL
uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/" + ext

// Push the image
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
    if let error = task.error {
        print("Upload failed (\(error))")
    }
    if let exception = task.exception {
        print("Upload failed (\(exception))")
    }
    if task.result != nil {
        let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
        print("Uploaded to:\n\(s3URL)")
    }
    else {
        print("Unexpected empty result.")
    }
    return nil
}
</code>```

You can now create a UIImage instance by doing:
let image = UIImage(data: NSData(contentsOfURL: s3URL)!)

Title: About Uploading photo to AWS

Body:
You need to setup and execute an upload request:

// Configure the authentication
import AWSS3

// configure S3
let S3BucketName = "<#bucket#>"

// configure authentication with Cognito
let CognitoPoolID = "<#cognito-pool-id#>"
let Region = AWSRegionType.<#region#>
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region,
    identityPoolId:CognitoPoolID)
let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

// Point to the image you want to upload
let ext = "png"
let imageURL = NSBundle.mainBundle().URLForResource("<#image-name#>", withExtension: ext)!

// Setup the upload request
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = imageURL
uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/" + ext

// Push the image
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
    if let error = task.error {
        print("Upload failed (\(error))")
    }
    if let exception = task.exception {
        print("Upload failed (\(exception))")
    }
    if task.result != nil {
        let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
        print("Uploaded to:\n\(s3URL)")
    }
    else {
        print("Unexpected empty result.")
    }
    return nil
}

You can now create a UIImage instance by doing:
let image = UIImage(data: NSData(contentsOfURL: s3URL)!)


问:
Tarantool - creating primary index
I am following the tarantool documentation but I am getting an error while creating the index.

I would like to understand why this is failing, as I am following exactly the tutorial.

```<code>$ tarantool
tarantool: version 1.6.7-591-g7d4dbbb
type 'help' for interactive help
tarantool> box.cfg{listen = 3301}
2017-12-06 20:57:18.684 [15168] main/101/interactive C> version 1.6.7-591-g7d4dbbb
2017-12-06 20:57:18.684 [15168] main/101/interactive C> log level 5
2017-12-06 20:57:18.684 [15168] main/101/interactive I> mapping 1073741824 bytes for tuple arena...
2017-12-06 20:57:18.705 [15168] main/101/interactive I> initializing an empty data directory
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> creating `./00000000000000000000.snap.inprogress'
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> saving snapshot `./00000000000000000000.snap.inprogress'
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> done
2017-12-06 20:57:18.713 [15168] iproto I> binary: started
2017-12-06 20:57:18.713 [15168] iproto I> binary: bound to 0.0.0.0:3301
2017-12-06 20:57:18.713 [15168] main/101/interactive I> ready to accept requests
---
...

tarantool> s = box.schema.space.create('tester')
2017-12-06 20:57:32.803 [15168] wal/101/main I> creating `./00000000000000000000.xlog.inprogress'
---
...

tarantool> s:create_index('primary', {
         > type = 'hash',
         > parts = {1, 'unsigned'}
         > })
---
- error: 'Can''t create or modify index ''primary'' in space ''tester'': unknown field
    type'
...
</code>```

答:
You are using Tarantool 1.6 so I believe you should have

```<code>parts = {1, 'NUM'}
</code>```

in the tutorial example. The code you show ('unsigned') is for 1.7, so one option is to upgrade your version of Tarantool. Also in the docs, you can change between Tarantool 1.6, 1.7 and 1.8 in the upper-right-hand corner.

Title: Tarantool - creating primary index

Body:
I am following the tarantool documentation but I am getting an error while creating the index.

I would like to understand why this is failing, as I am following exactly the tutorial.

$ tarantool
tarantool: version 1.6.7-591-g7d4dbbb
type 'help' for interactive help
tarantool> box.cfg{listen = 3301}
2017-12-06 20:57:18.684 [15168] main/101/interactive C> version 1.6.7-591-g7d4dbbb
2017-12-06 20:57:18.684 [15168] main/101/interactive C> log level 5
2017-12-06 20:57:18.684 [15168] main/101/interactive I> mapping 1073741824 bytes for tuple arena...
2017-12-06 20:57:18.705 [15168] main/101/interactive I> initializing an empty data directory
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> creating `./00000000000000000000.snap.inprogress'
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> saving snapshot `./00000000000000000000.snap.inprogress'
2017-12-06 20:57:18.710 [15168] snapshot/101/main I> done
2017-12-06 20:57:18.713 [15168] iproto I> binary: started
2017-12-06 20:57:18.713 [15168] iproto I> binary: bound to 0.0.0.0:3301
2017-12-06 20:57:18.713 [15168] main/101/interactive I> ready to accept requests
---
...

tarantool> s = box.schema.space.create('tester')
2017-12-06 20:57:32.803 [15168] wal/101/main I> creating `./00000000000000000000.xlog.inprogress'
---
...

tarantool> s:create_index('primary', {
         > type = 'hash',
         > parts = {1, 'unsigned'}
         > })
---
- error: 'Can''t create or modify index ''primary'' in space ''tester'': unknown field
    type'
...

Body:
You are using Tarantool 1.6 so I believe you should have

parts = {1, 'NUM'}

in the tutorial example. The code you show ('unsigned') is for 1.7, so one option is to upgrade your version of Tarantool. Also in the docs, you can change between Tarantool 1.6, 1.7 and 1.8 in the upper-right-hand corner.


问:
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

What is meant by this sentence?

答:
In C strings stored as arrays of char's and they are null-terminated, which means they have an extra 0 appended at the end, which marks the end of the string and could be used later to figure out the string's length.  So the string "hello" looks like this in memory:

```<code>char hello[] = {'h', 'e', 'l', 'l', 'o', 0};
</code>```

Normally, when you copy a string, the null character should be copied as well.  So the memory needed for the string buffer is its length + 1 (e.g. (strlen(hello) + 1) * sizeof(char)).

Function strncpy allows you to copy only as many characters as it's possible to fit in the provided buffer.  In case the buffer you provided is not big enough to hold that extra null, it won't be added.  Or if the string is cut, it won't be null-terminated.

```<code>char hello[] = "hello"; // 5 characters, 6 bytes long
char hel[3];
strncpy(hel, hello, 3); // hel is {'h', 'e', 'l'}
</code>```

You should be always careful after calling strncpy, since the result might not be a valid C string.  If the string is not null-terminated it's impossible to know its length and most of the string manipulation functions would fail or would do something unexpected.

Title: strncpy documentation question

Body:
In C strings stored as arrays of char's and they are null-terminated, which means they have an extra 0 appended at the end, which marks the end of the string and could be used later to figure out the string's length.  So the string "hello" looks like this in memory:

char hello[] = {'h', 'e', 'l', 'l', 'o', 0};

Normally, when you copy a string, the null character should be copied as well.  So the memory needed for the string buffer is its length + 1 (e.g. (strlen(hello) + 1) * sizeof(char)).

Function strncpy allows you to copy only as many characters as it's possible to fit in the provided buffer.  In case the buffer you provided is not big enough to hold that extra null, it won't be added.  Or if the string is cut, it won't be null-terminated.

char hello[] = "hello"; // 5 characters, 6 bytes long
char hel[3];
strncpy(hel, hello, 3); // hel is {'h', 'e', 'l'}

You should be always careful after calling strncpy, since the result might not be a valid C string.  If the string is not null-terminated it's impossible to know its length and most of the string manipulation functions would fail or would do something unexpected.


问:
Problems with including QWebView in QT application
I am using qt creator. I wanted to show a webpage inside QWebView, but my projet doesn't compile. When i want to include QWebView, editor says "no such file or directory".
My code:

```<code>#include <QApplication>
#include <QUrl>
#include <QWebView>

int main(int argc, char *argv[])
 {
QApplication a(argc, argv);

QWebView view;
view.showMaximized();

return a.exec();
</code>```

}

答: Did you add in your Project_name.pro file in Qt Creator line like this: QT += core gui webkit ?

Body:
I am using qt creator. I wanted to show a webpage inside QWebView, but my projet doesn't compile. When i want to include QWebView, editor says "no such file or directory".
My code:

#include <QApplication>
#include <QUrl>
#include <QWebView>

int main(int argc, char *argv[])
 {
QApplication a(argc, argv);

QWebView view;
view.showMaximized();

return a.exec();

}


问:
How to close active datareader c#
I am trying to select values out of a mySQL database. All good and well but the first time i ran the code I forgot to close the datareader. Now every time I run my updated code, it errors, stating there is already an active datareader for that connection that must be closed first.   I have tried ending the SQL instance as well as restarting my PC, but the error remains. How do I close this datareader

Below is the updated code

```<code>public static int getProductIDbyName(string productName)
    {
        try
        {
            if (connection.State.ToString()!="Open")
            {
                connection.Open();
            }
            string query = "SELECT * FROM  `tblproduct` WHERE  `ProductName` =  '"+productName+"'";
            if (connection.State.ToString() == "Open")
            {
                int result = 0;
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {
                    using (var dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            result = Convert.ToInt16(dataReader["ID"].ToString());
                        }

                        dataReader.Close();
                    }
                }
                connection.Close();
                MySqlConnection.ClearAllPools();
                return result;
            }
        }
        catch (Exception)
        {
            throw;
        }
        return 0;
    }
</code>```

答:
When you use ExecuteReader on a DbCommand, the reader that you get is disposable - i.e. it implements IDisposable. You should consume it with a using block. Then: when your code leaves the block, everything will happen automatically:

```<code>using(var reader = cmd.ExecuteReader())
{
    // ... consume the data
}
</code>```

Alternatively, use a tool like "Dapper" (free, etc) that will do this correctly for you, and make it easier to write ADO.NET.

Title: How to close active datareader c#

Body:
I am trying to select values out of a mySQL database. All good and well but the first time i ran the code I forgot to close the datareader. Now every time I run my updated code, it errors, stating there is already an active datareader for that connection that must be closed first.   I have tried ending the SQL instance as well as restarting my PC, but the error remains. How do I close this datareader

Below is the updated code

public static int getProductIDbyName(string productName)
    {
        try
        {
            if (connection.State.ToString()!="Open")
            {
                connection.Open();
            }
            string query = "SELECT * FROM  `tblproduct` WHERE  `ProductName` =  '"+productName+"'";
            if (connection.State.ToString() == "Open")
            {
                int result = 0;
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {
                    using (var dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            result = Convert.ToInt16(dataReader["ID"].ToString());
                        }

                        dataReader.Close();
                    }
                }
                connection.Close();
                MySqlConnection.ClearAllPools();
                return result;
            }
        }
        catch (Exception)
        {
            throw;
        }
        return 0;
    }

Body:
When you use ExecuteReader on a DbCommand, the reader that you get is disposable - i.e. it implements IDisposable. You should consume it with a using block. Then: when your code leaves the block, everything will happen automatically:

using(var reader = cmd.ExecuteReader())
{
    // ... consume the data
}

Alternatively, use a tool like "Dapper" (free, etc) that will do this correctly for you, and make it easier to write ADO.NET.


问:
Manual completion with Ctrl-N in Deoplete
I installed deoplete and it works for me, however by default it opens a pop-up window whenever you type something. This is not desirable. I want pop-up to only show when I hit Ctrl+N. So I disable autocompletion:

```<code>let b:deoplete_disable_auto_complete = 1
</code>```

But that makes Ctrl+N behave as it did before deoplete, that is use all words in the buffer as completion source.

I also tried adding the code from the docs, to no avail:

```<code>            inoremap <silent><expr> <TAB>
            \ pumvisible() ? "\<C-n>" :
            \ <SID>check_back_space() ? "\<TAB>" :
            \ deoplete#mappings#manual_complete()
            function! s:check_back_space() abort "{{{
            let col = col('.') - 1
            return !col || getline('.')[col - 1]  =~ '\s'
            endfunction"}}}
</code>```

It remaps the Tab key, but not Ctrl+N. Is it possible to show Deoplete manual completion by pressing Ctrl+N?

答:
I admit I'm slightly puzzled as to the exact behaviour you're looking for, but it seems like you just need to bind Ctrl+N? If so:

```<code>let g:deoplete#enable_at_startup = 1
let g:deoplete#disable_auto_complete = 1
inoremap <expr> <C-n>  deoplete#manual_complete()
</code>```

works ok.

Body:
I installed deoplete and it works for me, however by default it opens a pop-up window whenever you type something. This is not desirable. I want pop-up to only show when I hit Ctrl+N. So I disable autocompletion:

let b:deoplete_disable_auto_complete = 1

But that makes Ctrl+N behave as it did before deoplete, that is use all words in the buffer as completion source.

I also tried adding the code from the docs, to no avail:

            inoremap <silent><expr> <TAB>
            \ pumvisible() ? "\<C-n>" :
            \ <SID>check_back_space() ? "\<TAB>" :
            \ deoplete#mappings#manual_complete()
            function! s:check_back_space() abort "{{{
            let col = col('.') - 1
            return !col || getline('.')[col - 1]  =~ '\s'
            endfunction"}}}

It remaps the Tab key, but not Ctrl+N. Is it possible to show Deoplete manual completion by pressing Ctrl+N?

Body:
I admit I'm slightly puzzled as to the exact behaviour you're looking for, but it seems like you just need to bind Ctrl+N? If so:

let g:deoplete#enable_at_startup = 1
let g:deoplete#disable_auto_complete = 1
inoremap <expr> <C-n>  deoplete#manual_complete()

works ok.


问:
Graph Theory: number of connected triples
In order to find the Global Clustering Coefficient I need to find the number of connected triples. About this graph:

these are the triples that I found:

7-6-5

5-3-7

5-3-1

4-3-7

4-3-1

4-5-6

3-7-6

3-5-6

2-3-4

2-1-7

2-3-5

1-7-6

total: 12 triples.

Moreover, there are 3 triangles, and 1 triangle is equal to 3 triples. So in total there are 12 + 3*3 = 21 triples. Is that correct? And is it possible to find a rule or a method to find all the connected triples in a graph without doing it manually?

答: summation of k*(k-1)/2, where k is the degree of all nodes.</p>


问:
Powershell - Output individual members of an array of objects in a pipeline
I'm not sure if the title is correct. And I know this is easily answered and is probably all over the internet. But, I need your help please.

If I run a powershell command that returns multiple objects, and each object has it's own members, with one of those members being another list of multiple objects, what is the most efficient way to output this cleanly to the screen?

For instance, see the following command for querying MFA authentication methods a user has chosen in Office 365:

```<code>Get-MsolUser -All | where {$_.StrongAuthenticationMethods -ne $null} | Select-Object -Property UserPrincipalName, StrongAuthenticationMethods
</code>```

The output is:

```<code>UserPrincipalName                  StrongAuthenticationMethods
-----------------                  ---------------------------
user1@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...
user2@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...
user3@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...
</code>```

I want to list the UserPrincipalName followed by the value of the MethodType member of each StrongAuthenticationMethods object in a single line of code.

Take it easy on me, I know this has an obvious answer.

答:
One way to do this is to unroll the inner collection and output one for each object in the outer collection; example (not tested):</p>

```<code>Get-MsolUser -All | Where-Object { $_.StrongAuthenticationMethods } | ForEach-Object {
  $upn = $_.UserPrincipalName
  $_.StrongAuthenticationMethods | ForEach-Object {
    [PSCustomObject] @{
      "UserPrincpalName"            = $upn
      "StrongAuthenticationMethods" = $_
    }
  }
</code>```

Body:
I'm not sure if the title is correct. And I know this is easily answered and is probably all over the internet. But, I need your help please.

If I run a powershell command that returns multiple objects, and each object has it's own members, with one of those members being another list of multiple objects, what is the most efficient way to output this cleanly to the screen?

For instance, see the following command for querying MFA authentication methods a user has chosen in Office 365:

Get-MsolUser -All | where {$_.StrongAuthenticationMethods -ne $null} | Select-Object -Property UserPrincipalName, StrongAuthenticationMethods

The output is:

UserPrincipalName                  StrongAuthenticationMethods
-----------------                  ---------------------------
user1@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...
user2@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...
user3@domain.com       {Microsoft.Online.Administration.StrongAuthenticationMethod, Microsoft.Online.Adm...

I want to list the UserPrincipalName followed by the value of the MethodType member of each StrongAuthenticationMethods object in a single line of code.

Take it easy on me, I know this has an obvious answer.

Body:
One way to do this is to unroll the inner collection and output one for each object in the outer collection; example (not tested):

Get-MsolUser -All | Where-Object { $_.StrongAuthenticationMethods } | ForEach-Object {
  $upn = $_.UserPrincipalName
  $_.StrongAuthenticationMethods | ForEach-Object {
    [PSCustomObject] @{
      "UserPrincpalName"            = $upn
      "StrongAuthenticationMethods" = $_
    }
  }


答:
The syntax in your example is a bit off. You're missing a ; and have an extra }.

Cleaning it up, we have:

```<code>var arr = new Array();
$(".button").each(function () {
  arr.push($(this).attr('id'));
});
console.log(arr);
</code>```

Refer to working example here: https://jsfiddle.net/8Lt2m4u2/

As others have suggested, this may be a timing issue, however the console.log(arr); should not return undefined at any point, as you define it and initialize it to an empty array. Even if your buttons do not exist in the DOM at the time of the console.log, it should at least print an empty array.

One quirk to be aware of, is that console.log does not necessarily represent the value you expect. Refer to this SO question/answer for details. A workaround would be doing console.log(JSON.stringify(arr));, which will not matter if the object changes before you view it in the developer console. It will print what the value was at the time of executing the console.log.

Title: Array is giving an undefined in jquery

Body:
I want to get the id of each button and keep it in array. but the array looks undefined. why

Jquery CODE :

var arr = new Array();

$(".button").each(function () {
     arr.push($(this).attr('id'));
})

console.log(arr);//undefined

 }

HTML CODE :

Body:
The syntax in your example is a bit off. You're missing a ; and have an extra }.

Cleaning it up, we have:

var arr = new Array();
$(".button").each(function () {
  arr.push($(this).attr('id'));
});
console.log(arr);

Refer to working example here: https://jsfiddle.net/8Lt2m4u2/

As others have suggested, this may be a timing issue, however the console.log(arr); should not return undefined at any point, as you define it and initialize it to an empty array. Even if your buttons do not exist in the DOM at the time of the console.log, it should at least print an empty array.

One quirk to be aware of, is that console.log does not necessarily represent the value you expect. Refer to this SO question/answer for details. A workaround would be doing console.log(JSON.stringify(arr));, which will not matter if the object changes before you view it in the developer console. It will print what the value was at the time of executing the console.log.


问:
In a Batch Script execute command to start a web-server and then Launch Default Browser with URL
My own batch script is Myscript.bat which is in folder D:. There is a batch file named server.bat which is located at D:\wlp\bin for starting (IBM liberty web) server. And I use the command D:\wlp\bin>server start defaultServer. I want to start the server by clicking Myscript.bat and then want to display a message "Loading Completed" and the automatically a default browser with URL http://localhost:8080/Demo. But after starting the server I am not able to display message  or launching browser. Please suggest what needs to change in my code.(I am not allowed to look into code of server.bat, so it should not be touched)

Myscript.bat contains-

```<code>@echo Starting script

@echo Loading Liberty Profile. This may take some time ...

@cmd /k "%~dp0\wlp\bin\server.bat" start

echo Loading completed

start http://localhost:%NewPort%/HatsDemo

@pause
</code>```

Command Prompt Screenshot:

```<code>D:\wlp\bin>server start defaultServer

Starting server defaultServer.

Server defaultServer started.

D:\wlp\bin>
</code>```

答:
You need to call batchfiles.

Starting a Program

See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.

If a full path isn't given then Windows looks in

The directory from which the application loaded.

The current directory for the parent process.

Windows NT/2000/XP: The 32-bit Windows system directory. Use the
GetSystemDirectory function to get the path of this directory. The
name of this directory is System32.

Windows NT/2000/XP: The 16-bit Windows system directory. There is no
function that obtains the path of this directory, but it is
searched. The name of this directory is System.

The Windows directory. Use the GetWindowsDirectory function to get
the path of this directory.

The directories that are listed in the PATH environment variable.

Specify a program name

This is the standard way to start a program.

```<code>c:\windows\notepad.exe
</code>```

In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

Use Start command

Start starts programs in non standard ways.

```<code>start "" c:\windows\notepad.exe
</code>```

Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try

```<code>start shell:cache
</code>```

Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.

Use Call command

Call is used to start batch files and wait for them to exit and continue the current batch file.

Other Filenames

Typing a non program filename is the same as double clicking the file.

Body:
My own batch script is Myscript.bat which is in folder D:. There is a batch file named server.bat which is located at D:\wlp\bin for starting (IBM liberty web) server. And I use the command D:\wlp\bin>server start defaultServer. I want to start the server by clicking Myscript.bat and then want to display a message "Loading Completed" and the automatically a default browser with URL http://localhost:8080/Demo. But after starting the server I am not able to display message  or launching browser. Please suggest what needs to change in my code.(I am not allowed to look into code of server.bat, so it should not be touched)

Myscript.bat contains-

@echo Starting script

@echo Loading Liberty Profile. This may take some time ...

@cmd /k "%~dp0\wlp\bin\server.bat" start

echo Loading completed

start http://localhost:%NewPort%/HatsDemo

@pause

Command Prompt Screenshot:

D:\wlp\bin>server start defaultServer

Starting server defaultServer.

Server defaultServer started.

D:\wlp\bin>

Body:
You need to call batchfiles.

Starting a Program

See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.

If a full path isn't given then Windows looks in

The directory from which the application loaded.

The current directory for the parent process.

Windows NT/2000/XP: The 32-bit Windows system directory. Use the
GetSystemDirectory function to get the path of this directory. The
name of this directory is System32.

Windows NT/2000/XP: The 16-bit Windows system directory. There is no
function that obtains the path of this directory, but it is
searched. The name of this directory is System.

The Windows directory. Use the GetWindowsDirectory function to get
the path of this directory.

The directories that are listed in the PATH environment variable.

Specify a program name

This is the standard way to start a program.

c:\windows\notepad.exe

In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

Use Start command

Start starts programs in non standard ways.

start "" c:\windows\notepad.exe

Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try

start shell:cache

Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.

Use Call command

Call is used to start batch files and wait for them to exit and continue the current batch file.

Other Filenames

Typing a non program filename is the same as double clicking the file.


问:
Counting number of vowels in a string with JavaScript
I'm using basic JavaScript to count the number of vowels in a string.  The below code works but I would like to have it cleaned up a bit.  Would using .includes() help at all considering it is a string?  I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement.  Also, is it needed to convert the input into a string?

```<code>function getVowels(str) {
  var vowelsCount = 0;

  //turn the input into a string
  var string = str.toString();

  //loop through the string
  for (var i = 0; i <= string.length - 1; i++) {

  //if a vowel, add to vowel count
    if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
      vowelsCount += 1;
    }
  }
  return vowelsCount;
}
</code>```

答:
This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:

```<code>function vowelCount(str) {
  return str.replace(/[^aeiou]/gi, "").length;
};
</code>```

or if you prefer ES6

```<code>const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
</code>```

Body:
I'm using basic JavaScript to count the number of vowels in a string.  The below code works but I would like to have it cleaned up a bit.  Would using .includes() help at all considering it is a string?  I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement.  Also, is it needed to convert the input into a string?

function getVowels(str) {
  var vowelsCount = 0;

  //turn the input into a string
  var string = str.toString();

  //loop through the string
  for (var i = 0; i <= string.length - 1; i++) {

  //if a vowel, add to vowel count
    if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
      vowelsCount += 1;
    }
  }
  return vowelsCount;
}

Body:
This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:

function vowelCount(str) {
  return str.replace(/[^aeiou]/gi, "").length;
};

or if you prefer ES6

const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )


问:
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.

答:
First, about sorting within each group. Collectors.groupingBy has a second variant which allows you to specify a collector which is used to generate the groups. The collector you specify can be one which collects the items in a sorted way (e.g. a TreeSet), and as a finishing operation transforms it to a sorted list. Such a collector can be created with Collectors.collectingAndThen().

For example, with Integers I tried:

```<code>List<Integer> list = Arrays.asList(9, 2, 43, 6, 5, 3, 87, 56, 87, 67, 77, 22, 23, 1);
System.out.println(
    list.stream().collect(Collectors.groupingBy(
        i -> i % 3,                                         // classifier
        Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>()), // intermediate collector
            set -> new ArrayList<>(set)))));                // finishing operation
</code>```

Output:

```<code>{0=[3, 6, 9, 87], 1=[1, 22, 43, 67], 2=[2, 5, 23, 56, 77]}
</code>```

I'm sure you manage to translate this to your case. You might need to create a TreeSet with a custom comparator so that the students in each group are ordered the way you want, or, if students are sorted in the same way always, make Student implement Comparable.

Second about sorting the groups. Collectors.groupingBy by default creates a HashMap, which does not have a specified order of the keys (above, the keys are ordered correctly by chance). So, to also order the keys, you need to use the Collectors.groupingBy variant which also lets you create the result map, which luckily also exists:

```<code>System.out.println(
    list.stream().collect(Collectors.groupingBy(
        i -> i % 3,                                         // classifier
        new TreeMap<>((a, b) -> b.compareTo(a)),            // map creator
        Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>()), // intermediate collector
            set -> new ArrayList<>(set)))));                // finishing operation
</code>```

I specified a custom comparator for the map to show that the ordering is indeed different. The result is:

```<code>{2=[2, 5, 23, 56, 77], 1=[1, 22, 43, 67], 0=[3, 6, 9, 87]}
</code>```

Now, whether this is more readable and maintainable than a good-old pre-Java 8 solution is a matter of taste...

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:
First, about sorting within each group. Collectors.groupingBy has a second variant which allows you to specify a collector which is used to generate the groups. The collector you specify can be one which collects the items in a sorted way (e.g. a TreeSet), and as a finishing operation transforms it to a sorted list. Such a collector can be created with Collectors.collectingAndThen().

For example, with Integers I tried:

List<Integer> list = Arrays.asList(9, 2, 43, 6, 5, 3, 87, 56, 87, 67, 77, 22, 23, 1);
System.out.println(
    list.stream().collect(Collectors.groupingBy(
        i -> i % 3,                                         // classifier
        Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>()), // intermediate collector
            set -> new ArrayList<>(set)))));                // finishing operation

Output:

{0=[3, 6, 9, 87], 1=[1, 22, 43, 67], 2=[2, 5, 23, 56, 77]}

I'm sure you manage to translate this to your case. You might need to create a TreeSet with a custom comparator so that the students in each group are ordered the way you want, or, if students are sorted in the same way always, make Student implement Comparable.

Second about sorting the groups. Collectors.groupingBy by default creates a HashMap, which does not have a specified order of the keys (above, the keys are ordered correctly by chance). So, to also order the keys, you need to use the Collectors.groupingBy variant which also lets you create the result map, which luckily also exists:

System.out.println(
    list.stream().collect(Collectors.groupingBy(
        i -> i % 3,                                         // classifier
        new TreeMap<>((a, b) -> b.compareTo(a)),            // map creator
        Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>()), // intermediate collector
            set -> new ArrayList<>(set)))));                // finishing operation

I specified a custom comparator for the map to show that the ordering is indeed different. The result is:

{2=[2, 5, 23, 56, 77], 1=[1, 22, 43, 67], 0=[3, 6, 9, 87]}

Now, whether this is more readable and maintainable than a good-old pre-Java 8 solution is a matter of taste...


问:
Add more service-worker functionality with create-react-app
So create-react-app includes service worker functionality by default, which is lovely - all my static assets get cached for offline use out of the box. Cool, but now I want to take things a bit further and use indexedDB to cache some dynamic content.

Problem is, there's no service-worker.js file to modify. It gets generated during the build process.

Is there a way to add additional logic without ejecting create-react-app or redoing all the nice static caching stuff?

答:
As you've observed, create-react-app's config is locked down, and the service worker logic is entirely defined in the config.

If you'd rather not eject but you want some customization, another option is to modify the create-react-app build process to explicitly call the sw-precache CLI after the normal build has completed, overwriting the service-worker.js that create-react-app generates by default. Because this involves modifying your local package.json, it doesn't require ejecting first.

There's some info on this approach here, and the general idea is modifying your npm scripts to look something like:

```<code>"build": "react-scripts build && sw-precache --config=sw-precache-config.js"
</code>```

With sw-precache-config.js configured based on your needs, but including

```<code>swFilePath: './build/service-worker.js'
</code>```

to ensure that the built-in service-worker.js is overwritten.

Body:
As you've observed, create-react-app's config is locked down, and the service worker logic is entirely defined in the config.

If you'd rather not eject but you want some customization, another option is to modify the create-react-app build process to explicitly call the sw-precache CLI after the normal build has completed, overwriting the service-worker.js that create-react-app generates by default. Because this involves modifying your local package.json, it doesn't require ejecting first.

There's some info on this approach here, and the general idea is modifying your npm scripts to look something like:

"build": "react-scripts build && sw-precache --config=sw-precache-config.js"

With sw-precache-config.js configured based on your needs, but including

swFilePath: './build/service-worker.js'

to ensure that the built-in service-worker.js is overwritten.


问:
Python Function Returning List Objects Out of Order
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

```<code>test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)
</code>```

I would have expected the result to be:

```<code>[4, 8, 12]
4
8
12
</code>```

However, the actual result is as follows:

```<code>[8, 4, 12]
8
4
12
</code>```

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South

答: After first iteration you list look like [4,4,6] so k.index(4) return 0 index and multiple it by 2. So final result is [8,4,12].</p>

Body:
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)

I would have expected the result to be:

[4, 8, 12]
4
8
12

However, the actual result is as follows:

[8, 4, 12]
8
4
12

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South


问:
In JavaScript/AngularJS, I can't seem to remove the "T" in a date field from the DB?
I must be missing something very obvious, but I could use help. I have an Angular web app, which is getting data from a MS Web API. The DTO object has two date fields. When those fields come in, there is a "T" in the date field.

e.g. 2017-05-01T03:43:55

For whatever reason, I can't seem to get rid of that darn "T" when using the date. I'd tried using a date format both on the calendar control that displays the date data, and using the JavaScript format() command. I also tried using the Javascript replace() command to replace the "T" with a space. And I tried using Moment.js to create a new date (which seems to fail and give me an invalid date).

```<code>var startDate = moment(badge.startDate).format('yyyy-MM-dd HH:mm:ss');
var startDate = badge.startDate.format(''yyyy-MM-dd HH:mm:ss'');
var startDate = moment(badge.startDate).replace('T',' ');
</code>```

What am I missing? How should I be doing this? As far as I can tell, any of these should work?

答:
use, don't build what already exists!
First visit moment js this component is very helpful and has many options which you can do with a date.

```<code>var date = moment(yourDate).format('YYYY-MM-DD');
</code>```

format has a lot of options, you can find it on moment js documents.

Body:
I must be missing something very obvious, but I could use help. I have an Angular web app, which is getting data from a MS Web API. The DTO object has two date fields. When those fields come in, there is a "T" in the date field.

e.g. 2017-05-01T03:43:55

For whatever reason, I can't seem to get rid of that darn "T" when using the date. I'd tried using a date format both on the calendar control that displays the date data, and using the JavaScript format() command. I also tried using the Javascript replace() command to replace the "T" with a space. And I tried using Moment.js to create a new date (which seems to fail and give me an invalid date).

var startDate = moment(badge.startDate).format('yyyy-MM-dd HH:mm:ss');
var startDate = badge.startDate.format(''yyyy-MM-dd HH:mm:ss'');
var startDate = moment(badge.startDate).replace('T',' ');

What am I missing? How should I be doing this? As far as I can tell, any of these should work?

Body:
use, don't build what already exists!
First visit moment js this component is very helpful and has many options which you can do with a date.

var date = moment(yourDate).format('YYYY-MM-DD');

format has a lot of options, you can find it on moment js documents.


问:
How do I read multiple txt file and save them as respective object names?
I have hundreds of .txt files. I want to automate a process to read them all and save them with their respective file name. For example, I want to save them in this order without typing the name of individual files.

```<code>mytext1.txt <-read.table("./mytext1.txt", sep = "\t")
mytext2.txt <-read.table("./mytext2.txt", sep = "\t")
</code>```

Here is the code I have tried which of course doesn't save the dataframe in a separate object name.

```<code>filelist = list.files(pattern = ".*.txt")
datalist = lapply(filelist, FUN=read.table, header=TRUE, sep = "\t")
</code>```

答:
It looks like you are missing a line:

```<code>datafr = do.call("rbind", datalist)
</code>```

See this post for reference: How do you read in multiple .txt files into R?

Body:
I have hundreds of .txt files. I want to automate a process to read them all and save them with their respective file name. For example, I want to save them in this order without typing the name of individual files.

mytext1.txt <-read.table("./mytext1.txt", sep = "\t")
mytext2.txt <-read.table("./mytext2.txt", sep = "\t")

Here is the code I have tried which of course doesn't save the dataframe in a separate object name.

filelist = list.files(pattern = ".*.txt")
datalist = lapply(filelist, FUN=read.table, header=TRUE, sep = "\t")

Body:
It looks like you are missing a line:

datafr = do.call("rbind", datalist)

See this post for reference: How do you read in multiple .txt files into R?


问:
C - declare and init array inside struct
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

```<code>struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};
</code>```

later, i want to access the values ...

```<code>int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}
</code>```

the only error is

```<code>./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~
</code>```

答:
i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

That doesn't make any sense whatever, but your actual code is almost completely correct in C99 and later.  In particular, this:

```<code>(int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        }
</code>```

Is neither a declaration of nor (quite) an initialization of an array; rather, it is a compound literal of type array of int.  Because arrays decay to pointers in the context given, as in most, such a compound literal can indeed be used to initialize a structure member of type int * (to point to the first element of the array).  Having successfully initialized those two struct structname objects, you can certainly obtain their addresses and record those in variables.

HOWEVER, a pointer to an array element does not carry information about the number of elements in the array.  If that's all you have, as is the case in your main() function, then you cannot determine the number of array elements from it.  You need to be able to determine that from the content (this is why C strings must be null-terminated), or you must have that information from some other source, such as a function argument, a variable, or clairvoyance.

yes, i know my attempt is... let's say "not correct" :D but it would be very useful if something similar would exist.

If you declare the members of struct structname to be bona fide arrays then you can access and use their declared lengths.  If you prefer, you can store the number of array elements in additional members of that struct.  Both of those approaches are used in the wild, as are approaches based on the contents of the pointed to elements.  But I don't foresee C ever gaining a facility for making your ARRAY_SIZE() macro work with pointers as it seems you would like.

Body:
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};

later, i want to access the values ...

int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}

the only error is

./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~

Body:
i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

That doesn't make any sense whatever, but your actual code is almost completely correct in C99 and later.  In particular, this:

(int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        }

Is neither a declaration of nor (quite) an initialization of an array; rather, it is a compound literal of type array of int.  Because arrays decay to pointers in the context given, as in most, such a compound literal can indeed be used to initialize a structure member of type int * (to point to the first element of the array).  Having successfully initialized those two struct structname objects, you can certainly obtain their addresses and record those in variables.

HOWEVER, a pointer to an array element does not carry information about the number of elements in the array.  If that's all you have, as is the case in your main() function, then you cannot determine the number of array elements from it.  You need to be able to determine that from the content (this is why C strings must be null-terminated), or you must have that information from some other source, such as a function argument, a variable, or clairvoyance.

yes, i know my attempt is... let's say "not correct" :D but it would be very useful if something similar would exist.

If you declare the members of struct structname to be bona fide arrays then you can access and use their declared lengths.  If you prefer, you can store the number of array elements in additional members of that struct.  Both of those approaches are used in the wild, as are approaches based on the contents of the pointed to elements.  But I don't foresee C ever gaining a facility for making your ARRAY_SIZE() macro work with pointers as it seems you would like.


问:
Search column one to column two in Excel?
I have a sheet which has 3 columns.

In column one, I have 317 values and in other two 8000.

Now I have to match column one with column two and column three if either of them have that value I have to print YES In 4th column otherwise NO.

Example:

Column one has value: 'Big' in A2 cell

Column two has value : 'Big' in B9 cell,

Column three has value : 'Big' in B10 cell

then the it should print YES

答:
Briefer formula that returns TRUE or FALSE:

```<code>=AND(ISNUMBER(MATCH(A2,B:B,0)),ISNUMBER(MATCH(A2,C:C,0)))
</code>```

Formatted:

```<code>=AND(
    ISNUMBER(
        MATCH(A2,B:B,0)
    ),
    ISNUMBER(
        MATCH(A2,C:C,0)
    )
)
</code>```

The key here is using 0 as last argument to MATCH, meaning that the values in the lookup range can be in any order (see MATCH docs)

Body:
Briefer formula that returns TRUE or FALSE:

=AND(ISNUMBER(MATCH(A2,B:B,0)),ISNUMBER(MATCH(A2,C:C,0)))

Formatted:

=AND(
    ISNUMBER(
        MATCH(A2,B:B,0)
    ),
    ISNUMBER(
        MATCH(A2,C:C,0)
    )
)

The key here is using 0 as last argument to MATCH, meaning that the values in the lookup range can be in any order (see MATCH docs)


答:
I think you meant to do this:

```<code>test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for i in range(len(k)):
        k[i] = k[i] * 2
    x, y, z = k
    return k
</code>```

You're mixing indexes with values, and using index() to find the position in an array is incorrect, most of all because you're modifying the list and you'll find the same elements again but in different positions, better use a range to iterate over the indexes and retrieve the values.

Also, using globals is not cool. In fact, the whole procedure should be written like a list comprehension instead - simple and idiomatic:

```<code>[2 * x for x in test_list]
=> [4, 8, 12]
</code>```

Title: Python Function Returning List Objects Out of Order

Body:
I think you meant to do this:

test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for i in range(len(k)):
        k[i] = k[i] * 2
    x, y, z = k
    return k

You're mixing indexes with values, and using index() to find the position in an array is incorrect, most of all because you're modifying the list and you'll find the same elements again but in different positions, better use a range to iterate over the indexes and retrieve the values.

Also, using globals is not cool. In fact, the whole procedure should be written like a list comprehension instead - simple and idiomatic:

[2 * x for x in test_list]
=> [4, 8, 12]