问:
How To Change The Bottom Line EditText Color?
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

```<code>AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();
</code>```

For some weird reason that is not working, setHightlightColor should be it.

答: Under the xml file put it this way into ur EditText: app:backgroundTint="@color/black"

Body:
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();

For some weird reason that is not working, setHightlightColor should be it.


来源: stackexchange

问:
How to group contents in an array of dictionary?
I know this could have been solved easily from backend but was curious to know if there is any efficient way to solve this issue from front end using js.

I have an array

```<code>[
 {
    id: 11
    ruleDesc: "rule 1 "
 },
{
    id: 15
    ruleDesc: "rule 2 "
 },
{
    id: 12
    ruleDesc: "rule 3 "
 },
{
    id: 11
    ruleDesc: "rule 4 "
 },
{
    id: 11
    ruleDesc: "rule 5 "
 },

]
</code>```

What I'm expecting is

```<code>[
  {
        id: 11
        ruleDesc: "rule 1 "
        ruleDesc: "rule 4 "
        ruleDesc: "rule 5 "
     },
{
        id: 12
        ruleDesc: "rule 3 "
     },
{
        id: 15
        ruleDesc: "rule 2 "
     },
]
</code>```

答:
You need to create an array of ruleDesc for same group. Because an object can't have same keys.

You can use reduce() to get an object and then use Object.values to get an array.

const arr = [ { id: 11, ruleDesc: "rule 1 " }, { id: 15, ruleDesc: "rule 2 " }, { id: 12, ruleDesc: "rule 3 " }, { id: 11, ruleDesc: "rule 4 " }, { id: 11, ruleDesc: "rule 5 " } ]

const res = arr.reduce((ac,{id,ruleDesc}) => {
  ac[id] = ac[id] || {id,ruleDesc:[]}
  ac[id].ruleDesc.push(ruleDesc);
  return ac;
},{})
console.log(Object.values(res))```

ContentLicense: CC BY-SA 4.0

Body:
I know this could have been solved easily from backend but was curious to know if there is any efficient way to solve this issue from front end using js.

I have an array

[
 {
    id: 11
    ruleDesc: "rule 1 "
 },
{
    id: 15
    ruleDesc: "rule 2 "
 },
{
    id: 12
    ruleDesc: "rule 3 "
 },
{
    id: 11
    ruleDesc: "rule 4 "
 },
{
    id: 11
    ruleDesc: "rule 5 "
 },

]

What I'm expecting is

[
  {
        id: 11
        ruleDesc: "rule 1 "
        ruleDesc: "rule 4 "
        ruleDesc: "rule 5 "
     },
{
        id: 12
        ruleDesc: "rule 3 "
     },
{
        id: 15
        ruleDesc: "rule 2 "
     },
]


问:
Creating Bash Array with Multiple Elements
Very simple bash problem. I have an array that look like:

```<code>my_array=(1 2 3)
</code>```

However, when I print the array or loop through it, bash only refers to the first element.

```<code>echo $my_array
1

for element in my_array ; do
    echo $element
done
1
</code>```

How can I access all the elements?

答:
You need to use the proper syntax. To display all the elements, use

```<code>for element in "${my_array[@]}" ; do
    printf '%s\n' "$element"
done
</code>```

$my_array is the same as ${my_array[0]}.

Also, the loop in the original question outputs my_array, not 1. Without a $, it's not a variable, it's just a word.

Body:
Very simple bash problem. I have an array that look like:

my_array=(1 2 3)

However, when I print the array or loop through it, bash only refers to the first element.

echo $my_array
1

for element in my_array ; do
    echo $element
done
1

How can I access all the elements?

Body:
You need to use the proper syntax. To display all the elements, use

for element in "${my_array[@]}" ; do
    printf '%s\n' "$element"
done

$my_array is the same as ${my_array[0]}.

Also, the loop in the original question outputs my_array, not 1. Without a $, it's not a variable, it's just a word.


问:
Unable to register external kubernetes cluster with GKE
I'm trying to set up a multi-cloud deployment using GKE as a single plain of glass for cluster management. Unfortunately, I can't see "Register cluster" option within GKE. I can create a cluster, I can delete a cluster, I can deploy a workload to a cluster, but the option with registering the new cluster is not available for me.

I'm not using the free tier and I'm not within an Organisation also.

Could somebody help me to figure out why it is so? I could not find the solution digging through GCP documentation.

Thank you in advance

答:
I think what you are looking for is Anthos. It has a unified user interface and in the Anthos for operations section of the documentation it says:

Single pane of glass visibility across all clusters ...

But the link to the documentation to register a cluster gives me a 404.... I would suggest reaching out to Google Cloud Support to see if they can help you.

edit: It turns out that you need to be an Anthos customer to access the both the feature and the documentation for the feature.


问:
Caught exception is null itself !
I have an ASP.NET applications. Everything was fine, but recently I get exceptions that are null themselves:

```<code>try
{
    // do something
}
catch (Exception ex)
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}
</code>```

Sometimes ex is null itself !

Any idea?

答:
That cannot happen.

If you throw null, you'll get a NullReferenceException from the throw; the exception in the catch block can never be null.

You have something else that's null.

ContentLicense: CC BY-SA 3.0

Title: Caught exception is null itself !

Body:
I have an ASP.NET applications. Everything was fine, but recently I get exceptions that are null themselves:

try
{
    // do something
}
catch (Exception ex)
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}

Sometimes ex is null itself !

Any idea?


问:
How expensive is os.Getenv?
I have a piece of code that's called every few seconds and makes use of an environment variable:

for {
    myVar := os.Getenv("MY_VAR")
    //Do something
    time.Sleep(3 * time.Second)
}
```

<p>But how costly are repeat calls to <code>os.Getenv</code>?</p>

<p>The value of the environment variable will not change during runtime, so I could set it as a package level variable:</p>

<pre class="lang-golang prettyprint-override"><code>package blah

var myVar = os.Getenv("MY_VAR")
</code>```

But this does hurt testability of the code.

Should I set it as a package level variable? Or is os.Getenv benign enough?

EDIT:
I've benchmarked the call to os.Getenv but is it reliable?

package main_test

import (
    "os"
    "testing"
)

var result string

func BenchmarkEnv(b *testing.B) {
    var r string
    for n := 0; n < b.N; n++ {
        r = os.Getenv("PATH")
    }
    result = r
}
```

<pre class="lang-sh prettyprint-override"><code>goos: darwin
goarch: amd64
BenchmarkEnv-8      20000000            78.7 ns/op
PASS
</code>```

答:
You can benchmark os.Getenv and see how fast it is.

By looking at its implementation here, it costs:

A read-lock;

Lookup in global map;

Linear search of char '='.

Title: How expensive is os.Getenv?

Body:
I have a piece of code that's called every few seconds and makes use of an environment variable:

for {
    myVar := os.Getenv("MY_VAR")
    //Do something
    time.Sleep(3 * time.Second)
}

But how costly are repeat calls to os.Getenv?

The value of the environment variable will not change during runtime, so I could set it as a package level variable:

package blah

var myVar = os.Getenv("MY_VAR")

But this does hurt testability of the code.

Should I set it as a package level variable? Or is os.Getenv benign enough?

EDIT:
I've benchmarked the call to os.Getenv but is it reliable?

package main_test

import (
    "os"
    "testing"
)

var result string

func BenchmarkEnv(b *testing.B) {
    var r string
    for n := 0; n < b.N; n++ {
        r = os.Getenv("PATH")
    }
    result = r
}

goos: darwin
goarch: amd64
BenchmarkEnv-8      20000000            78.7 ns/op
PASS


问:
User delta query confusion
When using the deltaLink retrieved from a request to the users/delta endpoint on the v1.0 Microsoft graph API, do subsequent requests (using the deltaLink) returned from each previous request return changes since the initial request, or from the last request?

I am confused as to what the intended scenario is for the endpoint.  Is the token a long-lived thing, that you use in your application for a while to keep reusing to track changes from some initial sync, or is it a temporary method to see changes between two points in time, and then the token is discarded?

Right now it appears to "accumulate" changes since the token was created, which I guess makes sense, but if left to live for a long time would requests would potentially accumulate a lot of changes.

答:
When you call a deltaLink, it returns everything that has changed since that deltaLink token was issued. The results will also include a new deltaLink token that you use for your next poll of the system.

In other words, it is similar to the source code control systems like Git work. When you execute git pull, it looks at last commit in your local repository and then pulls down all of the changes that have occurred since that commit. In this example, Git's commit id is the delta token.

For example, you can start syncing Users "from now" using this query:

```<code>https://graph.microsoft.com/v1.0/users/delta
</code>```

The results will look something like this:

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",
    "@odata.deltaLink": "https://graph.microsoft.com/v1.0/users/delta?$deltatoken=4Pqov5cPSZPKjBZh-vGbekLcJ2oUTc1kzqA0XhF-lJrEmf3B2i-HyS72r9jBIqHuZUzdMopk5VyHnAI6_qh59FjavhOmaTmQW4JPL2bLKu5LpQ3m_zMSsp6M3Os03KOgaeay0zwAa08QefM1ArkZzkB_pUmZyV6MIS1eN7JHnBOgotBPFyPb-dnjAcheWE9W0HkUR87kf3jsuA4Ja4QTRnN3Hj_4eYdzoYxLWi54Aq2bHWTbDlPtl76M8Bhw8jiq37Y4R-G7G0eZNuRt43CBY0l3XliXXR5Ubi4ZUGApDAGVSPNc_VdHV4H3nbaB5qvwZZ7tAfqZB0-06-ZI-a0y2hxAPJLnI-iTB2PXdqxnaZn4f26k0khW52C57czh9KOjfE3nYV6pwEDFRFu-qj4062eMQwo2H6yoCLysv-C-XIOK3nDTaR3BPDOPGqNbnZkmB33-MXe9gcCPojAoU9ql95Z9de5QPnqezWVfBhXj_sRv3RlQQfCkGJHg3ZTVkdA475xJuHOhy2po38KlT3FmN0rzg0jOjvfPyTGrRI24C58ushGouckqHcCQllr4Dby9ECsPjVcNFEklSddjllaRMOkpUilecEdHnxsy0zH60bKkc2-6fcUvYuya8y4-7IySvbpk241ldxvoO9EQpDnUCdh3GgxKnYNuLtOiqiGdYVgGgTJa-iBQ1xVghcpsEMD9NqrByB3mSmy9rRKN3WP_C_HQBnEpV7Z3dvu-8ZxewMEhEObhhv8H_15msP4Bm6KvfuO-0EyNaMy_OXvGKpdkczSVQsdZ4jDmsAw_itqqtZmNoa3URjxjt0KAYNo9IrBXBx9yUGt6K_sY1xybfLxwBYOGOaV7zNd7XFaVXL8OM1hG2JGF0H4dM33uppuX5pWrrU0NBDcf9nbNkJf53fec-R1aX9BmEaAtv2xblxL75Kl0j8JKay2iBM7JaebqbGaZV6es9HUVFCIB6mxcNVDmR55U2Tel_D1TZ44eOwoZtvZvLPdQvQKuDYnwM1Yt9JJWXiGKigKi515UBPI52jhSnL1cY8VFnVDz4b81WgaRESSPipzC7fixQ94lvSaQ1MqJXRoWcm3LnjBMb7Z_aF4H_OFJNrGW-v8O__ZozNHUq04-v7rScKu3Cu64bISp1Z18DUeuRn9_Nc3vhXwhi2YlXxsX0mn-iKYjlGgE8MFSkcChpbtFLN3Wejublt3wlZ4yHQhySLDxFkgiA95BZLEXhdyVbfTzdW9cCUf9beltUT8qgcoLGH4lGdo2qjZqmUOZ8vfbPYCiExmOkN0qazvkGUs-VOcl37sccB2VEgqWodzy_Haq9HJJgAhFt_GeuL9VG58cPZPfKi0Q6DImdBE3p7NC36VvpgTbmz7G8N2V_BV8HC7e1lTiaLBkxXMEgcn_Uzl2gqPqc3CJxd3gTm7Z6MxgQXFZynwTXxo1CXSoSuLhMaND79EBrLOa11vd8aYmDwl5xuAXJZ7hZ0fVAuYe9JEUE2BvJYgBUijNi7ug8-_E73kcRQL5K2KbdTtUZRqFDxEnOBpC1adc1Pn633gC18z6Itzy5j6IXlutTBdlrAM-urzcxHX364VhnXwtWhLSEhB0xnBj-PejvfdzyuC3hTW6cLI-CttpgH-oMNDcrweeCB8NGOJYyxwFsYDZ9X3fwDYEhIwhUwdJOqG_10KJYVaRLUvdhgTkaEQdeRrJc2fyyDXAhJ7aIkr0PNy0ue1yn346cypSZw8BRAx6i3d4BTKgCxwnOqK8x6iMOb1Ad2IomKHoxH1_PkPIgMEz1mDcfipvG1IImuMj333wNe8tbPuPBsmQq-t-4GF4mH3sQkvt3pMdcnb4ITqLaZ5xR5Hxbyig6bENFyMR_5w_Q3LugXIIRknWB21jxWbcMOY1ggaYZno-MBFA2ueFDox8ImN4A9orD-8XpgbSqywqv5dnh4rCDoate27oMkz8NEGW6UdZUOSBrC0k91FKO2yHUa8KDA3tTKMIgDU-ynS0hOzfc_4cUICDpQJJOv2tXsWigkuVshJc-1733CXF3ptA8llB9dFPt6_-oWKAjxvHRq6_X8mX2Siz9D2kTXpfUS-AKmEpKcphNWzpIg5K8iKMy-xB_insLCYbkjFkxU5Q6-VnjS6KRolOXaRSejh2faVxFbgIFrOP6Ns5inBJZUemAPV7TTxY_RIGh3f4nMbzxU2P5doyYP7wTr_aiLDw1uJrDxjXRLPzLseS1uizlLpZMPw-QIAUARFyUzj7k4U9bzXoX_9URA5acvETVZOebdUbR3kCOOoBMmbdELX7uUkICPu_T0fsbGLAKA4wZSIIYdqCUydMQk9NofgvE28v-NB2g4-fFPuFANn0H4b0ktFrBT8wUO61ElrnwsL1tLyx6kP4s1y6OaH_ARTpb9StCkcvbO2bh4HYLj09xnxgbx_4RPUI6cag6mjCRhNTIipj3feZ0pBEVlL7NiTavSV2Ho2gGJujurYSE4cdF-Gjtraeulj0ur1buEwVQX8LbLWbO76X4cQLhE7G2Yf7GV8tjW2DX4TdG9yRciPaBntE0Imxe6IKZnSEEyqXMsZIRWLBfI3WIiVka-QD9lJlPZAdkNMb5VqQxyqruiCZ3nK-R7njc1EoVDejJEDOGyAljhF_kvcxsd_Hu0G8QHi0JtXXm8Tm9hH1O7EtEIDQAHR0tt6ihHixK2IYdfmoe3EIHJ_VmlC37RqTHf2ru2FgkoutuNLII9tYsMhWEEin-tgFwdCvUA0ONHytNY2I0EFKkx56t9JGoupL-lwpnhtnqpnVAPAgAk93D01fBz2NSNlXs_z3E8SOmXud35RNCG62i_nmzHICz_WRwKMHEbqelSst9U2h5FY.uzRUQfIEYUBmAFBUnNWTJn2yfL9toRZ2_VNuoRrA7jg",
    "value": []
}
</code>```

The value of @odata.delaLink is a URI that points to the state of Users as of the specific moment in time the URI was generated. If nothing has changed and you follow @odata.delaLink, you will receive an empty data set and a new URI. If you then add a new User, calling the deltaLink would return only that new user.

Title: User delta query confusion

Body:
When you call a deltaLink, it returns everything that has changed since that deltaLink token was issued. The results will also include a new deltaLink token that you use for your next poll of the system.

In other words, it is similar to the source code control systems like Git work. When you execute git pull, it looks at last commit in your local repository and then pulls down all of the changes that have occurred since that commit. In this example, Git's commit id is the delta token.

For example, you can start syncing Users "from now" using this query:

https://graph.microsoft.com/v1.0/users/delta

The results will look something like this:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",
    "@odata.deltaLink": "https://graph.microsoft.com/v1.0/users/delta?$deltatoken=4Pqov5cPSZPKjBZh-vGbekLcJ2oUTc1kzqA0XhF-lJrEmf3B2i-HyS72r9jBIqHuZUzdMopk5VyHnAI6_qh59FjavhOmaTmQW4JPL2bLKu5LpQ3m_zMSsp6M3Os03KOgaeay0zwAa08QefM1ArkZzkB_pUmZyV6MIS1eN7JHnBOgotBPFyPb-dnjAcheWE9W0HkUR87kf3jsuA4Ja4QTRnN3Hj_4eYdzoYxLWi54Aq2bHWTbDlPtl76M8Bhw8jiq37Y4R-G7G0eZNuRt43CBY0l3XliXXR5Ubi4ZUGApDAGVSPNc_VdHV4H3nbaB5qvwZZ7tAfqZB0-06-ZI-a0y2hxAPJLnI-iTB2PXdqxnaZn4f26k0khW52C57czh9KOjfE3nYV6pwEDFRFu-qj4062eMQwo2H6yoCLysv-C-XIOK3nDTaR3BPDOPGqNbnZkmB33-MXe9gcCPojAoU9ql95Z9de5QPnqezWVfBhXj_sRv3RlQQfCkGJHg3ZTVkdA475xJuHOhy2po38KlT3FmN0rzg0jOjvfPyTGrRI24C58ushGouckqHcCQllr4Dby9ECsPjVcNFEklSddjllaRMOkpUilecEdHnxsy0zH60bKkc2-6fcUvYuya8y4-7IySvbpk241ldxvoO9EQpDnUCdh3GgxKnYNuLtOiqiGdYVgGgTJa-iBQ1xVghcpsEMD9NqrByB3mSmy9rRKN3WP_C_HQBnEpV7Z3dvu-8ZxewMEhEObhhv8H_15msP4Bm6KvfuO-0EyNaMy_OXvGKpdkczSVQsdZ4jDmsAw_itqqtZmNoa3URjxjt0KAYNo9IrBXBx9yUGt6K_sY1xybfLxwBYOGOaV7zNd7XFaVXL8OM1hG2JGF0H4dM33uppuX5pWrrU0NBDcf9nbNkJf53fec-R1aX9BmEaAtv2xblxL75Kl0j8JKay2iBM7JaebqbGaZV6es9HUVFCIB6mxcNVDmR55U2Tel_D1TZ44eOwoZtvZvLPdQvQKuDYnwM1Yt9JJWXiGKigKi515UBPI52jhSnL1cY8VFnVDz4b81WgaRESSPipzC7fixQ94lvSaQ1MqJXRoWcm3LnjBMb7Z_aF4H_OFJNrGW-v8O__ZozNHUq04-v7rScKu3Cu64bISp1Z18DUeuRn9_Nc3vhXwhi2YlXxsX0mn-iKYjlGgE8MFSkcChpbtFLN3Wejublt3wlZ4yHQhySLDxFkgiA95BZLEXhdyVbfTzdW9cCUf9beltUT8qgcoLGH4lGdo2qjZqmUOZ8vfbPYCiExmOkN0qazvkGUs-VOcl37sccB2VEgqWodzy_Haq9HJJgAhFt_GeuL9VG58cPZPfKi0Q6DImdBE3p7NC36VvpgTbmz7G8N2V_BV8HC7e1lTiaLBkxXMEgcn_Uzl2gqPqc3CJxd3gTm7Z6MxgQXFZynwTXxo1CXSoSuLhMaND79EBrLOa11vd8aYmDwl5xuAXJZ7hZ0fVAuYe9JEUE2BvJYgBUijNi7ug8-_E73kcRQL5K2KbdTtUZRqFDxEnOBpC1adc1Pn633gC18z6Itzy5j6IXlutTBdlrAM-urzcxHX364VhnXwtWhLSEhB0xnBj-PejvfdzyuC3hTW6cLI-CttpgH-oMNDcrweeCB8NGOJYyxwFsYDZ9X3fwDYEhIwhUwdJOqG_10KJYVaRLUvdhgTkaEQdeRrJc2fyyDXAhJ7aIkr0PNy0ue1yn346cypSZw8BRAx6i3d4BTKgCxwnOqK8x6iMOb1Ad2IomKHoxH1_PkPIgMEz1mDcfipvG1IImuMj333wNe8tbPuPBsmQq-t-4GF4mH3sQkvt3pMdcnb4ITqLaZ5xR5Hxbyig6bENFyMR_5w_Q3LugXIIRknWB21jxWbcMOY1ggaYZno-MBFA2ueFDox8ImN4A9orD-8XpgbSqywqv5dnh4rCDoate27oMkz8NEGW6UdZUOSBrC0k91FKO2yHUa8KDA3tTKMIgDU-ynS0hOzfc_4cUICDpQJJOv2tXsWigkuVshJc-1733CXF3ptA8llB9dFPt6_-oWKAjxvHRq6_X8mX2Siz9D2kTXpfUS-AKmEpKcphNWzpIg5K8iKMy-xB_insLCYbkjFkxU5Q6-VnjS6KRolOXaRSejh2faVxFbgIFrOP6Ns5inBJZUemAPV7TTxY_RIGh3f4nMbzxU2P5doyYP7wTr_aiLDw1uJrDxjXRLPzLseS1uizlLpZMPw-QIAUARFyUzj7k4U9bzXoX_9URA5acvETVZOebdUbR3kCOOoBMmbdELX7uUkICPu_T0fsbGLAKA4wZSIIYdqCUydMQk9NofgvE28v-NB2g4-fFPuFANn0H4b0ktFrBT8wUO61ElrnwsL1tLyx6kP4s1y6OaH_ARTpb9StCkcvbO2bh4HYLj09xnxgbx_4RPUI6cag6mjCRhNTIipj3feZ0pBEVlL7NiTavSV2Ho2gGJujurYSE4cdF-Gjtraeulj0ur1buEwVQX8LbLWbO76X4cQLhE7G2Yf7GV8tjW2DX4TdG9yRciPaBntE0Imxe6IKZnSEEyqXMsZIRWLBfI3WIiVka-QD9lJlPZAdkNMb5VqQxyqruiCZ3nK-R7njc1EoVDejJEDOGyAljhF_kvcxsd_Hu0G8QHi0JtXXm8Tm9hH1O7EtEIDQAHR0tt6ihHixK2IYdfmoe3EIHJ_VmlC37RqTHf2ru2FgkoutuNLII9tYsMhWEEin-tgFwdCvUA0ONHytNY2I0EFKkx56t9JGoupL-lwpnhtnqpnVAPAgAk93D01fBz2NSNlXs_z3E8SOmXud35RNCG62i_nmzHICz_WRwKMHEbqelSst9U2h5FY.uzRUQfIEYUBmAFBUnNWTJn2yfL9toRZ2_VNuoRrA7jg",
    "value": []
}

The value of @odata.delaLink is a URI that points to the state of Users as of the specific moment in time the URI was generated. If nothing has changed and you follow @odata.delaLink, you will receive an empty data set and a new URI. If you then add a new User, calling the deltaLink would return only that new user.


问:
Issues with `addPolylines()` not appearing with data from `osmdata` package
I'm having issues with leaflet::addPolylines using sf objects with Leaflet for R.

Below is the code I'm using to extract (as a random example) of a railway in London.

```<code>library(osmdata)
library(leaflet)
library(sf)
library(ggplot2)

# Get Data
dlr <-
  opq("London, UK") %>%
  add_osm_feature(key = "line", value = "DLR") %>%
  osmdata_sf()

str(dlr$osm_lines)

# Classes ‘sf’ and 'data.frame':    213 obs. of  25 variables:
#   $ osm_id         : chr  "3636480" "3663203" "4005749" "4005750" ...
# $ name           : chr  "Docklands Light Railway" "Docklands Light Railway" "Docklands Light Railway" "Docklands Light Railway" ...
# $ bridge         : chr  "viaduct" "viaduct" NA NA ...
# $ covered        : chr  NA NA NA NA ...
# $ cutting        : chr  NA NA NA NA ...
# $ disused.railway: chr  NA NA NA NA ...
# $ electrified    : chr  "rail" "rail" "rail" "rail" ...
# $ fixme          : chr  NA NA NA NA ...
# $ frequency      : chr  "0" "0" "0" "0" ...
# $ gauge          : chr  "1435" "1435" "1435" "1435" ...
# $ layer          : chr  "1" "1" "-2" "-2" ...
# $ level          : chr  NA NA NA NA ...
# $ line           : chr  "DLR" "DLR" "DLR" "DLR" ...
# $ note           : chr  NA NA "Route guessed" "Route guessed" ...
# $ oneway         : chr  NA NA NA NA ...
# $ railway        : chr  "light_rail" "light_rail" "light_rail" "light_rail" ...
# $ service        : chr  NA NA NA NA ...
# $ short_name     : chr  NA NA NA NA ...
# $ source         : chr  NA NA NA NA ...
# $ source_ref     : chr  NA NA NA NA ...
# $ start_date     : chr  NA NA NA NA ...
# $ track_detail   : chr  NA NA NA NA ...
# $ tunnel         : chr  NA NA "yes" "yes" ...
# $ voltage        : chr  "750" "750" "750" "750" ...
# $ geometry       :sfc_LINESTRING of length 213; first list element:  'XY' num [1:4, 1:2] -0.0673 -0.0669 -0.0664 -0.0661 51.5111 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr  "18019994" "1842525419" "1752475375" "18019985"
# .. ..$ : chr  "lon" "lat"
# - attr(*, "sf_column")= chr "geometry"
# - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
# ..- attr(*, "names")= chr  "osm_id" "name" "bridge" "covered" ...
</code>```

Then, plotting using ggplot() and geom_sf() is fine:

```<code>dlr$osm_lines %>%
  ggplot() + geom_sf()
</code>```

But not with Leaflet:

```<code>dlr$osm_lines %>%
  leaflet() %>%
  addProviderTiles("Stamen.Watercolor") %>%
  addPolylines()
</code>```

Apologies for the unnecessary watercolour - just wanted to make it abundantly clear that the lines were not there.

答:
This seems to be a problem with the names being set in the geometry of the lines, following recent updates - see the discussion here https://github.com/r-spatial/sf/issues/880 - which suggests just removing them.

This works for me with your example...

```<code>names(st_geometry(dlr$osm_lines)) = NULL

dlr$osm_lines %>%
  leaflet() %>%
  addProviderTiles("Stamen.Watercolor") %>%
  addPolylines()
</code>```

Body:
I'm having issues with leaflet::addPolylines using sf objects with Leaflet for R.

Below is the code I'm using to extract (as a random example) of a railway in London.

library(osmdata)
library(leaflet)
library(sf)
library(ggplot2)

# Get Data
dlr <-
  opq("London, UK") %>%
  add_osm_feature(key = "line", value = "DLR") %>%
  osmdata_sf()

str(dlr$osm_lines)

# Classes ‘sf’ and 'data.frame':    213 obs. of  25 variables:
#   $ osm_id         : chr  "3636480" "3663203" "4005749" "4005750" ...
# $ name           : chr  "Docklands Light Railway" "Docklands Light Railway" "Docklands Light Railway" "Docklands Light Railway" ...
# $ bridge         : chr  "viaduct" "viaduct" NA NA ...
# $ covered        : chr  NA NA NA NA ...
# $ cutting        : chr  NA NA NA NA ...
# $ disused.railway: chr  NA NA NA NA ...
# $ electrified    : chr  "rail" "rail" "rail" "rail" ...
# $ fixme          : chr  NA NA NA NA ...
# $ frequency      : chr  "0" "0" "0" "0" ...
# $ gauge          : chr  "1435" "1435" "1435" "1435" ...
# $ layer          : chr  "1" "1" "-2" "-2" ...
# $ level          : chr  NA NA NA NA ...
# $ line           : chr  "DLR" "DLR" "DLR" "DLR" ...
# $ note           : chr  NA NA "Route guessed" "Route guessed" ...
# $ oneway         : chr  NA NA NA NA ...
# $ railway        : chr  "light_rail" "light_rail" "light_rail" "light_rail" ...
# $ service        : chr  NA NA NA NA ...
# $ short_name     : chr  NA NA NA NA ...
# $ source         : chr  NA NA NA NA ...
# $ source_ref     : chr  NA NA NA NA ...
# $ start_date     : chr  NA NA NA NA ...
# $ track_detail   : chr  NA NA NA NA ...
# $ tunnel         : chr  NA NA "yes" "yes" ...
# $ voltage        : chr  "750" "750" "750" "750" ...
# $ geometry       :sfc_LINESTRING of length 213; first list element:  'XY' num [1:4, 1:2] -0.0673 -0.0669 -0.0664 -0.0661 51.5111 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr  "18019994" "1842525419" "1752475375" "18019985"
# .. ..$ : chr  "lon" "lat"
# - attr(*, "sf_column")= chr "geometry"
# - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
# ..- attr(*, "names")= chr  "osm_id" "name" "bridge" "covered" ...

Then, plotting using ggplot() and geom_sf() is fine:

dlr$osm_lines %>%
  ggplot() + geom_sf()

But not with Leaflet:

dlr$osm_lines %>%
  leaflet() %>%
  addProviderTiles("Stamen.Watercolor") %>%
  addPolylines()

Apologies for the unnecessary watercolour - just wanted to make it abundantly clear that the lines were not there.

Body:
This seems to be a problem with the names being set in the geometry of the lines, following recent updates - see the discussion here https://github.com/r-spatial/sf/issues/880 - which suggests just removing them.

This works for me with your example...

names(st_geometry(dlr$osm_lines)) = NULL

dlr$osm_lines %>%
  leaflet() %>%
  addProviderTiles("Stamen.Watercolor") %>%
  addPolylines()


问:
Can get data individual data from foreachLoop Umbraco c#
My code works fine but when i try to get data of each funds = subpage.Name i get all the funds data not as individual. what im missing here ??
Can anyone help me? im sorry im new to umbraco and c#, whats the best way to manage this

now its like this

```<code>(16) [{…}, {…},]...
0: {Fundo: "CURTO PRAZO", data: Array(21)}
1: {Fundo: "CA MONETARIO", data: Array(21)}
...

In reality it should be

(16) [{…}, {…},]...
0: {Fundo: "CURTO PRAZO", data: Array(4)}
1: {Fundo: "CA MONETARIO", data: Array(3)}
for example
...
</code>```

this is my code

```<code>    var currentPage = Model.Content;

    var selection = Umbraco.Content(1448);

    @foreach (var page in selection.Children){

    if(page.Children.Count() > 0){

    foreach(var subpage in page.Children){

    var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");

         if(listaPdf == null) {

         listaPdf = new List<IPublishedContent>();}

        if(listaPdf != null){

        foreach(var row in listaPdf) {

        name = Umbraco.Field(row, "categoriaDoFundo").ToString();

        var id = Umbraco.Field(row, "documentos").ToString();

        var mediaItem = Umbraco.TypedMedia(id);

        url = mediaItem.Url;

        <script type="text/javascript">

       data.push({"Nome":"@name", "Url":"@url"});

        </script>
         }

         <script type="text/javascript">

        list.push({"Fundo":"@subpage.Name", data });
        </script>

              }

            }

        }

     }
</code>```

答:
You should use UmbracoHelper to get the IPublishedContent and then you can get the children of your content page & reach individual properties.

Please see details below; in my example my test content id is my Home page's nodeId and see how I get the children of my Home page and the first child's properties - so please update your code according to this, for further details take a look at this;

```<code>            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var testContentId = 1353; // This is your umbraco node id of your content page
            var publishedContent = umbracoHelper.TypedContent(testContentId);

            if (publishedContent != null)
            {
                foreach (var child in publishedContent.Children)
                {
                    // This is where you can reach the Children of this child as well as individual properties of this child
                    if (child.HasProperty("emailAddress_Contact_Information"))
                    {
                        var emailAddressContactInformation = child.GetProperty("emailAddress_Contact_Information");
                    }
                }
            }
</code>```

Body:
My code works fine but when i try to get data of each funds = subpage.Name i get all the funds data not as individual. what im missing here ??
Can anyone help me? im sorry im new to umbraco and c#, whats the best way to manage this

now its like this

(16) [{…}, {…},]...
0: {Fundo: "CURTO PRAZO", data: Array(21)}
1: {Fundo: "CA MONETARIO", data: Array(21)}
...

In reality it should be

(16) [{…}, {…},]...
0: {Fundo: "CURTO PRAZO", data: Array(4)}
1: {Fundo: "CA MONETARIO", data: Array(3)}
for example
...

this is my code

    var currentPage = Model.Content;

    var selection = Umbraco.Content(1448);

    @foreach (var page in selection.Children){

    if(page.Children.Count() > 0){

    foreach(var subpage in page.Children){

    var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");

         if(listaPdf == null) {

         listaPdf = new List<IPublishedContent>();}

        if(listaPdf != null){

        foreach(var row in listaPdf) {

        name = Umbraco.Field(row, "categoriaDoFundo").ToString();

        var id = Umbraco.Field(row, "documentos").ToString();

        var mediaItem = Umbraco.TypedMedia(id);

        url = mediaItem.Url;

         }

              }

            }

        }

     }

Body:
You should use UmbracoHelper to get the IPublishedContent and then you can get the children of your content page & reach individual properties.

Please see details below; in my example my test content id is my Home page's nodeId and see how I get the children of my Home page and the first child's properties - so please update your code according to this, for further details take a look at this;

            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var testContentId = 1353; // This is your umbraco node id of your content page
            var publishedContent = umbracoHelper.TypedContent(testContentId);

            if (publishedContent != null)
            {
                foreach (var child in publishedContent.Children)
                {
                    // This is where you can reach the Children of this child as well as individual properties of this child
                    if (child.HasProperty("emailAddress_Contact_Information"))
                    {
                        var emailAddressContactInformation = child.GetProperty("emailAddress_Contact_Information");
                    }
                }
            }


问:
Include file.php + id. Is this possible with php?
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

```<code><a href="news.php?id=<?=$row['id']?>">Read More</a></p>
</code>```

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!

答:
Yeah, include basically adds the code of another file to the execution of the code you are using.  So if you already have the variable in you index file can just use it in your menu file.

If the menu file has to be loaded on it own sometimes you can do a conditional for the existence of the GET, then the existence of the variable in your index file, and finally if none of them exit, set a default value.

Body:
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

<a href="news.php?id=<?=$row['id']?>">Read More

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!


问:
SQL update from one Table to another based on a ID match IN db2
The Query below is suited in SQL sErver. But in DB2 it does not give results:

```<code>Error is  SQLCODE = -199, ERROR:  ILLEGAL USE OF KEYWORD FROM.
</code>```

Query:

```<code>UPDATE
     Sales_Import
 SET
    Sales_Import.AccountNumber = RAN.AccountNumber
FROM
Sales_Import SI
INNER JOIN
RetrieveAccountNumber RAN
ON
SI.LeadID = RAN.LeadID
</code>```

Can someone please clarify the differences b/w DB2 and SQL queries.

答:
In case someone else want to update a table with the SUM() of values of another Table on DB2. I was running into many issues with joins and finally a simple SELECT in the UPDATE solved it. Thx to @mustaccio</p>

```<code>TABLE_A
ID......|TOTAL...|...
1
5
6

TABLE_B
ID......|REF_ID...|QUANTITY|...
1        5         20
2        1         25
3        1         3
</code>```

```<code>SQL Statement:
UPDATE TABLE_A ta
SET ta.TOTAL = (
    SELECT SUM(tb.QUANTITY)
    FROM TABLE_B tb
    WHERE tb.REF_ID = ta.ID
)
</code>```

```<code>RESULT
TABLE_A
ID......|TOTAL...|...
1        28
5        20
6        NULL
</code>```

Body:
The Query below is suited in SQL sErver. But in DB2 it does not give results:

Error is  SQLCODE = -199, ERROR:  ILLEGAL USE OF KEYWORD FROM.

Query:

UPDATE
     Sales_Import
 SET
    Sales_Import.AccountNumber = RAN.AccountNumber
FROM
Sales_Import SI
INNER JOIN
RetrieveAccountNumber RAN
ON
SI.LeadID = RAN.LeadID

Can someone please clarify the differences b/w DB2 and SQL queries.

Body:
In case someone else want to update a table with the SUM() of values of another Table on DB2. I was running into many issues with joins and finally a simple SELECT in the UPDATE solved it. Thx to @mustaccio

TABLE_A
ID......|TOTAL...|...
1
5
6

TABLE_B
ID......|REF_ID...|QUANTITY|...
1        5         20
2        1         25
3        1         3

SQL Statement:
UPDATE TABLE_A ta
SET ta.TOTAL = (
    SELECT SUM(tb.QUANTITY)
    FROM TABLE_B tb
    WHERE tb.REF_ID = ta.ID
)

RESULT
TABLE_A
ID......|TOTAL...|...
1        28
5        20
6        NULL


问:
what is the alternative for 'using a dict on a Series for aggregation'
I used agg function to calculate the average value of CENSUS2010POP grouped by STNAME. Inside the agg function, I used a dictionary with {} to name the new column for the average values (details in the codes below)
The codes work well but Jupyter Notebook gave me a warning

FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version

I wonder what is the new way to do this.

I'm running this on the newest Jupyter Notebook, with python 3, installed from Anaconda3

the method I am using now is like this:

```<code>df = pd.read_csv('census.csv')
df = (df.where(df['SUMLEV']==50)
     .dropna()
     .set_index('STNAME')
     .groupby(level = 0)['CENSUS2010POP']
     .agg({'avg' : np.average}) )

df
</code>```

But this method is deprecated and will be removed in the future as the warning said

The result should be like this (which is the result from the codes above)

```<code>                avg
STNAME
Alabama         71339.343284
Alaska          24490.724138
Arizona         426134.466667
Arkansas        38878.906667
California      642309.586207
Colorado        78581.187500
Connecticut     446762.125000
Delaware        299311.333333
...
</code>```

答:
Under the documentation for pandas.DataFrame.agg it says agg can take a function, list, str, or dict as input. So you could directly pass the function np.average and give it as a column label.

```<code>df = pd.read_csv('census.csv')
df = (df.where(df['SUMLEV']==50)
     .dropna()
     .set_index('STNAME')
df['avg'] = df.groupby(level = 0)['CENSUS2010POP']
     .agg(np.average) )
</code>```

Body:
I used agg function to calculate the average value of CENSUS2010POP grouped by STNAME. Inside the agg function, I used a dictionary with {} to name the new column for the average values (details in the codes below)
The codes work well but Jupyter Notebook gave me a warning

FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version

I wonder what is the new way to do this.

I'm running this on the newest Jupyter Notebook, with python 3, installed from Anaconda3

the method I am using now is like this:

df = pd.read_csv('census.csv')
df = (df.where(df['SUMLEV']==50)
     .dropna()
     .set_index('STNAME')
     .groupby(level = 0)['CENSUS2010POP']
     .agg({'avg' : np.average}) )

df

But this method is deprecated and will be removed in the future as the warning said

The result should be like this (which is the result from the codes above)

                avg
STNAME
Alabama         71339.343284
Alaska          24490.724138
Arizona         426134.466667
Arkansas        38878.906667
California      642309.586207
Colorado        78581.187500
Connecticut     446762.125000
Delaware        299311.333333
...

Body:
Under the documentation for pandas.DataFrame.agg it says agg can take a function, list, str, or dict as input. So you could directly pass the function np.average and give it as a column label.

df = pd.read_csv('census.csv')
df = (df.where(df['SUMLEV']==50)
     .dropna()
     .set_index('STNAME')
df['avg'] = df.groupby(level = 0)['CENSUS2010POP']
     .agg(np.average) )


问:
How to render only one document in jade view?
I need to display only one document from my CouchDB, but if I don't create for-each loop, I can't define variable employer

```<code>  .row
    .col-xs-12.col-sm-8
      .row.list-group
        each employer in the employers
          .col-xs-12.list-group-item
            h4
              p #{employer.value.name}, #{employer.value.location} #{employer.value.type}, #{employeer.value.position}
              small
    .col-xs-12.col-sm-4
      p.lead= sidebar
</code>```

When I try to display only one document without the loop, I am receiving an error:  Cannot read property 'value' of undefined

答:
If employeers is an array, you should be able to do something like:

```<code>employeers[0].value.name
</code>```

If you want to keep using "employer" you can also replace your each loop with:

```<code>- var employer = employeers[0];
</code>```

Body:
I need to display only one document from my CouchDB, but if I don't create for-each loop, I can't define variable employer

  .row
    .col-xs-12.col-sm-8
      .row.list-group
        each employer in the employers
          .col-xs-12.list-group-item
            h4
              p #{employer.value.name}, #{employer.value.location} #{employer.value.type}, #{employeer.value.position}
              small
    .col-xs-12.col-sm-4
      p.lead= sidebar

When I try to display only one document without the loop, I am receiving an error:  Cannot read property 'value' of undefined

Body:
If employeers is an array, you should be able to do something like:

employeers[0].value.name

If you want to keep using "employer" you can also replace your each loop with:

- var employer = employeers[0];


问:
VB.NET 2005, Serial port, dispose problem, Windows CE
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

```<code>port.close()
port.dispose()
</code>```

And If I add this:

```<code>System.GC.collect()
</code>```

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?

答: It could be that an object that owns the port object is not disposed or still maintains a reference. That would explain why after system.gc.collect() it works.</p>

Body:
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

port.close()
port.dispose()

And If I add this:

System.GC.collect()

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?


问:
Display a "traditional" html Select list on iOS
How can I display a "traditional" html <select> list on iOS rather than the iOS "picker"?

Details:

I have a HTML page that that displays a <select> list that has ~500 items in a column. The list is always displayed. Depending on the height of the browser window, the list typically displays 20-30 items.

When displayed on iOS devices, the list shows an arrow which, when tapped, pops up a small list that displays four list items. I want a "traditional" HTML list displayed (similar to the appearance in a desktop browser).

FWIW, the contents of this page (a Google Earth-like map) aren't appropriate for small devices (e.g., phones), but are very appropriate for larger screens like iPads. I limit access to the page accordingly. Also because somebody is going to say the list is too long, there are filter and search controls the user can use to limit the number of items displayed in the list. The pages uses HTML, CSS, JavaScript, and jQuery.

Thanks!

答:
The short answer is, unfortunately, you can't. The behaviour of a <select> element is determined by the OS/Browser in which it is being viewed. Limited options do exist for customizing the appearance, but being able to choose between a dropdown and a picker is not one of them.

You do, however, still have a couple of options;

Create a completely custom select box Note: This is probably the route I'd take

Follow IOS design patterns and emulate a drilldown list or action sheet.


问:
wrapping a listviewBuilder inside of Column?
I wish a good day.i m struggling to wrap a ListView.builder inside of a column.
every time I try to fix it I get this exception :

```<code> The following RenderObject was being processed when the exception was fired:
flutter:   RenderViewport#c3792 NEEDS-LAYOUT NEEDS-PAINT
flutter:   creator: Viewport ← IgnorePointer-[GlobalKey#b696d] ← Semantics ← Listener ← _GestureSemantics ←
flutter:   RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#65964] ← Listener ← _ScrollableScope
flutter:   ← _ScrollSemantics-[GlobalKey#f3a27] ← Scrollable ← PrimaryScrollController ← ListView ← ⋯
flutter:   parentData: <none> (can use size)
flutter:   constraints: BoxConstraints(w=327.0, 0.0<=h<=Infinity)
flutter:   size: MISSING
flutter:   axisDirection: down
flutter:   crossAxisDirection: right
flutter:   offset: ScrollPositionWithSingleContext#60171(offset: 0.0, range: null..null, viewport: null,
flutter:   ScrollableState, AlwaysScrollableScrollPhysics -> BouncingScrollPhysics, IdleScrollActivity#63b9f,
flutter:   ScrollDirection.idle)
flutter:   anchor: 0.0
flutter: This RenderObject had the following descendants (showing up to depth 5):
flutter:   RenderSliverPadding#e4dfb NEEDS-LAYOUT NEEDS-PAINT
flutter:     RenderSliverList#17862 NEEDS-LAYOUT NEEDS-PAINT
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: RenderBox was not laid out: RenderViewport#c3792 NEEDS-LAYOUT NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderViewport#c3792 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderIgnorePointer#8fccb relayoutBoundary=up9 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderFlex#cbeea relayoutBoundary=up2 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderPadding#0b306 relayoutBoundary=up1 NEEDS-PAINT
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
</code>```

this is my code :

```<code>Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView.builder(
                  itemCount: _messages.length,
                  itemBuilder: (context, position) {

                print(_messages.length);
                return Center(child: Text(_messages[position]));
              }),
            )
          ]))
</code>```

if there's anyone who can help me i will be very thankful.

答: As I mentioned in the comment, wrapping the second Padding inside of Expanded widget does the job.

Body:
I wish a good day.i m struggling to wrap a ListView.builder inside of a column.
every time I try to fix it I get this exception :

 The following RenderObject was being processed when the exception was fired:
flutter:   RenderViewport#c3792 NEEDS-LAYOUT NEEDS-PAINT
flutter:   creator: Viewport ← IgnorePointer-[GlobalKey#b696d] ← Semantics ← Listener ← _GestureSemantics ←
flutter:   RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#65964] ← Listener ← _ScrollableScope
flutter:   ← _ScrollSemantics-[GlobalKey#f3a27] ← Scrollable ← PrimaryScrollController ← ListView ← ⋯
flutter:   parentData: <none> (can use size)
flutter:   constraints: BoxConstraints(w=327.0, 0.0<=h<=Infinity)
flutter:   size: MISSING
flutter:   axisDirection: down
flutter:   crossAxisDirection: right
flutter:   offset: ScrollPositionWithSingleContext#60171(offset: 0.0, range: null..null, viewport: null,
flutter:   ScrollableState, AlwaysScrollableScrollPhysics -> BouncingScrollPhysics, IdleScrollActivity#63b9f,
flutter:   ScrollDirection.idle)
flutter:   anchor: 0.0
flutter: This RenderObject had the following descendants (showing up to depth 5):
flutter:   RenderSliverPadding#e4dfb NEEDS-LAYOUT NEEDS-PAINT
flutter:     RenderSliverList#17862 NEEDS-LAYOUT NEEDS-PAINT
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: RenderBox was not laid out: RenderViewport#c3792 NEEDS-LAYOUT NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderViewport#c3792 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderIgnorePointer#8fccb relayoutBoundary=up9 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderFlex#cbeea relayoutBoundary=up2 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderPadding#0b306 relayoutBoundary=up1 NEEDS-PAINT
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.

this is my code :

Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView.builder(
                  itemCount: _messages.length,
                  itemBuilder: (context, position) {

                print(_messages.length);
                return Center(child: Text(_messages[position]));
              }),
            )
          ]))

if there's anyone who can help me i will be very thankful.


问:
How to train an image similarity model on 20 millions images(total size 10GB)?
My system is configured with 16GB RAM. I have tried to train image similarity model on 20 millions images(total size 10GB) using VGG19 and KNN's nearest neighbor. When tried to read images i am getting Memory error. Even I have tried to train model on 200000(total size 770MB) but issue is same. How I can read millions of images to train ML models.

Ubuntu 18.04.2 LTS,Core™ i7,Intel® HD Graphics 5500 (Broadwell GT2), 64-bit, 16GB RAM

```<code>import os
import skimage.io
import tensorflow as tf
from skimage.transform import resize
import numpy as np
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from sklearn import manifold
import pickle
skimage.io.use_plugin('matplotlib')

dirPath = 'train_data'
args = [os.path.join(dirPath, filename) for filename in os.listdir(dirPath)]

imgs_train = [skimage.io.imread(arg, as_gray=False) for arg in args]
shape_img = (130, 130, 3)

model = tf.keras.applications.VGG19(weights='imagenet', include_top=False,
                                        input_shape=shape_img)
model.summary()
shape_img_resize = tuple([int(x) for x in model.input.shape[1:]])
input_shape_model = tuple([int(x) for x in model.input.shape[1:]])
output_shape_model = tuple([int(x) for x in model.output.shape[1:]])
n_epochs = None

def resize_img(img, shape_resized):
    img_resized = resize(img, shape_resized,
                         anti_aliasing=True,
                         preserve_range=True)
    assert img_resized.shape == shape_resized
    return img_resized

def normalize_img(img):
    return img / 255.

def transform_img(img, shape_resize):
    img_transformed = resize_img(img, shape_resize)
    img_transformed = normalize_img(img_transformed)
    return img_transformed

def apply_transformer(imgs, shape_resize):
    imgs_transform = [transform_img(img, shape_resize) for img in imgs]
    return imgs_transform

imgs_train_transformed = apply_transformer(imgs_train, shape_img_resize)
X_train = np.array(imgs_train_transformed).reshape((-1,) + input_shape_model)
E_train = model.predict(X_train)
E_train_flatten = E_train.reshape((-1, np.prod(output_shape_model)))
knn = NearestNeighbors(n_neighbors=5, metric="cosine")
knn.fit(E_train_flatten)
</code>```

答:
Knowing that keras is working well with generator, you should consider using one:
python generator tutorial,
using a generator with keras (example)

It allows you to load your image during your training, batch by batch.

Body:
My system is configured with 16GB RAM. I have tried to train image similarity model on 20 millions images(total size 10GB) using VGG19 and KNN's nearest neighbor. When tried to read images i am getting Memory error. Even I have tried to train model on 200000(total size 770MB) but issue is same. How I can read millions of images to train ML models.

Ubuntu 18.04.2 LTS,Core™ i7,Intel® HD Graphics 5500 (Broadwell GT2), 64-bit, 16GB RAM

import os
import skimage.io
import tensorflow as tf
from skimage.transform import resize
import numpy as np
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from sklearn import manifold
import pickle
skimage.io.use_plugin('matplotlib')

dirPath = 'train_data'
args = [os.path.join(dirPath, filename) for filename in os.listdir(dirPath)]

imgs_train = [skimage.io.imread(arg, as_gray=False) for arg in args]
shape_img = (130, 130, 3)

model = tf.keras.applications.VGG19(weights='imagenet', include_top=False,
                                        input_shape=shape_img)
model.summary()
shape_img_resize = tuple([int(x) for x in model.input.shape[1:]])
input_shape_model = tuple([int(x) for x in model.input.shape[1:]])
output_shape_model = tuple([int(x) for x in model.output.shape[1:]])
n_epochs = None

def resize_img(img, shape_resized):
    img_resized = resize(img, shape_resized,
                         anti_aliasing=True,
                         preserve_range=True)
    assert img_resized.shape == shape_resized
    return img_resized

def normalize_img(img):
    return img / 255.

def transform_img(img, shape_resize):
    img_transformed = resize_img(img, shape_resize)
    img_transformed = normalize_img(img_transformed)
    return img_transformed

def apply_transformer(imgs, shape_resize):
    imgs_transform = [transform_img(img, shape_resize) for img in imgs]
    return imgs_transform

imgs_train_transformed = apply_transformer(imgs_train, shape_img_resize)
X_train = np.array(imgs_train_transformed).reshape((-1,) + input_shape_model)
E_train = model.predict(X_train)
E_train_flatten = E_train.reshape((-1, np.prod(output_shape_model)))
knn = NearestNeighbors(n_neighbors=5, metric="cosine")
knn.fit(E_train_flatten)


问:
How to get length as 0 if the dictionary is not available in Json file while parsing using python
I am trying to get the length of a dictionary as below . for dictionary "ZZZZ" i may have multiple records available

```<code>for j in range(len(json_file['entitity'][i]['XXXX']['YYYYY']['ZZZZ']))
</code>```

But if the dictionary doesn't exists in the json file i want to return them as 0

As per the above value i have requirement to get a variable value like below.

```<code>temp['EMPID'] = json_file['entities'][i]['XXXX']['YYYYY']['ZZZZ'][j]['re']['id']
</code>```

Please help with an suggestion , how can i get "j" variable as 0 if the dictionary doesn't exist. Please find below example

```<code>"YYYYY": [
        {
          "ZZZZ": {
            "id": "Z1234",
            "type": "p1"
          },
          "id": "wer1234",
          "prop": {
            "dir": "South",
            "Type": "C1"
          }
        },
        {
          "ZZZZ": {
            "id": "Y1234",
            "type": "p2"
          },
          "id": "ert12345",
          "prop": {
            "dir": "North",
            "relationshipType": "C2"
          }
        }
      ]
</code>```

In the above example , i am trying to get the value [ZZZZ][id] ( Value should be : "Z1234" ). In the same way i have one more record with
value "Y1234". I have totally 2 records because of that i am trying to capture the length as per below command and get the id value.

```<code>for j in range(len(json_file['YYYYY']))   ------###to capture the lenght as i have 2 records so i am trying to capture length 2
    temp['EMPID'] = json_file['YYYYY'][j]['ZZZZ']['id']   -------##to capture the attribute value
</code>```

But in some cases i may not receive these attributes in my source Json Files, where i want to handle if the attributes are available and have
multiple records then as per above statement i want to get the values else we can populate null values for these id columns.

答:
You can accomplish this by using the dict.get(key, default) method, supplying an empty list as the default value if the key in the dictionary doesn't exist.

This will allow you to iterate over the keys in the dictionary at the specified key, if it exists, and skip it otherwise.

Ex:

data = {
    'one': {},
    'two': {
        'a': {
            're': {
                'id': 1
            }
        },
        'b': {
            're': {
                'id': 1
            }
        }
    }
}

# Example with empty dictionary
for key in data.get('one', []):
    print(f'data[\'one\'] - {key}: {data["one"][key]}')

# Example with populated dictionary
for key in data.get('two', []):
    print(f'data[\'two\'] - {key}: {data["two"][key]}')

# Example with non-existent dictionary
for key in data.get('foo', []):
    print(f'data[\'foo\'] - {key}: {data["foo"][key]}')
```

Body:
I am trying to get the length of a dictionary as below . for dictionary "ZZZZ" i may have multiple records available

for j in range(len(json_file['entitity'][i]['XXXX']['YYYYY']['ZZZZ']))

But if the dictionary doesn't exists in the json file i want to return them as 0

As per the above value i have requirement to get a variable value like below.

temp['EMPID'] = json_file['entities'][i]['XXXX']['YYYYY']['ZZZZ'][j]['re']['id']

Please help with an suggestion , how can i get "j" variable as 0 if the dictionary doesn't exist. Please find below example

"YYYYY": [
        {
          "ZZZZ": {
            "id": "Z1234",
            "type": "p1"
          },
          "id": "wer1234",
          "prop": {
            "dir": "South",
            "Type": "C1"
          }
        },
        {
          "ZZZZ": {
            "id": "Y1234",
            "type": "p2"
          },
          "id": "ert12345",
          "prop": {
            "dir": "North",
            "relationshipType": "C2"
          }
        }
      ]

In the above example , i am trying to get the value [ZZZZ][id] ( Value should be : "Z1234" ). In the same way i have one more record with
value "Y1234". I have totally 2 records because of that i am trying to capture the length as per below command and get the id value.

for j in range(len(json_file['YYYYY']))   ------###to capture the lenght as i have 2 records so i am trying to capture length 2
    temp['EMPID'] = json_file['YYYYY'][j]['ZZZZ']['id']   -------##to capture the attribute value

But in some cases i may not receive these attributes in my source Json Files, where i want to handle if the attributes are available and have
multiple records then as per above statement i want to get the values else we can populate null values for these id columns.


问:
Jquery not recognize menu include
I have my index calls from other HTML pages using the library CSI.js

my index:

```<code><div class="col-6 col-md-2" id="nav">
  <div data-include="./views/menu/sticky-menu.html"></div> <!-- menu -->
</div>
</code>```

in menu page:

```<code><div class="sticky-menu" id="sticky-menu">
  <div class="sticky-menu-header">
    <img class="logo" src="./img/logo-branco.svg" />
  </div>
  <ul>
    <li class="active"><a href="#"><i class="fa fa-home"></i>Home </a></li>
    <li><a href="#"><i class="fa fa-glass"></i>Eventos </a></li>
    <li><a href="#"><i class="fa fa-file-image-o"></i>Alertas </a><span class="sticky-menu-label">4 </span></li>
    <li><a href="#"><i class="fa fa-cog"></i>Indicadores </a>
      <ul class="submenu">
        <li><a href="#">Teste</a></li>
        <li><a href="#">Teste </a></li>
        <li>
          <a href="#">Teste </a>
            <ul class="submenu">
              <li><a href="#">Teste </a></li>
            </ul>
        </li>
        <li><a href="#">Consulting </a></li>
      </ul>
    </li>
    <li>
      <a href="#"><i class="fa fa-suitcase"></i>Grafana </a>
      <ul class="submenu">
        <li><a href="#">Item 0 </a></li>
        <li><a href="#">Item 1 </a><span class="sticky-menu-label">10 </span></li>
      </ul>
    </li>
  </ul>
</div>
</code>```

submenu have dropdown animation with jquery:

```<code>jQuery(document).ready(function() {
  jQuery("#sticky-menu").jqueryAccordionMenu();
});
</code>```

On the menu page (sticky-menu.html) it works fine, like this:

https://i.stack.imgur.com/oAPds.png

Notice that the + sign appears when clicked:

https://i.stack.imgur.com/9OJIu.png

However, not index.html, menu (jquery) does not work:

https://i.stack.imgur.com/tvBRR.png

When I enter the code in the console:

```<code>jQuery(document).ready(function() {
  jQuery("#sticky-menu").jqueryAccordionMenu();
});
</code>```

it works: https://i.stack.imgur.com/YZe8y.png

I've included the js code on both pages, I think it's silly, but I really can not. Thank you for your help.

EDIT:
I noticed that my sticky-menu.html is wearing after the script. How to solve?

https://i.stack.imgur.com/j1Pzu.png

EDIT 2 :

I solved with requireJS.

答:
You could run some code as follows

```<code>function waitForElement(id, callback){
    var checkForElement = setInterval(function(){
        if(document.getElementById(id)){
            clearInterval(checkForElement);
            callback();
        }
    }, 100);
}

waitForElement("idOfElementToWaitFor", function(){
    alert("element is loaded.. do stuff");
});
</code>```

Where your id for your element would be #sticky-menu and your callback function would be jQuery("#sticky-menu").jqueryAccordionMenu();

Title: Jquery not recognize menu include

Body:
I have my index calls from other HTML pages using the library CSI.js

my index:

in menu page:

Home

Eventos

Alertas 4

Indicadores

Teste

Teste

          Teste

Teste

Consulting

      Grafana

Item 0

Item 1 10

submenu have dropdown animation with jquery:

jQuery(document).ready(function() {
  jQuery("#sticky-menu").jqueryAccordionMenu();
});

On the menu page (sticky-menu.html) it works fine, like this:

https://i.stack.imgur.com/oAPds.png

Notice that the + sign appears when clicked:

https://i.stack.imgur.com/9OJIu.png

However, not index.html, menu (jquery) does not work:

https://i.stack.imgur.com/tvBRR.png

When I enter the code in the console:

jQuery(document).ready(function() {
  jQuery("#sticky-menu").jqueryAccordionMenu();
});

it works: https://i.stack.imgur.com/YZe8y.png

I've included the js code on both pages, I think it's silly, but I really can not. Thank you for your help.

EDIT:
I noticed that my sticky-menu.html is wearing after the script. How to solve?

https://i.stack.imgur.com/j1Pzu.png

EDIT 2 :

I solved with requireJS.

Body:
You could run some code as follows

function waitForElement(id, callback){
    var checkForElement = setInterval(function(){
        if(document.getElementById(id)){
            clearInterval(checkForElement);
            callback();
        }
    }, 100);
}

waitForElement("idOfElementToWaitFor", function(){
    alert("element is loaded.. do stuff");
});

Where your id for your element would be #sticky-menu and your callback function would be jQuery("#sticky-menu").jqueryAccordionMenu();


问:
in Rails, make assets:precompile output the list of files it has precompiled?
In Rails, how do I output list of assets compiled for assets pipeline by rake assets:precompile?

答:
For Rails 5, on console:</p>

```<code>Rails.application.config.assets[:precompile]
</code>```

Body:
For Rails 5, on console:

Rails.application.config.assets[:precompile]


问:
Create Html from React Component including Style
I have a simple react component in which using ref I am getting the div but I have to generate a html includes styling as well. So I can pass this html to PDF generation backend server.

```<code>pdfRef(elem){
        console.log(elem);
//<div><span>dataPDF</span> </div>

    }

    render() {

        return (
            <div ref={(elem) => this.pdfRef(elem)} className="SomeCssClass">
                <span >dataPDF</span>
            </div>
        );
    }
}
</code>```

[Edit]

When I try to print the div via ref, the elements are printed with class name. But when I send this string to pdf service, since only html element is sent and class name without the actual css , the pdf is generated without style.

is there any way to generate html with css as as string so further it can be send to pdf service. Hope the question is clear
Any pointers?

答:
The server.js script in react-dom lets you render a React component to static html string. You can require it in your code like:

```<code>const ReactDOMServer = require('react-dom/server');
</code>```

Or using ES6 syntax:

```<code>import ReactDomServer from 'react-dom/server'
</code>```

After this you can render your component to HTML string using the ReactDomServer.renderToString or ReactDomServer.renderToStaticMarkup functions as follows:

```<code>const htmlStr = ReactDomServer.renderToStaticMarkup(<MyComponent prop1={'value1'} />);
</code>```

This looks almost exactly like ReactDom.render, except that it doesn't need the second parameter of dom node to render at, and the html string is returned. Additionally this method can be used on both client and server side. For your generate-pdf use case renderToStaticMarkup would suffice. If required check the documentation at following link for subtle difference between the two methods mentioned above: https://reactjs.org/docs/react-dom-server.html

Body:
I have a simple react component in which using ref I am getting the div but I have to generate a html includes styling as well. So I can pass this html to PDF generation backend server.

pdfRef(elem){
        console.log(elem);
//
dataPDF

    }

    render() {

        return (

 this.pdfRef(elem)} className="SomeCssClass">
                dataPDF

        );
    }
}

[Edit]

When I try to print the div via ref, the elements are printed with class name. But when I send this string to pdf service, since only html element is sent and class name without the actual css , the pdf is generated without style.

is there any way to generate html with css as as string so further it can be send to pdf service. Hope the question is clear
Any pointers?

Body:
The server.js script in react-dom lets you render a React component to static html string. You can require it in your code like:

const ReactDOMServer = require('react-dom/server');

Or using ES6 syntax:

import ReactDomServer from 'react-dom/server'

After this you can render your component to HTML string using the ReactDomServer.renderToString or ReactDomServer.renderToStaticMarkup functions as follows:

const htmlStr = ReactDomServer.renderToStaticMarkup(<MyComponent prop1={'value1'} />);

This looks almost exactly like ReactDom.render, except that it doesn't need the second parameter of dom node to render at, and the html string is returned. Additionally this method can be used on both client and server side. For your generate-pdf use case renderToStaticMarkup would suffice. If required check the documentation at following link for subtle difference between the two methods mentioned above: https://reactjs.org/docs/react-dom-server.html


问:
MSVC 1 bit enum type equals -1 and equality test fails
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;
```
<p>Later the following comparison fails:</p>
<pre class="lang-none prettyprint-override"><code>Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...
</code>```

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?

答:
The exact type used to represent an enum is implementation defined.  So what is most likely happening is that MSVC is using char for this particular enum which is signed.  So declaring a 1-bit bitfield of this type means you get 0 and -1 for the values.

Rather that declaring the bitfield as the type of the enum, declare them as unsigned int or unsigned char so the values are properly represented.

Body:
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;

Later the following comparison fails:

Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?


问:
Loading a file from an API causing an error because of parsing to JSON
I am loading a xlsx file from an API. But loading causes an error because Angular trys to parse the body to JSON.

It is working if I give the request directly the response type like this:

this.http.get(this.url + "/getExcel",{responseType:'blob'});
```

<p>But in my backend I also need an authorization. And if I give the request a HttpHeaders object it isn't working:</p>

<pre class="lang-js prettyprint-override"><code>const headers = new HttpHeaders({
    responseType:'blob',
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{headers});
</code>```

I think the both above should do the same. Shouldn't it?

答: You should use application/octet-stream as a Content-Type, or not provide Content-Type at all

Body:
I am loading a xlsx file from an API. But loading causes an error because Angular trys to parse the body to JSON.

It is working if I give the request directly the response type like this:

this.http.get(this.url + "/getExcel",{responseType:'blob'});

But in my backend I also need an authorization. And if I give the request a HttpHeaders object it isn't working:

const headers = new HttpHeaders({
    responseType:'blob',
    'Content-Type': 'application/json',
    'Authorization': this.authService.getToken()
})
this.http.get(this.url + "/getExcel",{headers});

I think the both above should do the same. Shouldn't it?


问:
Datagrid rowbackground color
I'm trying to change a background color of a row datagrid in codebehing I'm using a binding property
in code behing I see the color changes but when displayed the background color doesn't change.
When  I play with the scroll I some of the </p>

答:
I created a sample CustomClass:

```<code>public class CustomClass
    {
        public string PropertyToBeWatched { get; set; }
    }
</code>```

Created a list:

```<code>MyList = new ObservableCollection<CustomClass>();
            MyList.Add(new CustomClass() { PropertyToBeWatched = "1"});
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });
</code>```

Then created the Datagrid:

```<code><sdk:DataGrid ItemsSource="{Binding MyList}" RowStyle="{StaticResource Style1}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Binding="{Binding PropertyToBeWatched}" Header="Property1"/>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
</code>```

Then the resources:

```<code>xmlns:sdk1="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
             xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

 <SolidColorBrush x:Key="Red" Color="#FFFF0000" />
        <SolidColorBrush x:Key="Green" Color="#FF00FF00" />

        <Style x:Key="Style1" TargetType="sdk:DataGridRow">
            <Setter Property="IsTabStop" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="sdk:DataGridRow">
                        <Grid Background="{Binding Converter={StaticResource Test}}">
                            <sdk1:DataGridFrozenGrid x:Name="Root">
                                <sdk1:DataGridFrozenGrid.Resources>
                                    <Storyboard x:Key="DetailsVisibleTransition">
                                        <DoubleAnimation Duration="00:00:0.1" Storyboard.TargetProperty="ContentHeight" Storyboard.TargetName="DetailsPresenter"/>
                                    </Storyboard>
                                </sdk1:DataGridFrozenGrid.Resources>
                                            <sdk1:DataGridFrozenGrid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition/>
                            </sdk1:DataGridFrozenGrid.ColumnDefinitions>
                                <sdk1:DataGridFrozenGrid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                </sdk1:DataGridFrozenGrid.RowDefinitions>
                                                                                <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="NormalAlternatingRow">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="NormalSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="MouseOverSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="UnfocusedSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="UnfocusedEditing"/>
                                    <VisualState x:Name="NormalEditing"/>
                                    <VisualState x:Name="MouseOverUnfocusedEditing"/>
                                    <VisualState x:Name="MouseOverEditing"/>
                                    <VisualState x:Name="MouseOverUnfocusedSelected"/>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="ValidationStates">
                                    <VisualState x:Name="Valid"/>
                                    <VisualState x:Name="Invalid">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="BackgroundRectangle">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="InvalidVisualElement"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                                <Rectangle x:Name="BackgroundRectangle" Grid.ColumnSpan="2" Fill="Red" Opacity="0" Grid.RowSpan="2"/>
                                <Rectangle x:Name="InvalidVisualElement" Grid.ColumnSpan="2" Fill="#FFF7D8DB" Opacity="0" Grid.RowSpan="2"/>
                                <sdk1:DataGridRowHeader x:Name="RowHeader" sdk1:DataGridFrozenGrid.IsFrozen="True" Grid.RowSpan="3"/>
                                <sdk1:DataGridCellsPresenter x:Name="CellsPresenter" Grid.Column="1" sdk1:DataGridFrozenGrid.IsFrozen="True"/>
                                <sdk1:DataGridDetailsPresenter x:Name="DetailsPresenter" Grid.Column="1" Grid.Row="1"/>
                                <Rectangle x:Name="BottomGridLine" Grid.Column="1" HorizontalAlignment="Stretch" Height="1" Grid.Row="2"/>
                            </sdk1:DataGridFrozenGrid>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

and this is for the converter:

```<code>public class RowStyleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (((CustomClass)value).PropertyToBeWatched == "1")
                return App.Current.Resources["Red"] as SolidColorBrush;
            else
                return App.Current.Resources["Green"] as SolidColorBrush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
</code>```

It basically gets and sets the solidcolorbrush based on the property "PropertyToBeWatched".

Hope this helps

Title: Datagrid rowbackground color

Body:
I created a sample CustomClass:

public class CustomClass
    {
        public string PropertyToBeWatched { get; set; }
    }

Created a list:

MyList = new ObservableCollection<CustomClass>();
            MyList.Add(new CustomClass() { PropertyToBeWatched = "1"});
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });
            MyList.Add(new CustomClass() { PropertyToBeWatched = "2" });

Then created the Datagrid:

<sdk:DataGrid ItemsSource="{Binding MyList}" RowStyle="{StaticResource Style1}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Binding="{Binding PropertyToBeWatched}" Header="Property1"/>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

Then the resources:

xmlns:sdk1="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
             xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

 <SolidColorBrush x:Key="Red" Color="#FFFF0000" />
        <SolidColorBrush x:Key="Green" Color="#FF00FF00" />

        <Style x:Key="Style1" TargetType="sdk:DataGridRow">
            <Setter Property="IsTabStop" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="sdk:DataGridRow">
                        <Grid Background="{Binding Converter={StaticResource Test}}">
                            <sdk1:DataGridFrozenGrid x:Name="Root">
                                <sdk1:DataGridFrozenGrid.Resources>
                                    <Storyboard x:Key="DetailsVisibleTransition">
                                        <DoubleAnimation Duration="00:00:0.1" Storyboard.TargetProperty="ContentHeight" Storyboard.TargetName="DetailsPresenter"/>
                                    </Storyboard>
                                </sdk1:DataGridFrozenGrid.Resources>
                                            <sdk1:DataGridFrozenGrid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition/>
                            </sdk1:DataGridFrozenGrid.ColumnDefinitions>
                                <sdk1:DataGridFrozenGrid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                </sdk1:DataGridFrozenGrid.RowDefinitions>
                                                                                <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="NormalAlternatingRow">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="NormalSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="MouseOverSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="UnfocusedSelected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundRectangle"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="UnfocusedEditing"/>
                                    <VisualState x:Name="NormalEditing"/>
                                    <VisualState x:Name="MouseOverUnfocusedEditing"/>
                                    <VisualState x:Name="MouseOverEditing"/>
                                    <VisualState x:Name="MouseOverUnfocusedSelected"/>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="ValidationStates">
                                    <VisualState x:Name="Valid"/>
                                    <VisualState x:Name="Invalid">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="BackgroundRectangle">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="InvalidVisualElement"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                                <Rectangle x:Name="BackgroundRectangle" Grid.ColumnSpan="2" Fill="Red" Opacity="0" Grid.RowSpan="2"/>
                                <Rectangle x:Name="InvalidVisualElement" Grid.ColumnSpan="2" Fill="#FFF7D8DB" Opacity="0" Grid.RowSpan="2"/>
                                <sdk1:DataGridRowHeader x:Name="RowHeader" sdk1:DataGridFrozenGrid.IsFrozen="True" Grid.RowSpan="3"/>
                                <sdk1:DataGridCellsPresenter x:Name="CellsPresenter" Grid.Column="1" sdk1:DataGridFrozenGrid.IsFrozen="True"/>
                                <sdk1:DataGridDetailsPresenter x:Name="DetailsPresenter" Grid.Column="1" Grid.Row="1"/>
                                <Rectangle x:Name="BottomGridLine" Grid.Column="1" HorizontalAlignment="Stretch" Height="1" Grid.Row="2"/>
                            </sdk1:DataGridFrozenGrid>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

and this is for the converter:

public class RowStyleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (((CustomClass)value).PropertyToBeWatched == "1")
                return App.Current.Resources["Red"] as SolidColorBrush;
            else
                return App.Current.Resources["Green"] as SolidColorBrush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }

It basically gets and sets the solidcolorbrush based on the property "PropertyToBeWatched".

Hope this helps


问:
R data.table values depending on previous row
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}
```

<p>and here's the output:</p>

```     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10
```

Can someone help me improve the code?

答:
Note: This is not a general answer to the OP's problem, just to the toy example posted.

Your iterations for a and b are on a cycle every six iterations, and c is a cumulative sum. As a result, it does not have to be computed iteratively, but has a closed form solution for any iteration #:

```<code>f = function(i, a0 = 1, b0 = 2, c0 = 2.5){
  trio = c(a0, a0+b0, b0)
  a = c(trio, -trio)
  b = -c(tail(a, 1L), head(a, -1L))

  cs = cumsum(a/b)
  c6 = tail(cs, 1L)

  k = (i - 1L) %/% 6L
  ii = 1L + (i - 1L) %% 6L

  list(a = a[ii], b = b[ii], c = c0 + k*c6 + cs[ii])
}

library(data.table)
DT = data.table(iter = 1:10)[, c("a", "b", "c") := f(iter)][]

    iter  a  b          c
 1:    1  1  2  3.0000000
 2:    2  3 -1  0.0000000
 3:    3  2 -3 -0.6666667
 4:    4 -1 -2 -0.1666667
 5:    5 -3  1 -3.1666667
 6:    6 -2  3 -3.8333333
 7:    7  1  2 -3.3333333
 8:    8  3 -1 -6.3333333
 9:    9  2 -3 -7.0000000
10:   10 -1 -2 -6.5000000
</code>```

That is, you can just skip ahead to any iteration:

```<code>> setDT(f(10))[]
    a  b    c
1: -1 -2 -6.5
> setDT(f(100))[]
    a  b      c
1: -1 -2 -101.5
</code>```

Body:
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}

and here's the output:

     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10

Can someone help me improve the code?

Body:
Note: This is not a general answer to the OP's problem, just to the toy example posted.

Your iterations for a and b are on a cycle every six iterations, and c is a cumulative sum. As a result, it does not have to be computed iteratively, but has a closed form solution for any iteration #:

f = function(i, a0 = 1, b0 = 2, c0 = 2.5){
  trio = c(a0, a0+b0, b0)
  a = c(trio, -trio)
  b = -c(tail(a, 1L), head(a, -1L))

  cs = cumsum(a/b)
  c6 = tail(cs, 1L)

  k = (i - 1L) %/% 6L
  ii = 1L + (i - 1L) %% 6L

  list(a = a[ii], b = b[ii], c = c0 + k*c6 + cs[ii])
}

library(data.table)
DT = data.table(iter = 1:10)[, c("a", "b", "c") := f(iter)][]

    iter  a  b          c
 1:    1  1  2  3.0000000
 2:    2  3 -1  0.0000000
 3:    3  2 -3 -0.6666667
 4:    4 -1 -2 -0.1666667
 5:    5 -3  1 -3.1666667
 6:    6 -2  3 -3.8333333
 7:    7  1  2 -3.3333333
 8:    8  3 -1 -6.3333333
 9:    9  2 -3 -7.0000000
10:   10 -1 -2 -6.5000000

That is, you can just skip ahead to any iteration:

> setDT(f(10))[]
    a  b    c
1: -1 -2 -6.5
> setDT(f(100))[]
    a  b      c
1: -1 -2 -101.5


问:
Light Weight Render Pipeline is not supported in Oculus Go? Because the app crashes when opening
Is LWRP supported on Oculus Go or not? I am using Unity 2019.1.0f2 version and I have changed every setting in Unity, but somehow the application always crashes before the scene even loads.

Will this also occur in Oculus Quest? Is there any work around?

答: I was dealing with a similar issue on Quest + Unity 2019 and what solved it for me was removing Vulkan Graphics API Options in Player Settings. If it's on "Auto", just uncheck it and remove Vulkan. After that LWRP worked for Oculus Quest.</p>


问:
Pass parameters to a component from a parent controller
I am using Angularjs 1.7 and I am trying to pass an array from the parent controller to the component.How can I pass arraySteps and selectedSteps to the component.

I tried the following but didn't work. I am not getting the arraySteps in the component controller

ulMultiselect.component.js

```<code>angular.module('ulMultiselect.module').component('ulMultiselect', {
    templateUrl: 'app/components/ulMultiselect/ulMultiselect.template.html',
    controller: 'ulMultiselect.controller',
    bindings: {
        arraySteps: '<'
    },
    transclude: true
});
</code>```

ulMultiselect.controller.js

```<code>angular.module('ulMultiselect.module').controller('ulMultiselect.controller',
function () {
    var self = this;
    self.$onInit = function () {
        if (typeof self.arraySteps === 'undefined') {
            self.arraySteps = [];
        }
    };
});
</code>```

ulMultiselect.template.html

```<code><div layout="row">
    <md-input-container style="width:100%">
        <label>Steps</label>
        <md-select ng-model="$ctrl.selectedSteps" multiple>
            <md-option ng-value="step.StepName" ng-repeat="step in $ctrl.arraySteps">{{step.StepName}}</md-option>
        </md-select>
    </md-input-container>
</div>
</code>```

mainTest.html

```<code><ul-Multiselect arraySteps="$ctrl.steps"></ul-Multiselect>
</code>```

mainTest.controller.js

```<code>angular.module('view.mainTest.module').controller('view.mainTest.controller',
function () {
    var self = this;
    self.$onInit = function () {
        self.steps = [{ StepName: "Step1" }, { StepName: "Step2" }, { StepName: "Step3" }];
    };
});
</code>```

答:
The one-way binding needs to be normalized to kebab-case:

```<code>̶<̶u̶l̶-̶M̶u̶l̶t̶i̶s̶e̶l̶e̶c̶t̶ ̶a̶r̶r̶a̶y̶S̶t̶e̶p̶s̶=̶"̶$̶c̶t̶r̶l̶.̶s̶t̶e̶p̶s̶"̶>̶<̶/̶u̶l̶-̶M̶u̶l̶t̶i̶s̶e̶l̶e̶c̶t̶>̶
<ul-multiselect array-steps="$ctrl.steps"></ul-multiselect>
</code>```

For more information, see

AngularJS Developer Guide - Directive Normalization

Body:
I am using Angularjs 1.7 and I am trying to pass an array from the parent controller to the component.How can I pass arraySteps and selectedSteps to the component.

I tried the following but didn't work. I am not getting the arraySteps in the component controller

ulMultiselect.component.js

angular.module('ulMultiselect.module').component('ulMultiselect', {
    templateUrl: 'app/components/ulMultiselect/ulMultiselect.template.html',
    controller: 'ulMultiselect.controller',
    bindings: {
        arraySteps: '<'
    },
    transclude: true
});

ulMultiselect.controller.js

angular.module('ulMultiselect.module').controller('ulMultiselect.controller',
function () {
    var self = this;
    self.$onInit = function () {
        if (typeof self.arraySteps === 'undefined') {
            self.arraySteps = [];
        }
    };
});

ulMultiselect.template.html

    <md-input-container style="width:100%">
        Steps
        <md-select ng-model="$ctrl.selectedSteps" multiple>
            <md-option ng-value="step.StepName" ng-repeat="step in $ctrl.arraySteps">{{step.StepName}}</md-option>
        </md-select>
    </md-input-container>

mainTest.html

mainTest.controller.js

angular.module('view.mainTest.module').controller('view.mainTest.controller',
function () {
    var self = this;
    self.$onInit = function () {
        self.steps = [{ StepName: "Step1" }, { StepName: "Step2" }, { StepName: "Step3" }];
    };
});

Body:
The one-way binding needs to be normalized to kebab-case:

̶<̶u̶l̶-̶M̶u̶l̶t̶i̶s̶e̶l̶e̶c̶t̶ ̶a̶r̶r̶a̶y̶S̶t̶e̶p̶s̶=̶"̶$̶c̶t̶r̶l̶.̶s̶t̶e̶p̶s̶"̶>̶<̶/̶u̶l̶-̶M̶u̶l̶t̶i̶s̶e̶l̶e̶c̶t̶>̶
<ul-multiselect array-steps="$ctrl.steps"></ul-multiselect>

For more information, see

AngularJS Developer Guide - Directive Normalization


问:
Java fx-8. How to configure path to local image using fxml file
I have some troubles configuring path to local image in my javaFX application.
I want to use icon to my button, but it's not working for local images, only with external resources. This is my code:

```<code>            <Button fx:id="magicWangButton" mnemonicParsing="false" onAction="#magicWang" text="Magic wang">
                <graphic>
                    <ImageView fitHeight="20.0" fitWidth="20.0" pickOnBounds="true" preserveRatio="true">
                        <image>
                            <!--<Image url="/fxml/img/magic-wang.png" />-->

                            <Image url="https://i.stack.imgur.com/y1evM.png" />
                            <!--<Image url="/fxml/img/site-logo.png" />-->
                            <Image url="img/magic-wang.png"/>
                        </image>
                    </ImageView>
                </graphic>
            </Button>
</code>```

this string work's fine:

```<code><Image url="https://i.stack.imgur.com/y1evM.png" />
</code>```

, but others...
My image located in path: resources/fxml/img/
all fxml files located in fxml directory.
I saw other questions and answers but it uses configuration in java files, but it is not what I looking for.

答:
You can specify a path relative to the fxml by starting the attribute value with @, see Introduction to FXML: Location Resolution

<Image url="@img/site-logo.png" />
```

Body:
I have some troubles configuring path to local image in my javaFX application.
I want to use icon to my button, but it's not working for local images, only with external resources. This is my code:

            <Button fx:id="magicWangButton" mnemonicParsing="false" onAction="#magicWang" text="Magic wang">
                <graphic>
                    <ImageView fitHeight="20.0" fitWidth="20.0" pickOnBounds="true" preserveRatio="true">
                        <image>

                            <Image url="https://i.stack.imgur.com/y1evM.png" />

                            <Image url="img/magic-wang.png"/>
                        </image>
                    </ImageView>
                </graphic>
            </Button>

this string work's fine:

<Image url="https://i.stack.imgur.com/y1evM.png" />

, but others...
My image located in path: resources/fxml/img/
all fxml files located in fxml directory.
I saw other questions and answers but it uses configuration in java files, but it is not what I looking for.