问:
Best way to feature select using PCA (discussion)
Terminology:

Component: PC

loading-score[i,j]: the j feature in  PC[i]

Question:

I know the question regarding feature selection is asked several times here at StackOverflow (SO) and on other tech-pages, and it proposes different answers/discussion. That is why I want to open a discussion for the different solutions, and not post it as a general question since that has been done.

Different methods are proposed for feature selection using PCA: For instance using the dot product between the original features and the components (here) to get their correlation, a discussion at SO here suggests that you can only talk about important features as loading-scores in a component (and not use that importance in the input space), and another discussion at SO (which I cannot find at the moment) suggest that the importance for feature[j] would be abs(sum(loading_score[:,j]) i.e the sum of the absolute value of loading_score[i,j] for all i components.

I personally would think that a way to get the importance of a feature would be an absolute sum where each loading_score[i,j] is weighted by the explained variance of component i i.e

imp_feature[j]=sum_i (abs(loading_score[i,j])*explained_variance[i].

答:
Well, there is no universal way to select features; it totally depends on the dataset and some insights available about the dataset. I will provide some examples which might be helpful.

Since you asked about PCA, initially it separates the whole dataset into two sets under which the variances. On the other ICA (Independent Component Analysis) is able to extract multiple features simultaneously. Look at this example,

In this example, we mix three independent signals and try to separate out them using ICA and PCA. In this case, ICA is doing it a better way than PCA. In general, if you search Blind Souce Separation (BSS) you may find more information about this. Besides, in this example, we know the independent components thus, separation is easy. In general, we do not know the number of components. Hence, you may have to guess based on some prior information about the dataset. Also, you may use LDA (Linear Discriminate Analysis) to reduce the number of features.

Once you extract PC components using any of the techniques, following way we can visualize it. If we assume, those extracted components as random variables i.e., x, y, z

More information about you may refer to this original source where I took about two figures.

Coming back to your proposition,

```<code>imp_feature[j]=sum_i (abs(loading_score[i,j])*explained_variance[i]
</code>```

I would not recommend this way due to the following reasons:
 abs(loading_score[i,j]) when we get absolute values you may loose positive or negative correlations of considered features. explained_variance[i] may be used to find the correlation between features, but multiplying does not make any sense.

Edit:
In PCA, each component has its explained variance. Explained variance is the ratio between individual component variance and total variance(sum of all individual components variances). Feature significance can be measured by magnitude of explained variance.

All in all, what I want to say, feature selection totally depends on the dataset and the significance of features. PCA is just one technique. Frist understand the properties of features and the dataset. Then, try to extract features. Hope this helps. If you can provide us with an exact example, we may provide more insights.

Body:
Well, there is no universal way to select features; it totally depends on the dataset and some insights available about the dataset. I will provide some examples which might be helpful.

Since you asked about PCA, initially it separates the whole dataset into two sets under which the variances. On the other ICA (Independent Component Analysis) is able to extract multiple features simultaneously. Look at this example,

In this example, we mix three independent signals and try to separate out them using ICA and PCA. In this case, ICA is doing it a better way than PCA. In general, if you search Blind Souce Separation (BSS) you may find more information about this. Besides, in this example, we know the independent components thus, separation is easy. In general, we do not know the number of components. Hence, you may have to guess based on some prior information about the dataset. Also, you may use LDA (Linear Discriminate Analysis) to reduce the number of features.

Once you extract PC components using any of the techniques, following way we can visualize it. If we assume, those extracted components as random variables i.e., x, y, z

More information about you may refer to this original source where I took about two figures.

Coming back to your proposition,

imp_feature[j]=sum_i (abs(loading_score[i,j])*explained_variance[i]

I would not recommend this way due to the following reasons:
 abs(loading_score[i,j]) when we get absolute values you may loose positive or negative correlations of considered features. explained_variance[i] may be used to find the correlation between features, but multiplying does not make any sense.

Edit:
In PCA, each component has its explained variance. Explained variance is the ratio between individual component variance and total variance(sum of all individual components variances). Feature significance can be measured by magnitude of explained variance.

All in all, what I want to say, feature selection totally depends on the dataset and the significance of features. PCA is just one technique. Frist understand the properties of features and the dataset. Then, try to extract features. Hope this helps. If you can provide us with an exact example, we may provide more insights.


来源: stackexchange

问:
Restart loop when it ends

 let options = document.getElementsByClassName("option");
 console.log(options);
 var i = 1;

for (let i = 0; i < options.length; i++){
        options[i].classList.remove("active")
        setTimeout(function () {
            if(i!=0){
                console.log(options[i-1].classList.remove("active"))
            }
            console.log(options[i].classList.add("active"))

         }, i*3000)

}

function changeItem(item){
    item.classList.add("active")
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    overflow: hidden;
    height: 100vh;
    font-family: 'Roboto', sans-serif;
  }
  body .credit {
    position: absolute;
    bottom: 20px;
    left: 20px;
    color: #000;
  }
  body .options {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-align: stretch;
            align-items: stretch;
    overflow: hidden;
    min-width: 600px;
    max-width: 900px;
    width: calc(100% - 100px);
    height: 400px;
  }
  @media screen and (max-width: 718px) {
    body .options {
      min-width: 520px;
    }
    body .options .option:nth-child(5) {
      display: none;
    }
  }
  @media screen and (max-width: 638px) {
    body .options {
      min-width: 440px;
    }
    body .options .option:nth-child(4) {
      display: none;
    }
  }
  @media screen and (max-width: 558px) {
    body .options {
      min-width: 360px;
    }
    body .options .option:nth-child(3) {
      display: none;
    }
  }
  @media screen and (max-width: 478px) {
    body .options {
      min-width: 280px;
    }
    body .options .option:nth-child(2) {
      display: none;
    }
  }
  body .options .option {
    position: relative;
    overflow: hidden;
    min-width: 60px;
    margin: 10px;
    background: var(--optionBackground, var(--defaultBackground, #E6E9ED));
    background-size: auto 120%;
    background-position: center;
    cursor: pointer;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option:nth-child(1) {
    --defaultBackground:#ED5565;
  }
  body .options .option:nth-child(2) {
    --defaultBackground:#FC6E51;
  }
  body .options .option:nth-child(3) {
    --defaultBackground:#FFCE54;
  }
  body .options .option:nth-child(4) {
    --defaultBackground:#2ECC71;
  }
  body .options .option:nth-child(5) {
    --defaultBackground:#5D9CEC;
  }
  body .options .option:nth-child(6) {
    --defaultBackground:#AC92EC;
  }
  body .options .option.active {
    -webkit-box-flex: 10000;
            flex-grow: 10000;
    -webkit-transform: scale(1);
            transform: scale(1);
    max-width: 600px;
    margin: 0px;
    border-radius: 40px;
    background-size: auto 100%;
    /*&:active {
       transform:scale(0.9);
    }*/
  }
  body .options .option.active .shadow {
    box-shadow: inset 0 -120px 120px -120px black, inset 0 -120px 120px -100px black;
  }
  body .options .option.active .label {
    bottom: 20px;
    left: 20px;
  }
  body .options .option.active .label .info > div {
    left: 0px;
    opacity: 1;
  }
  body .options .option:not(.active) {
    -webkit-box-flex: 1;
            flex-grow: 1;
    border-radius: 30px;
  }
  body .options .option:not(.active) .shadow {
    bottom: -40px;
    box-shadow: inset 0 -120px 0px -120px black, inset 0 -120px 0px -100px black;
  }
  body .options .option:not(.active) .label {
    bottom: 10px;
    left: 10px;
  }
  body .options .option:not(.active) .label .info > div {
    left: 20px;
    opacity: 0;
  }
  body .options .option .shadow {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    height: 120px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label {
    display: -webkit-box;
    display: flex;
    position: absolute;
    right: 0px;
    height: 40px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label .icon {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    min-width: 40px;
    max-width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: white;
    color: var(--defaultBackground);
  }
  body .options .option .label .info {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
            flex-direction: column;
    -webkit-box-pack: center;
            justify-content: center;
    margin-left: 10px;
    color: white;
    white-space: pre;
  }
  body .options .option .label .info > div {
    position: relative;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
  }
  body .options .option .label .info .main {
    font-weight: bold;
    font-size: 1.2rem;
  }
  body .options .option .label .info .sub {
    -webkit-transition-delay: .1s;
            transition-delay: .1s;
  }
  </code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Blonkisoaz

Omuke trughte a otufta

Oretemauw

Omuke trughte a otufta

Iteresuselle

Omuke trughte a otufta

Idiefe

Omuke trughte a otufta

Inatethi

Omuke trughte a otufta

     Photos from Victor of Valencia on tumblr

```

I took this animation from codepen , initially it executes on clicks only but I wanted to execute it after 3s. So I added a for loop.

I am changing classes of each element after 3000ms, what I want is when loops ends or reach last element it should restart from beginning. I tired setting i = 0 when i is last element of array, but it didn't work somehow.

Thanks in advance.

答:
You can use setInterval instead of setTimeOut inside a for loop.</p>

```<code> let options = document.getElementsByClassName("option");
 var i = 1;
 setInterval(function () {
  if (i === 5) {
    options[i - 1].classList.remove("active")
    i = 0
  }
  if (i != 0) {
    if (i === 5) {
      options[i].classList.remove("active")
    }
    options[i - 1].classList.remove("active")
  }
  options[i].classList.add("active")
  i++
 }, 3000)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Restart loop when it ends

Body:
 let options = document.getElementsByClassName("option");
 console.log(options);
 var i = 1;

for (let i = 0; i < options.length; i++){
        options[i].classList.remove("active")
        setTimeout(function () {
            if(i!=0){
                console.log(options[i-1].classList.remove("active"))
            }
            console.log(options[i].classList.add("active"))

         }, i*3000)

}

function changeItem(item){
    item.classList.add("active")
}

body {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    overflow: hidden;
    height: 100vh;
    font-family: 'Roboto', sans-serif;
  }
  body .credit {
    position: absolute;
    bottom: 20px;
    left: 20px;
    color: #000;
  }
  body .options {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-align: stretch;
            align-items: stretch;
    overflow: hidden;
    min-width: 600px;
    max-width: 900px;
    width: calc(100% - 100px);
    height: 400px;
  }
  @media screen and (max-width: 718px) {
    body .options {
      min-width: 520px;
    }
    body .options .option:nth-child(5) {
      display: none;
    }
  }
  @media screen and (max-width: 638px) {
    body .options {
      min-width: 440px;
    }
    body .options .option:nth-child(4) {
      display: none;
    }
  }
  @media screen and (max-width: 558px) {
    body .options {
      min-width: 360px;
    }
    body .options .option:nth-child(3) {
      display: none;
    }
  }
  @media screen and (max-width: 478px) {
    body .options {
      min-width: 280px;
    }
    body .options .option:nth-child(2) {
      display: none;
    }
  }
  body .options .option {
    position: relative;
    overflow: hidden;
    min-width: 60px;
    margin: 10px;
    background: var(--optionBackground, var(--defaultBackground, #E6E9ED));
    background-size: auto 120%;
    background-position: center;
    cursor: pointer;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option:nth-child(1) {
    --defaultBackground:#ED5565;
  }
  body .options .option:nth-child(2) {
    --defaultBackground:#FC6E51;
  }
  body .options .option:nth-child(3) {
    --defaultBackground:#FFCE54;
  }
  body .options .option:nth-child(4) {
    --defaultBackground:#2ECC71;
  }
  body .options .option:nth-child(5) {
    --defaultBackground:#5D9CEC;
  }
  body .options .option:nth-child(6) {
    --defaultBackground:#AC92EC;
  }
  body .options .option.active {
    -webkit-box-flex: 10000;
            flex-grow: 10000;
    -webkit-transform: scale(1);
            transform: scale(1);
    max-width: 600px;
    margin: 0px;
    border-radius: 40px;
    background-size: auto 100%;
    /*&:active {
       transform:scale(0.9);
    }*/
  }
  body .options .option.active .shadow {
    box-shadow: inset 0 -120px 120px -120px black, inset 0 -120px 120px -100px black;
  }
  body .options .option.active .label {
    bottom: 20px;
    left: 20px;
  }
  body .options .option.active .label .info > div {
    left: 0px;
    opacity: 1;
  }
  body .options .option:not(.active) {
    -webkit-box-flex: 1;
            flex-grow: 1;
    border-radius: 30px;
  }
  body .options .option:not(.active) .shadow {
    bottom: -40px;
    box-shadow: inset 0 -120px 0px -120px black, inset 0 -120px 0px -100px black;
  }
  body .options .option:not(.active) .label {
    bottom: 10px;
    left: 10px;
  }
  body .options .option:not(.active) .label .info > div {
    left: 20px;
    opacity: 0;
  }
  body .options .option .shadow {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    height: 120px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label {
    display: -webkit-box;
    display: flex;
    position: absolute;
    right: 0px;
    height: 40px;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95);
  }
  body .options .option .label .icon {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
            flex-direction: row;
    -webkit-box-pack: center;
            justify-content: center;
    -webkit-box-align: center;
            align-items: center;
    min-width: 40px;
    max-width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: white;
    color: var(--defaultBackground);
  }
  body .options .option .label .info {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
            flex-direction: column;
    -webkit-box-pack: center;
            justify-content: center;
    margin-left: 10px;
    color: white;
    white-space: pre;
  }
  body .options .option .label .info > div {
    position: relative;
    -webkit-transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
    transition: 0.5s cubic-bezier(0.05, 0.61, 0.41, 0.95), opacity 0.5s ease-out;
  }
  body .options .option .label .info .main {
    font-weight: bold;
    font-size: 1.2rem;
  }
  body .options .option .label .info .sub {
    -webkit-transition-delay: .1s;
            transition-delay: .1s;
  }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Blonkisoaz

Omuke trughte a otufta

Oretemauw

Omuke trughte a otufta

Iteresuselle

Omuke trughte a otufta

Idiefe

Omuke trughte a otufta

Inatethi

Omuke trughte a otufta

     Photos from Victor of Valencia on tumblr

I took this animation from codepen , initially it executes on clicks only but I wanted to execute it after 3s. So I added a for loop.

I am changing classes of each element after 3000ms, what I want is when loops ends or reach last element it should restart from beginning. I tired setting i = 0 when i is last element of array, but it didn't work somehow.

Thanks in advance.

Body:
You can use setInterval instead of setTimeOut inside a for loop.

 let options = document.getElementsByClassName("option");
 var i = 1;
 setInterval(function () {
  if (i === 5) {
    options[i - 1].classList.remove("active")
    i = 0
  }
  if (i != 0) {
    if (i === 5) {
      options[i].classList.remove("active")
    }
    options[i - 1].classList.remove("active")
  }
  options[i].classList.add("active")
  i++
 }, 3000)


问:
How to count the consecutive duplicate values in an array?
I have an array like this:

```<code>$arr = array(1, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3);
</code>```

I found the function array_count_values(), but it will group all of the same values and count the occurrences without respecting breaks in the consecutive sequences.

```<code>$result[1] = 5
$result[2] = 4
$result[3] = 3
</code>```

How can I group each set of consecutive values and count the length of each sequence?  Notice there are two sets of sequences for the numbers 1, 2, and 3.

The data that I expect to generate needs to resemble this:

```<code>[1] = 3;
[2] = 2;
[3] = 2;
[1] = 2;
[2] = 2;
[3] = 1;
</code>```

答:
My suggestion is to extract&remove the first value from the array prior to entering the loop and use a temporary array ($carry) to track whether each new value matches the key in the carry array.  If so, increment it.  If not, push the completed sequence count into the result array and overwrite the carry with the new value and set the counter to 1.  When the loop finishes, push the lingering carry into the result set.  My snippet does not check if the input array is empty; if necessary, add that condition to your project.

Code: (Demo)

```<code>$array = [1,1,1,2,2,3,3,1,1,2,2,3];

$result = [];
$carry = [array_shift($array) => 1];

foreach ($array as $value) {
    if (isset($carry[$value])) {
        ++$carry[$value];
    } else {
        $result[] = $carry;
        $carry = [$value => 1];
    }
}
$result[] = $carry;
print_r($result);
</code>```

Output: (condensed to reduce page bloat)

```<code>[
    [1 => 3],
    [2 => 2],
    [3 => 2],
    [1 => 2],
    [2 => 2],
    [3 => 1],
]
</code>```

If you'd rather implement a zerkms-style, modify-by-reference style technique, the following snippet provides the same result as the above snippet.

Effectively, it pushes every newly encountered value as an associative, single-element array into the indexed result array.  Because the pushed subarray is declared as a variable ($carry) then assigned-by-reference (= &) to the result array, incrementation of $carry will be applied to the deeply nested value in the result array.  The output array requires the additional depth in its structure so that a given value which occurs multiple times can be reliably stored.

Code: (Demo)

```<code>$result = [];
$carry = [];
foreach ($array as $value) {
    if ($carry && key($carry) === $value) {
        ++$carry[$value];
    } else {
        unset($carry);
        $carry = [$value => 1];
        $result[] = &$carry;
    }
}
unset($carry);
print_r($result);
</code>```

Unsetting the reference variable $carry after the loop may not be necessary, but if there is any potential re-use of that variable within the variable's scope, it will be important to uncouple the reference with unset().

And just for fun, here is a hideous regex-infused approach that works with the sample data: Demo

Body:
I have an array like this:

$arr = array(1, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3);

I found the function array_count_values(), but it will group all of the same values and count the occurrences without respecting breaks in the consecutive sequences.

$result[1] = 5
$result[2] = 4
$result[3] = 3

How can I group each set of consecutive values and count the length of each sequence?  Notice there are two sets of sequences for the numbers 1, 2, and 3.

The data that I expect to generate needs to resemble this:

[1] = 3;
[2] = 2;
[3] = 2;
[1] = 2;
[2] = 2;
[3] = 1;

Body:
My suggestion is to extract&remove the first value from the array prior to entering the loop and use a temporary array ($carry) to track whether each new value matches the key in the carry array.  If so, increment it.  If not, push the completed sequence count into the result array and overwrite the carry with the new value and set the counter to 1.  When the loop finishes, push the lingering carry into the result set.  My snippet does not check if the input array is empty; if necessary, add that condition to your project.

Code: (Demo)

$array = [1,1,1,2,2,3,3,1,1,2,2,3];

$result = [];
$carry = [array_shift($array) => 1];

foreach ($array as $value) {
    if (isset($carry[$value])) {
        ++$carry[$value];
    } else {
        $result[] = $carry;
        $carry = [$value => 1];
    }
}
$result[] = $carry;
print_r($result);

Output: (condensed to reduce page bloat)

[
    [1 => 3],
    [2 => 2],
    [3 => 2],
    [1 => 2],
    [2 => 2],
    [3 => 1],
]

If you'd rather implement a zerkms-style, modify-by-reference style technique, the following snippet provides the same result as the above snippet.

Effectively, it pushes every newly encountered value as an associative, single-element array into the indexed result array.  Because the pushed subarray is declared as a variable ($carry) then assigned-by-reference (= &) to the result array, incrementation of $carry will be applied to the deeply nested value in the result array.  The output array requires the additional depth in its structure so that a given value which occurs multiple times can be reliably stored.

Code: (Demo)

$result = [];
$carry = [];
foreach ($array as $value) {
    if ($carry && key($carry) === $value) {
        ++$carry[$value];
    } else {
        unset($carry);
        $carry = [$value => 1];
        $result[] = &$carry;
    }
}
unset($carry);
print_r($result);

Unsetting the reference variable $carry after the loop may not be necessary, but if there is any potential re-use of that variable within the variable's scope, it will be important to uncouple the reference with unset().

And just for fun, here is a hideous regex-infused approach that works with the sample data: Demo


问:
When using MVVM design pattern, Is there a way to prevent Controller layer to communicate with Model layer in swift?
Typically, In the MVVM design pattern, the Controller will not directly communicate with the Model. ViewModel will be the buffer layer between C and M. However, if there is a data model in the Model like

```<code>struct Book
{
  var title: String
}
</code>```

we can still define a variable in Controller like:

```<code>var books = [Book]()
</code>```

In this case, the controller still can directly communicate with the Model but not through ViewModel.

Is there a way to prevent it? For example, adding an access control for the Model class or some other ways.

答:
Here is possible approach - to define public view model and interface to model, but file private model itself, so view model can manage model, but anybody outside can work with it only via public interfaces:</p>

```<code>public protocol Reading {
    var title: String { get set }
}

public class BooksViewModel {
    public var books = [Reading]()

    public func createNewBook() -> Reading {
        let book = Book()
        self.books.append(book)
        return book
    }
}

fileprivate struct Book: Reading
{
  var title: String = "Undefined"
}
</code>```

Body:
Typically, In the MVVM design pattern, the Controller will not directly communicate with the Model. ViewModel will be the buffer layer between C and M. However, if there is a data model in the Model like

struct Book
{
  var title: String
}

we can still define a variable in Controller like:

var books = [Book]()

In this case, the controller still can directly communicate with the Model but not through ViewModel.

Is there a way to prevent it? For example, adding an access control for the Model class or some other ways.

Body:
Here is possible approach - to define public view model and interface to model, but file private model itself, so view model can manage model, but anybody outside can work with it only via public interfaces:

public protocol Reading {
    var title: String { get set }
}

public class BooksViewModel {
    public var books = [Reading]()

    public func createNewBook() -> Reading {
        let book = Book()
        self.books.append(book)
        return book
    }
}

fileprivate struct Book: Reading
{
  var title: String = "Undefined"
}


问:
Getting data from text file and display it in html table
I got a text file in this pattern for each line:

```<code>Username : Score
</code>```

I'm trying to create a scoreboard out of this.

This is my attempt:

    Nom
    Score

```
</div>
</div>
</p>

<p>The question is how can I copy each <code>username</code> and <code>score</code> to the table (without the <code>:</code> character) ?</p>

<p><strong>EDIT:</strong></p>

<p>My current php code:</p>

```<?php

    $file = file_get_contents('facile.txt', true);
    $arr = explode("/", $file, 2);
    $first = $arr[0];

?>
```

This will give me only the first username, but I want to get all the usernames from every line.

答:
Rizier123's answer was perfect. But I had to make some changes to get it to work in my system. </p>

```<code><!DOCTYPE HTML>
<html>
<body>
<?php

    $lines = file("scores.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    function explodeLine($v)
    {
        list($username, $score) = explode(":", $v);
        return array("username" => $username, "score" => $score);
    }
    $data = array_map('explodeLine', $lines);

    function comparatorFunc($a, $b)
    {
        if($a["score"] == $b["score"])
            return 0;
        return $a["score"] > $b["score"] ? 1 : -1;
    }
    usort($data, 'comparatorFunc');

?>

<table width="200" border="1">
    <tr>
        <td width="85">Nom</td>
        <td width="99">Score</td>
    </tr>
<?php foreach($data as $user){ ?>
    <tr>
        <td height="119"><?php echo $user["username"]; ?></td>
        <td><?php echo $user["score"]; ?></td>
    </tr>
<?php } ?>
</table>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got a text file in this pattern for each line:

Username : Score

I'm trying to create a scoreboard out of this.

This is my attempt:

    Nom
    Score

The question is how can I copy each username and score to the table (without the : character) ?

EDIT:

My current php code:

<?php

    $file = file_get_contents('facile.txt', true);
    $arr = explode("/", $file, 2);
    $first = $arr[0];

?>

This will give me only the first username, but I want to get all the usernames from every line.

Body:
Rizier123's answer was perfect. But I had to make some changes to get it to work in my system.

<!DOCTYPE HTML>
<html>
<body>
<?php

    $lines = file("scores.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    function explodeLine($v)
    {
        list($username, $score) = explode(":", $v);
        return array("username" => $username, "score" => $score);
    }
    $data = array_map('explodeLine', $lines);

    function comparatorFunc($a, $b)
    {
        if($a["score"] == $b["score"])
            return 0;
        return $a["score"] > $b["score"] ? 1 : -1;
    }
    usort($data, 'comparatorFunc');

?>

<table width="200" border="1">
    <tr>
        <td width="85">Nom</td>
        <td width="99">Score</td>
    </tr>
<?php foreach($data as $user){ ?>
    <tr>
        <td height="119"><?php echo $user["username"]; ?></td>
        <td><?php echo $user["score"]; ?></td>
    </tr>
<?php } ?>
</table>
</body>
</html>


问:
Project runing But database connection not fount
```<code>This is my .env file....
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

this is from database.php file

 'connections' => [

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
</code>```

but my project working there is no database connection.
where from database connecting???
and issue is when i upload it on live i getting error
"Access denied for user 'root'@'localhost'"
i have cleared all cache and every thing but i didn't find database connection detail any where.
this project installed that time i give all details.

i have used all these
php artisan cache:clear

php artisan config:clear

php artisan config:cache

php artisan route:clear

php artisan route:cache

but not working

答:
Add your database details
username and password of your database in your env file</p>

Body:
This is my .env file....
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

this is from database.php file

 'connections' => [

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

but my project working there is no database connection.
where from database connecting???
and issue is when i upload it on live i getting error
"Access denied for user 'root'@'localhost'"
i have cleared all cache and every thing but i didn't find database connection detail any where.
this project installed that time i give all details.

i have used all these
php artisan cache:clear

php artisan config:clear

php artisan config:cache

php artisan route:clear

php artisan route:cache

but not working


问:
Extracting labels from owl ontologies when the label isn't in the ontology but can be found at the URI
Please bear with me as I am new to semantic technologies.

I am trying to use the package rdflib to extract labels from classes in ontologies. However some ontologies don't contain the labels themselves but have the URIs of classes from other ontologies. How does one extract the labels from URIs of the external ontologies?

The intuition behind my attempts center on identifying classes that don't contain labels locally (if that is the right way of putting it) and then "following" their URIs to the external ontologies to extract the labels. However the way I have implemented it does not work.

```<code>import rdflib

g = rdflib.Graph()

# I have no trouble extracting labels from this ontology:
# g.load("http://purl.obolibrary.org/obo/po.owl#")
# However, this ontology contains no labels locally:
g.load("http://www.bioassayontology.org/bao/bao_complete.owl#")

owlClass = rdflib.namespace.OWL.Class
rdfType = rdflib.namespace.RDF.type

for s in g.subjects(predicate=rdfType, object=owlClass):
    # Where label is present...
    if g.label(s) != '':
        # Do something with label...
        print(g.label(s))

    # This is what I have added to try to follow the URI to the external ontology.
    elif g.label(s) == '':
        g2 = rdflib.Graph()
        g2.parse(location=s)
        # Do something with label...
        print(g.label(s))

</code>```

Am I taking completely the wrong approach? All help is appreciated! Thank you.

答:
I think you can be much more efficient than this. You are trying to do a web request, remote ontology download and search every time you encounter a URI that doesn't have a label given in http://www.bioassayontology.org/bao/bao_complete.owl which is most of them and it's a very large number. So your script will take forever and thrash the web servers delivering those remote ontologies.

Looking at http://www.bioassayontology.org/bao/bao_complete.owl, I see that most of the URIs without labels there are from OBO, and perhaps a couple of other ontologies, but mostly OBO.

What you should do is download OBO once and load that with RDFlib. Then if you run your script above on the joined (union) graph of http://www.bioassayontology.org/bao/bao_complete.owl & OBO, you'll have all OBO's content at your fingertips so that g.label(s) will find a much higher proportion of labels.

Perhaps there are a couple of other source ontologies providing labels for http://www.bioassayontology.org/bao/bao_complete.owl you may need as well but my quick browsing sees only OBO.

Body:
Please bear with me as I am new to semantic technologies.

I am trying to use the package rdflib to extract labels from classes in ontologies. However some ontologies don't contain the labels themselves but have the URIs of classes from other ontologies. How does one extract the labels from URIs of the external ontologies?

The intuition behind my attempts center on identifying classes that don't contain labels locally (if that is the right way of putting it) and then "following" their URIs to the external ontologies to extract the labels. However the way I have implemented it does not work.

import rdflib

g = rdflib.Graph()

# I have no trouble extracting labels from this ontology:
# g.load("http://purl.obolibrary.org/obo/po.owl#")
# However, this ontology contains no labels locally:
g.load("http://www.bioassayontology.org/bao/bao_complete.owl#")

owlClass = rdflib.namespace.OWL.Class
rdfType = rdflib.namespace.RDF.type

for s in g.subjects(predicate=rdfType, object=owlClass):
    # Where label is present...
    if g.label(s) != '':
        # Do something with label...
        print(g.label(s))

    # This is what I have added to try to follow the URI to the external ontology.
    elif g.label(s) == '':
        g2 = rdflib.Graph()
        g2.parse(location=s)
        # Do something with label...
        print(g.label(s))

Am I taking completely the wrong approach? All help is appreciated! Thank you.


问:
Current User Information in Angular9
How can I get current Login User Information in Angular 9????????????

 I am new on web development and working on a project in Angular 9. I successfully logined by providing username and password. Now I want to get current user id but in this task I am failed.Please any one can guide me how can I get current user id or current user profile from database and to store this information in the local storage. Code of my login.component.ts is here

```<code>import { AppConstants } from './../../private/AppConstants';
import { BadInput } from './../../../common/ErrorHandler/badInput';
import { AuthService } from '../../private/Services/auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

import { AppError } from '../../../common/ErrorHandler/appError';
import { toBase64String } from '@angular/compiler/src/output/source_map';
import { stringify } from 'querystring';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  invalidLogin: boolean = false;
  userName: string;
  constructor(
    private route: Router,
    private router: ActivatedRoute,
    private authService: AuthService) {

  }

  errorFlag: boolean;
  errorMessage: string;

  ngOnInit() { }

  signIn(credentials) {
    this.errorFlag = false;
    this.authService.blockUI.start();
    this.authService.login(credentials)
      .subscribe(
      resp => {
          let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
          if (resp !== undefined && resp["access_token"]) {
            localStorage.setItem(AppConstants.userInfo , resp["access_token"] );
            localStorage.setItem("message","Welcome Sajid");
            localStorage.setItem("userid",resp["access_id"]);
            this.route.navigate([returnUrl || '/']);
          }
          else this.invalidLogin = true;
          this.authService.blockUI.stop();
        },
        (error) => {
          this.authService.blockUI.stop();
          if (error instanceof BadInput) {
            //alert(error.message);
            this.errorMessage = error.message;
          }
          //else throw error;
          else if (error.status === 400) {
            //alert(error.json().error_description);
            this.errorMessage = error.json().error_description;
          }
          this.errorFlag = true;
        }
      );
  }
}

My service code is given below
import { HttpClient } from '@angular/common/http';
import { AppConstants } from './../AppConstants';
import { NotFoundError } from '../../../common/ErrorHandler/notFoundError';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
//import { Http, Headers, RequestOptions } from '@angular/http';
import { AppError } from '../../../common/ErrorHandler/appError';
import {environment} from '../../../environments/environment'
import { BadInput } from '../../../common/ErrorHandler/badInput';
import { NgBlockUI, BlockUI } from 'ng-block-ui';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

  constructor(private http : HttpClient){
     this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
   this.options = {headers  : this.headers};
   }
  private headers;
  private options;
  @BlockUI() blockUI: NgBlockUI;

  login(credentials)
  {

     return this.http.post( environment.authURL +  "token",
     "grant_type=password&username="+ credentials.userName + "&password=" + credentials.password +
      "&client_id="+ environment.clientId ,this.options);
  }

  logout()
  {
    localStorage.clear();
  }

isLogedIn()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  if(userInfo !== undefined && userInfo !== null)
  {
   //let expiryDate : Date = new Date(userInfo[".expires"]);
   //if (expiryDate > new Date()) return true;
   // Implement Refresh token Logic here as well ...........
   return true;
  }

  return false;
}

currentUser()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  return userInfo;
}

private ErrorHandler(error : Response)
{
  if(error.status === 404)
  {
    //return Observable.throw(new NotFoundError());
  }
  if(error.status === 400)
  {
    ///return Observable.throw(new BadInput(error.json().error_description));
  }
  //return Observable.throw(new AppError(error));
}

}
</code>```

答:
Validate in backend using username and password return data or error based on result and this will help for login    </p>

```<code>.subscribe(
      data => {
          // Add successfull usl Headers;
      },
      error =>{
        //rediredt to login page
      }
);
</code>```

Title: Current User Information in Angular9

Body:
How can I get current Login User Information in Angular 9????????????

 I am new on web development and working on a project in Angular 9. I successfully logined by providing username and password. Now I want to get current user id but in this task I am failed.Please any one can guide me how can I get current user id or current user profile from database and to store this information in the local storage. Code of my login.component.ts is here

import { AppConstants } from './../../private/AppConstants';
import { BadInput } from './../../../common/ErrorHandler/badInput';
import { AuthService } from '../../private/Services/auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

import { AppError } from '../../../common/ErrorHandler/appError';
import { toBase64String } from '@angular/compiler/src/output/source_map';
import { stringify } from 'querystring';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  invalidLogin: boolean = false;
  userName: string;
  constructor(
    private route: Router,
    private router: ActivatedRoute,
    private authService: AuthService) {

  }

  errorFlag: boolean;
  errorMessage: string;

  ngOnInit() { }

  signIn(credentials) {
    this.errorFlag = false;
    this.authService.blockUI.start();
    this.authService.login(credentials)
      .subscribe(
      resp => {
          let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
          if (resp !== undefined && resp["access_token"]) {
            localStorage.setItem(AppConstants.userInfo , resp["access_token"] );
            localStorage.setItem("message","Welcome Sajid");
            localStorage.setItem("userid",resp["access_id"]);
            this.route.navigate([returnUrl || '/']);
          }
          else this.invalidLogin = true;
          this.authService.blockUI.stop();
        },
        (error) => {
          this.authService.blockUI.stop();
          if (error instanceof BadInput) {
            //alert(error.message);
            this.errorMessage = error.message;
          }
          //else throw error;
          else if (error.status === 400) {
            //alert(error.json().error_description);
            this.errorMessage = error.json().error_description;
          }
          this.errorFlag = true;
        }
      );
  }
}

My service code is given below
import { HttpClient } from '@angular/common/http';
import { AppConstants } from './../AppConstants';
import { NotFoundError } from '../../../common/ErrorHandler/notFoundError';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
//import { Http, Headers, RequestOptions } from '@angular/http';
import { AppError } from '../../../common/ErrorHandler/appError';
import {environment} from '../../../environments/environment'
import { BadInput } from '../../../common/ErrorHandler/badInput';
import { NgBlockUI, BlockUI } from 'ng-block-ui';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

  constructor(private http : HttpClient){
     this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
   this.options = {headers  : this.headers};
   }
  private headers;
  private options;
  @BlockUI() blockUI: NgBlockUI;

  login(credentials)
  {

     return this.http.post( environment.authURL +  "token",
     "grant_type=password&username="+ credentials.userName + "&password=" + credentials.password +
      "&client_id="+ environment.clientId ,this.options);
  }

  logout()
  {
    localStorage.clear();
  }

isLogedIn()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  if(userInfo !== undefined && userInfo !== null)
  {
   //let expiryDate : Date = new Date(userInfo[".expires"]);
   //if (expiryDate > new Date()) return true;
   // Implement Refresh token Logic here as well ...........
   return true;
  }

  return false;
}

currentUser()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  return userInfo;
}

private ErrorHandler(error : Response)
{
  if(error.status === 404)
  {
    //return Observable.throw(new NotFoundError());
  }
  if(error.status === 400)
  {
    ///return Observable.throw(new BadInput(error.json().error_description));
  }
  //return Observable.throw(new AppError(error));
}

}

Body:
Validate in backend using username and password return data or error based on result and this will help for login

.subscribe(
      data => {
          // Add successfull usl Headers;
      },
      error =>{
        //rediredt to login page
      }
);


问:
What is the relation between CPU utilization and energy consumption?
What is the function that describes the relation between CPU utilization and consumption of energy (electricity/heat wise).

I wonder if it's linear/sub-linear/exp etc..

I am writing a program that decreases the CPU utilization/load of other programs and my main concern is how much do I benefit energy wise..

Moreover, my server is mostly being used as a web-server or DB in a data-center (headless).

In case the data center need more power for cooling I need to consider that as well..
I also need to know what is the effect of CPU utilization on the entire machine power consumption ..

答:
Here you can find a short ppt answering your questions, and providing additional info.

Although there is no Copyright notice in the ppt, the work is probably protected, so I will copy here only three graphs relevant to your main question and follow-ups in comments.

HTH!


问:
How can I type the OAuthClient from googleapis?
I am working on nodemailer app with gmail OAuth2 in TypeScript, with "noImplicitAny": true,"noImplicitReturns": true. This requires me to explicitly specify return types.

I have this snippet

```<code>import { google } from 'googleapis';

export const getOAuth2Client = (): OAuth2Client => { // 2. So I set the return type as OAuth2Client
  const { OAuth2 } = google.auth;

  const auth2Client = new OAuth2(
    process.env.G_OAUTH_CLIENT_ID,
    process.env.G_OAUTH_CLIENT_SECRET,
    process.env.G_OAUTH_REDIRECT_URL
  );

  auth2Client.setCredentials({
    /* eslint-disable @typescript-eslint/camelcase */
    refresh_token: process.env.G_OAUTH_REFRESH_TOKEN,
  });

  return auth2Client; // 1. Inspecting auth2Client shows its of type OAuth2Client
};

</code>```

I got the OAuth2Client type on inspecting the type of the returned auth2Client. The problem though is where to import it from and use it in the project.

I tried the following...

```<code>import { google, OAuth2Client } from 'googleapis';
</code>```

That fails as googleapis has no such named export.

I also saw this approach from @corolla answer where he imports the types from google-auth-library

```<code>import { OAuth2Client } from 'google-auth-library';
</code>```

I would wish to use the type without having to add another library as a dependency just for a single type for an already typed library (Much as googleapis uses types from google-auth-library under the hood, the project linter requires me to list it as a project dependency, which I wouldn't wish to do for now). Is there any other way I can go about this please.

Thank you.

答:
I settled with just disabling the eslint warning for no-extraneous-dependencies.

// eslint-disable-next-line import/no-extraneous-dependencies
import { OAuth2Client } from 'google-auth-library';
import { google } from 'googleapis';

```

I couldn't specifically specify google-auth-library as a project dependency just to pick one type, yet under the hood, the googleapis package was also importing the types for the same package. So I wouldn't be breaking anything I guess.

Body:
I am working on nodemailer app with gmail OAuth2 in TypeScript, with "noImplicitAny": true,"noImplicitReturns": true. This requires me to explicitly specify return types.

I have this snippet

import { google } from 'googleapis';

export const getOAuth2Client = (): OAuth2Client => { // 2. So I set the return type as OAuth2Client
  const { OAuth2 } = google.auth;

  const auth2Client = new OAuth2(
    process.env.G_OAUTH_CLIENT_ID,
    process.env.G_OAUTH_CLIENT_SECRET,
    process.env.G_OAUTH_REDIRECT_URL
  );

  auth2Client.setCredentials({
    /* eslint-disable @typescript-eslint/camelcase */
    refresh_token: process.env.G_OAUTH_REFRESH_TOKEN,
  });

  return auth2Client; // 1. Inspecting auth2Client shows its of type OAuth2Client
};

I got the OAuth2Client type on inspecting the type of the returned auth2Client. The problem though is where to import it from and use it in the project.

I tried the following...

import { google, OAuth2Client } from 'googleapis';

That fails as googleapis has no such named export.

I also saw this approach from @corolla answer where he imports the types from google-auth-library

import { OAuth2Client } from 'google-auth-library';

I would wish to use the type without having to add another library as a dependency just for a single type for an already typed library (Much as googleapis uses types from google-auth-library under the hood, the project linter requires me to list it as a project dependency, which I wouldn't wish to do for now). Is there any other way I can go about this please.

Thank you.

Body:
I settled with just disabling the eslint warning for no-extraneous-dependencies.

// eslint-disable-next-line import/no-extraneous-dependencies
import { OAuth2Client } from 'google-auth-library';
import { google } from 'googleapis';

I couldn't specifically specify google-auth-library as a project dependency just to pick one type, yet under the hood, the googleapis package was also importing the types for the same package. So I wouldn't be breaking anything I guess.


问:
How to escape nested single quotes inside back tick or back quote
Let's say we have the following template literal in ES6.

```<code>`'{"0": "It's Friday today"}'`
</code>```

How do we escape the single quote in the word It's

Also, let's say we have the following template literal:

```<code>`'{"0": "Thursday\nFriday"}'`
</code>```

How do we escape the \n in the above.

答:
By default, you don't have to escape them.

If you want to parse it later, you can use a template tag function.

Template tag functions receive an unescaped string to allow further processing.

The String.raw tag function, for example, returns a string without parsing additional escapes:

console.log(String.raw `'{"0": "It\'s Friday today"}'`)
//       A single \ will do it ---^-----v
console.log(String.raw `'{"0": "Thursday\nFriday"}'`)```

Body:
Let's say we have the following template literal in ES6.

`'{"0": "It's Friday today"}'`

How do we escape the single quote in the word It's

Also, let's say we have the following template literal:

`'{"0": "Thursday\nFriday"}'`

How do we escape the \n in the above.


问:
Return Collection after update()?
Using Raw, how to return collection of updated row?

For example:

```<code>$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
</code>```

I was expecting dd($updated) to return updated row of collection but it returned 1.

```<code>{{$updated->votes}} should return 123
</code>```

答:
Try this</p>

```<code>$updated = tap(DB::table('users')->where('id', 1))
    ->update(['votes' => 123])
    ->first();

</code>```

Title: Return Collection after update()?

Body:
Using Raw, how to return collection of updated row?

For example:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

I was expecting dd($updated) to return updated row of collection but it returned 1.

{{$updated->votes}} should return 123

Body:
Try this

$updated = tap(DB::table('users')->where('id', 1))
    ->update(['votes' => 123])
    ->first();


问:
React native App having api calls - should I use redux?
I am starting to build an app in react native and it will be based on too many api calls example, it will have different options upon login for different users so it will be loaded totally based on apis.
Now, I have read about redux a little bit but not able to understand why and what will I benefit from using it in my project. Any directions.</p>

答: I did a lot of research on this, also considered other topics like hooks and state but turns out that this is one of the most recommended approach for writing large react native applications especially when lot of api calls are involved. Hope this helps!</p>


问:
What's the difference between data-th-text and th:text in Spring thymeleaf
I am new in spring thymeleaf and I am not able to get difference between these two data-th-text and th:text.

Can anyone explain the difference, with the help of examples, and when should I use data-th-text and th:text ?

答:
Both does the same thing but as per thymeleaf docs:

Non-standard attributes we are using in the th:* form are not allowed by the HTML5 specification. To make your templates HTML5-valid use data- prefix for attribute names and hyphen (-) separators instead of semi-colons (:)

Ref: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-texts

This is not HTML5 valid:

Welcome to our grocery store!

```

<p>This is HTML5 valid:</p>

<pre class="lang-html prettyprint-override"><code><p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>
</code>```

Body:
Both does the same thing but as per thymeleaf docs:

Non-standard attributes we are using in the th:* form are not allowed by the HTML5 specification. To make your templates HTML5-valid use data- prefix for attribute names and hyphen (-) separators instead of semi-colons (:)

Ref: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-texts

This is not HTML5 valid:

 <p th:text="#{home.welcome}">Welcome to our grocery store!</p>

This is HTML5 valid:

<p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>


问:
how to filter data from array and apply conditions angular8
I am getting below sample data from api dynamically.

Can anyone suggest how to apply condition based on data.

答:
as others have said here, you have to check values in the "providers" array. since you just need to check provider != 'All' you can simply check for the first element in the array as below.</p>

```<code>if (this.tagSchemaDetails.schema_context.providers[0] !== 'All') {
        request['schema_context'] = this.createConditionsData();
    }
</code>```

Body:
as others have said here, you have to check values in the "providers" array. since you just need to check provider != 'All' you can simply check for the first element in the array as below.

if (this.tagSchemaDetails.schema_context.providers[0] !== 'All') {
        request['schema_context'] = this.createConditionsData();
    }


问:
Embed MP4 in HTML using flash-player
Can I embed MP4-files streaming using a flash-player? I find several places it is mentioned, but some places also mention that flash-10 might be a requirement, it might now work well for streaming etc...

Are there any limitations I should be aware of - and which embeddable flash-player works well?

答: MP4 files need to be encoded or fixed using a utility or server code to be fast start - the header information at the beginning of the file rather than the end.</p>

ContentLicense: CC BY-SA 2.5

Title: Embed MP4 in HTML using flash-player


问:
Multiple axios requests with vue.js and Airtable
I build a working code to retrieve data from fake Airtable database with axios. You can see the code below perfectly working. No problem to retrieve data when is on the main table. Yet as you can assume some fields are connected to other tables (named in Airtable: parent child data or fields). Is the case in my table when you have the field "ORGANIZZAZIONE" (Organization) that is connected to another table having the organization datails as for example: NOME (Name) and TIPOLOGIA (Activity).
As you can see in the code when I try to access to this data (ORGANIZZAZIONE) I have bad results. Probably I have to build an "axios.all" request but I can't find the right way.

```<code>enter code here
</code>```

           new Vue({
                el: '#app',
                data: {
                  saluti:'Saluti da Mauro',
                    items: []
                },
                mounted: function(){
                   this.loadItems();
                },
                methods: {
                    loadItems: function(){

                        // Init variables
                        var self = this
                        var app_id = "apppCqmyJHPmfDTLr";
                        var app_key = "key8S2tx7NINXaZzZ";
                        this.items = []
axios.get(
  "https://api.airtable.com/v0/"+app_id+"/DASHBOARD?api_key="+app_key,

                            {
                                headers: { Authorization: "Bearer "+app_key }
                            }
                        ).then(function(response){
                            self.items = response.data.records
                        }).catch(function(error){
                            console.log(error)
                        })
                    }
                }
            })
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <head>
      <title>Airtable example</title>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    </head>
    <body>
      <h1>AIT</h1>
      <p>All work from <strong>Ryan Hayden</strong> | A basic introduction to the Airtable API.</p>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<div id="app">
            <h2>{{saluti}}</h2>
  <div class="container-fluid">

        <div class="card-body" v-for="item, index in items" :key:="items">
          <img src="https://www.artemedialab.it/wp-content/uploads/2019/04/immagini-sfondo-1-700x400.jpg" class="card-img-top" class="img-fluid" alt="MM" style="width: 18rem;">

              <div class="card text-BLACK bg-primary mb-3 text-right" style="width: 18rem;">
                <div class="card-header">

                    {{ index+1 }}
                </div>

                            <div class="card text-black bg-success mb-3" style="max-width: 18rem;">
                             <div class="card border-primary mb-1" style="max-width: 18rem;">
     <!-- lavorare su questo per approfondire la struttura su JSON
this.posts = response.data.data.map((post) => {
        return {id: post.id, title: post.attributes.title, body: post.attributes.body};
      }) -->

                    <p class="price"><strong>DATA INIZIO: </strong>{{ item['fields']['DATA INIZIO'] }}</p>
                     <p class="category"><strong>DETTAGLI ATTIVITA': </strong>{{ item['fields']["Attivita'"] }}</p>
                    <p class="category"><strong>PRIORITA': </strong>{{ item['fields']["PRIORITA'"] }}</p>
                               <p class="category"><strong>ORGANIZZAZIONE: </strong>{{ item['fields']['ORGANIZZAZIONE']}}</p>
                                <p class="category"><strong>ORGANIZZAZIONE / NOME: </strong>{{ item['fields']['ORGANIZZAZIONE']['Nome_Organizzazione']}}</p>
                               <p class="category"><strong>ORGANIZZAZIONE / TIPOLOGIA: </strong>{{ item['fields']['ORGANIZZAZIONE']['TIPOLOGIA']}}</p>
                    <img :src="item['fields']['Photo'][0]['thumbnails']['large']['url']" alt="" v-if="item['fields']['Photo']" width="150">

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

    </div>

    <!--app-->

        <!-- Include Dependancy Scripts -->
        <script type="text/javascript" src="https://unpkg.com/vue"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

    </body></code>```

答:
In your case, you need to call the api for each ORGANIZZAZIONE on your response, then append it. Here is an example with the first ORGANIZZAZIONE:

```<code>var app_id = "apppCqmyJHPmfDTLr";
var app_key = "key8S2tx7NINXaZzZ";
this.items = []
axios.get(
  "https://api.airtable.com/v0/" + app_id + "/DASHBOARD?api_key=" + app_key, {
    headers: {
      Authorization: "Bearer " + app_key
    }
  }
).then(function(response) {
  // here get ORGANIZZAZIONE for each record
  for (let record of response.data.records) {
    // here the first ORGANIZZAZIONE on array
    let ORGANIZZAZIONE = record.fields.ORGANIZZAZIONE[0];

    //call Airtable api again
    axios.get(
      "https://api.airtable.com/v0/" + app_id + "/DASHBOARD/" + ORGANIZZAZIONE + "?api_key=" + app_key, {
        headers: {
          Authorization: "Bearer " + app_key
        }
      }
    ).then(function(response2) {
      // Replace  ORGANIZZAZIONE on first response to the the data in response2
      record.fields.ORGANIZZAZIONE = response2.data.fields;
      this.items = response.data.records; // You can set each time is getted

    }).catch(function(error) {
      console.log(error)
    })
  }
}).catch(function(error) {
  console.log(error)
})
</code>```

codepen: https://codepen.io/hans-felix/pen/MWaNraL

Body:
I build a working code to retrieve data from fake Airtable database with axios. You can see the code below perfectly working. No problem to retrieve data when is on the main table. Yet as you can assume some fields are connected to other tables (named in Airtable: parent child data or fields). Is the case in my table when you have the field "ORGANIZZAZIONE" (Organization) that is connected to another table having the organization datails as for example: NOME (Name) and TIPOLOGIA (Activity).
As you can see in the code when I try to access to this data (ORGANIZZAZIONE) I have bad results. Probably I have to build an "axios.all" request but I can't find the right way.

enter code here

           new Vue({
                el: '#app',
                data: {
                  saluti:'Saluti da Mauro',
                    items: []
                },
                mounted: function(){
                   this.loadItems();
                },
                methods: {
                    loadItems: function(){

                        // Init variables
                        var self = this
                        var app_id = "apppCqmyJHPmfDTLr";
                        var app_key = "key8S2tx7NINXaZzZ";
                        this.items = []
axios.get(
  "https://api.airtable.com/v0/"+app_id+"/DASHBOARD?api_key="+app_key,

                            {
                                headers: { Authorization: "Bearer "+app_key }
                            }
                        ).then(function(response){
                            self.items = response.data.records
                        }).catch(function(error){
                            console.log(error)
                        })
                    }
                }
            })

      <title>Airtable example</title>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

AIT

All work from Ryan Hayden | A basic introduction to the Airtable API.

      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

{{saluti}}

                    {{ index+1 }}

DATA INIZIO: {{ item['fields']['DATA INIZIO'] }}

DETTAGLI ATTIVITA': {{ item['fields']["Attivita'"] }}

PRIORITA': {{ item['fields']["PRIORITA'"] }}

ORGANIZZAZIONE: {{ item['fields']['ORGANIZZAZIONE']}}

ORGANIZZAZIONE / NOME: {{ item['fields']['ORGANIZZAZIONE']['Nome_Organizzazione']}}

ORGANIZZAZIONE / TIPOLOGIA: {{ item['fields']['ORGANIZZAZIONE']['TIPOLOGIA']}}

Body:
In your case, you need to call the api for each ORGANIZZAZIONE on your response, then append it. Here is an example with the first ORGANIZZAZIONE:

var app_id = "apppCqmyJHPmfDTLr";
var app_key = "key8S2tx7NINXaZzZ";
this.items = []
axios.get(
  "https://api.airtable.com/v0/" + app_id + "/DASHBOARD?api_key=" + app_key, {
    headers: {
      Authorization: "Bearer " + app_key
    }
  }
).then(function(response) {
  // here get ORGANIZZAZIONE for each record
  for (let record of response.data.records) {
    // here the first ORGANIZZAZIONE on array
    let ORGANIZZAZIONE = record.fields.ORGANIZZAZIONE[0];

    //call Airtable api again
    axios.get(
      "https://api.airtable.com/v0/" + app_id + "/DASHBOARD/" + ORGANIZZAZIONE + "?api_key=" + app_key, {
        headers: {
          Authorization: "Bearer " + app_key
        }
      }
    ).then(function(response2) {
      // Replace  ORGANIZZAZIONE on first response to the the data in response2
      record.fields.ORGANIZZAZIONE = response2.data.fields;
      this.items = response.data.records; // You can set each time is getted

    }).catch(function(error) {
      console.log(error)
    })
  }
}).catch(function(error) {
  console.log(error)
})

codepen: https://codepen.io/hans-felix/pen/MWaNraL


问:
Mockito verify fails when method takes a function as argument
I have a Scala test which uses Mockito to verify that certain DataFrame transformations are invoked.   I broke it down to this simple problematic example

```<code>import org.apache.spark.sql.DataFrame
import org.scalatest.funsuite.AnyFunSuite
import org.apache.spark.sql.functions._
import org.mockito.{Mockito, MockitoSugar}

class SimpleTest extends  AnyFunSuite{

  def withGreeting(df: DataFrame):DataFrame = {
    df.withColumn("greeting", lit("hello"))
  }

  test("sample test") {
    val mockDF = MockitoSugar.mock[DataFrame]
    val mockDF2 = MockitoSugar.mock[DataFrame]
    MockitoSugar.doReturn(mockDF2).when(mockDF).transform(withGreeting)
    mockDF.transform(withGreeting)
    val orderVerifier = Mockito.inOrder(mockDF)
    orderVerifier.verify(mockDF).transform(withGreeting)
  }

}
</code>```

I'm trying to assert that the transform was called on my mockDF, but it fails with

```<code>Argument(s) are different! Wanted:
dataset.transform(<function1>);
-> at org.apache.spark.sql.Dataset.transform(Dataset.scala:2182)
Actual invocations have different arguments:
dataset.transform(<function1>);
</code>```

Why would the verify fail in this case?

答:
You need to save lambda expression argument for transform as val for correct testing and pass it to all transform calls:

```<code>def withGreeting(df: DataFrame):DataFrame = {
  df.withColumn("greeting", lit("hello"))
}

test("sample test") {
  val mockDF = MockitoSugar.mock[DataFrame]
  val mockDF2 = MockitoSugar.mock[DataFrame]
  val withGreetingExpression = df => withGreeting(df)
  MockitoSugar.doReturn(mockDF2).when(mockDF).transform(withGreetingExpression)
  mockDF.transform(withGreetingExpression)
  val orderVerifier = Mockito.inOrder(mockDF)
  orderVerifier.verify(mockDF).transform(withGreetingExpression)
}
</code>```

Mockito requires to provide same (or equal) arguments to the mocked functions calls. When you are passing lambda expression without saving each call transform(withGreeting) creates new object Function[DataFrame, DataFrame]

transform(withGreeting)

is the same as:

```<code>transform(new Function[DataFrame, DataFrame] {
  override def apply(df: DataFrame): DataFrame = withGreeting(df)
})
</code>```

And they aren't equal to each other - this is the cause of error message:
Argument(s) are different!

For example, try to execute:

```<code>println(((df: DataFrame) => withGreeting(df)) == ((df: DataFrame) => withGreeting(df))) //false
</code>```

You can read more about objects equality in java (in the scala it's same):

wikibooks

javaworld.com

Body:
I have a Scala test which uses Mockito to verify that certain DataFrame transformations are invoked.   I broke it down to this simple problematic example

import org.apache.spark.sql.DataFrame
import org.scalatest.funsuite.AnyFunSuite
import org.apache.spark.sql.functions._
import org.mockito.{Mockito, MockitoSugar}

class SimpleTest extends  AnyFunSuite{

  def withGreeting(df: DataFrame):DataFrame = {
    df.withColumn("greeting", lit("hello"))
  }

  test("sample test") {
    val mockDF = MockitoSugar.mock[DataFrame]
    val mockDF2 = MockitoSugar.mock[DataFrame]
    MockitoSugar.doReturn(mockDF2).when(mockDF).transform(withGreeting)
    mockDF.transform(withGreeting)
    val orderVerifier = Mockito.inOrder(mockDF)
    orderVerifier.verify(mockDF).transform(withGreeting)
  }

}

I'm trying to assert that the transform was called on my mockDF, but it fails with

Argument(s) are different! Wanted:
dataset.transform(<function1>);
-> at org.apache.spark.sql.Dataset.transform(Dataset.scala:2182)
Actual invocations have different arguments:
dataset.transform(<function1>);

Why would the verify fail in this case?

Body:
You need to save lambda expression argument for transform as val for correct testing and pass it to all transform calls:

def withGreeting(df: DataFrame):DataFrame = {
  df.withColumn("greeting", lit("hello"))
}

test("sample test") {
  val mockDF = MockitoSugar.mock[DataFrame]
  val mockDF2 = MockitoSugar.mock[DataFrame]
  val withGreetingExpression = df => withGreeting(df)
  MockitoSugar.doReturn(mockDF2).when(mockDF).transform(withGreetingExpression)
  mockDF.transform(withGreetingExpression)
  val orderVerifier = Mockito.inOrder(mockDF)
  orderVerifier.verify(mockDF).transform(withGreetingExpression)
}

Mockito requires to provide same (or equal) arguments to the mocked functions calls. When you are passing lambda expression without saving each call transform(withGreeting) creates new object Function[DataFrame, DataFrame]

transform(withGreeting)

is the same as:

transform(new Function[DataFrame, DataFrame] {
  override def apply(df: DataFrame): DataFrame = withGreeting(df)
})

And they aren't equal to each other - this is the cause of error message:
Argument(s) are different!

For example, try to execute:

println(((df: DataFrame) => withGreeting(df)) == ((df: DataFrame) => withGreeting(df))) //false

You can read more about objects equality in java (in the scala it's same):

wikibooks

javaworld.com


问:
HTML width at 100% overflowing
I am trying to set the width of a container to 100% of the page. By itself it seems to be fine, but once I add another
 element in the container, it overflows and the page becomes scrollable. I don't know what's wrong, because I haven't changed the padding and margin settings.

EDIT: the issue only seems to happen on chrome.

EDIT #2: Some people told me that they were not experiencing the same issue on their end, so I uploaded the project files and a screenshot of what I see on my google drive:

Project files

/* this is my css: */

body {
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  background-color: steelblue;
}

#mainContainer {
  width: 100%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.genContainer {
  width: 50%;
  display: flex;
  justify-content: center;
}

.square {
  width: 5%;
  border: 1px solid black;
}

.circle {
  width: 5%;
  border: 1px solid black;
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="mainContainer">

    <div class="genContainer">

      <div class="person square"></div>

    </div>

  </div>
</body></code>```

Thank you!

答:
Change this:

```<code>#mainContainer {
    width: 100%;
    border: 1px solid black;
    display: flex;
    justify-content: center;
    flex-direction: column;
}
</code>```

To this:

```<code>#mainContainer {
    max-width: 100%; /*This limits the container to be 100% regardless of what's within it*/
    border: 1px solid black;
    display: flex;
    justify-content: center;
    flex-direction: column;
}
</code>```

Title: HTML width at 100% overflowing

Body:
I am trying to set the width of a container to 100% of the page. By itself it seems to be fine, but once I add another
 element in the container, it overflows and the page becomes scrollable. I don't know what's wrong, because I haven't changed the padding and margin settings.

EDIT: the issue only seems to happen on chrome.

EDIT #2: Some people told me that they were not experiencing the same issue on their end, so I uploaded the project files and a screenshot of what I see on my google drive:

Project files

/* this is my css: */

body {
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  background-color: steelblue;
}

#mainContainer {
  width: 100%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.genContainer {
  width: 50%;
  display: flex;
  justify-content: center;
}

.square {
  width: 5%;
  border: 1px solid black;
}

.circle {
  width: 5%;
  border: 1px solid black;
  border-radius: 50%;
}

Thank you!

Body:
Change this:

#mainContainer {
    width: 100%;
    border: 1px solid black;
    display: flex;
    justify-content: center;
    flex-direction: column;
}

To this:

#mainContainer {
    max-width: 100%; /*This limits the container to be 100% regardless of what's within it*/
    border: 1px solid black;
    display: flex;
    justify-content: center;
    flex-direction: column;
}


问:
Error received: [SSL: BAD_LENGTH] bad length (_ssl.c:2408)
I made a game that can be controlled with voice command. To convert all the voice command into text I used IBM Cloud Speech to Text service. Everything is done except it is showing me the BAD LENGTH ERROR as you can see in the image.

This is the code for speech to text:

```<code>###############################################
#### Initalize queue to store the recordings ##
###############################################
CHUNK = 1024
# Note: It will discard if the websocket client can't consumme fast enough
# So, increase the max size as per your choice
BUF_MAX_SIZE = CHUNK * 10
# Buffer to store audio
q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK)))

# Create an instance of AudioSource
audio_source = AudioSource(q, True, True)

###############################################
#### Prepare Speech to Text Service ########
###############################################

# initialize speech to text service
authenticator = IAMAuthenticator('i3gkxvESZRUHnt0_Iv2PtMQaHd2roF1YgvTTIzq0tbop')
speech_to_text = SpeechToTextV1(authenticator=authenticator)
speech_to_text.set_service_url("https://api.eu-gb.speech-to-
text.watson.cloud.ibm.com/instances/54f44656-b15c-4a16-8dac-c5b782482f93")

actions = []
</code>```

答:
I got that error solved by just uninstalling all the packages and reinstalling the required one.
It will simply run successfully by just that and even if you receive that error in the future, try doing this process again. It will work.
Apart from this, I was not been able to find any other solution.</p>

Body:
I made a game that can be controlled with voice command. To convert all the voice command into text I used IBM Cloud Speech to Text service. Everything is done except it is showing me the BAD LENGTH ERROR as you can see in the image.

This is the code for speech to text:

###############################################
#### Initalize queue to store the recordings ##
###############################################
CHUNK = 1024
# Note: It will discard if the websocket client can't consumme fast enough
# So, increase the max size as per your choice
BUF_MAX_SIZE = CHUNK * 10
# Buffer to store audio
q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK)))

# Create an instance of AudioSource
audio_source = AudioSource(q, True, True)

###############################################
#### Prepare Speech to Text Service ########
###############################################

# initialize speech to text service
authenticator = IAMAuthenticator('i3gkxvESZRUHnt0_Iv2PtMQaHd2roF1YgvTTIzq0tbop')
speech_to_text = SpeechToTextV1(authenticator=authenticator)
speech_to_text.set_service_url("https://api.eu-gb.speech-to-
text.watson.cloud.ibm.com/instances/54f44656-b15c-4a16-8dac-c5b782482f93")

actions = []


问:
How to get a hyperlink on a web page to open a file in a text editor (Sublime Text)
I'm working on a large static website (Jekyll) and would like to be able to click on a link on a page in browser (Chrome) which will open it's corresponding source file on the local machine (Sublime). I can get the absolute link of the file.

From the console (Ubuntu) I can do:

```<code>subl path/to/file.txt
</code>```

to open a file, so perhaps an extension that allows command execution on trusted domains?

答:
Ubuntu
There is a solution for Ubuntu

Windows Method

You first have to install a Protocol Handler in the Windows registry.
(Reference:
Custom protocol handler in chrome)

This will get Chrome to run a command when a subl:path/to/file link is clicked.
But you can't simply run sublime_text.exe subl:path/to/file, because Sublime doesn't understand the subl:path/to/file parameter. You first have to extract the filename with a script and then call Sublime with a single file parameter.

Solution 1

This is a Solution for Windows, that opens links with the format

```<code>subl://open?url=file://<path_to_file>&line=4
</code>```

It first registers a Script as a Protocol Handler, which in turn calls Sublime

Solution 2

I edited Solution 1 to open links in the format

```<code>subl://path/to/file:line
</code>```

Just follow Solution 1, but change open_file.vbs to:

```<code>' path to sublime_text.exe
Dim sublime_path
' CHANGE THIS:
sublime_path = "C:\Programme\Sublime Text 3\sublime_text.exe"

Dim text, filename
' get first command line argument
text = WScript.Arguments.Item(0)

filename  = Split(text, ":/")(1)

Dim run_command
run_command = """"&sublime_path&""" """&filename&""""

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(run_command)
Set objShell = Nothing
</code>```

(You have to change the path to your sublime_text.exe)

Mac
https://github.com/corysimmons/subl-handler

Body:
I'm working on a large static website (Jekyll) and would like to be able to click on a link on a page in browser (Chrome) which will open it's corresponding source file on the local machine (Sublime). I can get the absolute link of the file.

From the console (Ubuntu) I can do:

subl path/to/file.txt

to open a file, so perhaps an extension that allows command execution on trusted domains?

Body:
Ubuntu
There is a solution for Ubuntu

Windows Method

You first have to install a Protocol Handler in the Windows registry.
(Reference:
Custom protocol handler in chrome)

This will get Chrome to run a command when a subl:path/to/file link is clicked.
But you can't simply run sublime_text.exe subl:path/to/file, because Sublime doesn't understand the subl:path/to/file parameter. You first have to extract the filename with a script and then call Sublime with a single file parameter.

Solution 1

This is a Solution for Windows, that opens links with the format

subl://open?url=file://<path_to_file>&line=4

It first registers a Script as a Protocol Handler, which in turn calls Sublime

Solution 2

I edited Solution 1 to open links in the format

subl://path/to/file:line

Just follow Solution 1, but change open_file.vbs to:

' path to sublime_text.exe
Dim sublime_path
' CHANGE THIS:
sublime_path = "C:\Programme\Sublime Text 3\sublime_text.exe"

Dim text, filename
' get first command line argument
text = WScript.Arguments.Item(0)

filename  = Split(text, ":/")(1)

Dim run_command
run_command = """"&sublime_path&""" """&filename&""""

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(run_command)
Set objShell = Nothing

(You have to change the path to your sublime_text.exe)

Mac
https://github.com/corysimmons/subl-handler


问:
How to close a file handle opened with SHCreateStreamOnFile
Since I need to format "pretty" XML using MSXML, I am using the trick referenced here to add indentation to my code. Since all I want is to save a file, I open an IStream using SHCreateStreamOnFile(). The file gets saved, I can open it in a text editor and the XML content is there. Then I call Release() on the IStream interface so that the IStream and the file handle get closed.

Or so I tought, however Process Explorer tell me that my process still has a reference to my file once my save function exits (despite the release). I tried calling Release() a second time, but still no result, the handle doesn't get closed. All Google and MSDN could tell me was that I should call Release... But it isn't clear if Release() releases only the COM object or the file handle also.

So, is there a special way to force the close of a file handle created by SHCreateStreamOnFile()? Or is there a better way to obtain an IStream on a file? Do I need to call Release() on the IMXWriter, ISAXXMLReader and IStream in a specific order?

Thank you in advance.

答:
ildjarn was right, I was passing it to an object that didn't get deleted, because I didn't knew that QueryInterface incremented the reference count ( I tought it was kind of a "COM" way of casting a pointer ). Releasing that object released the file at the same time.

A beginner mistake from someone not used to COM programming.


问:
Clear status doesn't work with status=None
I am writing a short command that will let me set my status to anything I want but I read the documentation and there is no way to clear the status. The only thing I found was a discussion from 3 years ago which does not work

Here is my attempt:

```<code>@bot.command()
    async def statc(c):
        print(f"Works")
        await bot.change_presence(status=None)
</code>```

答:
According to the documentation, you can set status=None, to quote the docs "If [status] None, then Status.online is used." which is the default (/clear) state.

```<code>import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>')

@bot.command()
async def stati(ctx):
    await bot.change_presence(status=discord.Status.idle)

@bot.command()
async def statc(c):
    await bot.change_presence(status=None)

bot.run('app token')
</code>```

Body:
I am writing a short command that will let me set my status to anything I want but I read the documentation and there is no way to clear the status. The only thing I found was a discussion from 3 years ago which does not work

Here is my attempt:

@bot.command()
    async def statc(c):
        print(f"Works")
        await bot.change_presence(status=None)

Body:
According to the documentation, you can set status=None, to quote the docs "If [status] None, then Status.online is used." which is the default (/clear) state.

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>')

@bot.command()
async def stati(ctx):
    await bot.change_presence(status=discord.Status.idle)

@bot.command()
async def statc(c):
    await bot.change_presence(status=None)

bot.run('app token')


问:
How implement SFINAE limited to few types, using template parameter pack
I need enable std::string and int, but using a parameter pack.

```<code>template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{

}
</code>```

but i have errors when call

```<code>Log("hello"s, "world"s); //syntax ERROR
</code>```

Desired result

```<code>Log(4,3,"Hello"s); //OK
Log("Hello"s); //OK
Log(5); //OK
</code>```

答:
In c++17 using fold-expressions:

```<code>#include <type_traits>

template <typename... ParamType>
static inline auto Log(const ParamType&... args)
    -> std::enable_if_t<((std::is_same_v<ParamType, std::string>
                       || std::is_same_v<ParamType, int>) && ...)>
{
}
</code>```

However, if there's no alternative overload of Log, that could be used for parameters that do not satisfy the condition, consider using static_assert instead to provide an informative error message:

```<code>template <typename... ParamType>
static inline void Log(const ParamType&... args)
{
    static_assert(((std::is_same_v<ParamType, std::string>
                 || std::is_same_v<ParamType, int>) && ...)
                  , "Only ints and strings");
}
</code>```

In c++20 using concepts:

```<code>#include <type_traits>

template <typename T>
concept LogParam = std::is_same_v<T, std::string> || std::is_same_v<T, int>;

static inline void Log(const LogParam auto&... args)
{
}
</code>```

Body:
I need enable std::string and int, but using a parameter pack.

template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{

}

but i have errors when call

Log("hello"s, "world"s); //syntax ERROR

Desired result

Log(4,3,"Hello"s); //OK
Log("Hello"s); //OK
Log(5); //OK

Body:
In c++17 using fold-expressions:

#include <type_traits>

template <typename... ParamType>
static inline auto Log(const ParamType&... args)
    -> std::enable_if_t<((std::is_same_v<ParamType, std::string>
                       || std::is_same_v<ParamType, int>) && ...)>
{
}

However, if there's no alternative overload of Log, that could be used for parameters that do not satisfy the condition, consider using static_assert instead to provide an informative error message:

template <typename... ParamType>
static inline void Log(const ParamType&... args)
{
    static_assert(((std::is_same_v<ParamType, std::string>
                 || std::is_same_v<ParamType, int>) && ...)
                  , "Only ints and strings");
}

In c++20 using concepts:

#include <type_traits>

template <typename T>
concept LogParam = std::is_same_v<T, std::string> || std::is_same_v<T, int>;

static inline void Log(const LogParam auto&... args)
{
}