问:
Jetpack Compose Smart Recomposition
I'm doing experiments to comprehend recomposition and smart recomposition and made a sample

Sorry for the colors, they are generated with Random.nextIn() to observe recomposition visually, setting colors has no effect on recomposition, tried without changing colors either.

What's in gif is composed of three parts

Sample1

```<code>@Composable
private fun Sample1() {

    Column(
        modifier = Modifier
            .background(getRandomColor())
            .fillMaxWidth()
            .padding(4.dp)
    ) {
        var counter by remember { mutableStateOf(0) }

        Text("Sample1", color = getRandomColor())

        Button(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 4.dp),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                counter++
            }) {
            Text("Counter: $counter", color = getRandomColor())
        }
    }
}
</code>```

I have no questions here since smart composition works as expected, Text on top is not reading changes in counter so recomposition only occurs for Text inside Button.

Sample2

```<code>@Composable
private fun Sample2() {
    Column(
        modifier = Modifier.background(getRandomColor())
    ) {

        var update1 by remember { mutableStateOf(0) }
        var update2 by remember { mutableStateOf(0) }

        println("ROOT")
        Text("Sample2", color = getRandomColor())

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 4.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                update1++
            },
            shape = RoundedCornerShape(5.dp)
        ) {

            println(" Button1")

            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )

        }

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = { update2++ },
            shape = RoundedCornerShape(5.dp)
        ) {
            println(" Button 2")

            Text(
                text = "Update2: $update2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

        Column(
            modifier = Modifier.background(getRandomColor())
        ) {

            println(" Inner Column")
            var update3 by remember { mutableStateOf(0) }

            Button(
                modifier = Modifier
                    .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                    .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
                onClick = { update3++ },
                shape = RoundedCornerShape(5.dp)
            ) {

                println("✅ Button 3")
                Text(
                    text = "Update2: $update2, Update3: $update3",
                    textAlign = TextAlign.Center,
                    color = getRandomColor()
                )

            }
        }

        Column() {
            println("☕ Bottom Column")
            Text(
                text = "Sample2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

    }
}
</code>```

It also works as expected each mutableState is updating only the scope they have been observed in. Only Text that observes update2 and update3 is changed when either of these mutableStates are updated.

Sample3

```<code>@Composable
private fun Sample3() {
    Column(
        modifier = Modifier.background(getRandomColor())
    ) {

        var update1 by remember { mutableStateOf(0) }
        var update2 by remember { mutableStateOf(0) }

        println("ROOT")
        Text("Sample3", color = getRandomColor())

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 4.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                update1++
            },
            shape = RoundedCornerShape(5.dp)
        ) {

            println(" Button1")

            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )

        }

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = { update2++ },
            shape = RoundedCornerShape(5.dp)
        ) {
            println(" Button 2")

            Text(
                text = "Update2: $update2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

        Column {

            println(" Inner Column")
            var update3 by remember { mutableStateOf(0) }

            Button(
                modifier = Modifier
                    .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                    .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
                onClick = { update3++ },
                shape = RoundedCornerShape(5.dp)
            ) {

                println("✅ Button 3")
                Text(
                    text = "Update2: $update2, Update3: $update3",
                    textAlign = TextAlign.Center,
                    color = getRandomColor()
                )

            }
        }
       //  Reading update1 causes entire composable to recompose
        Column(
            modifier = Modifier.background(getRandomColor())
        ) {
            println("☕ Bottom Column")
            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }
    }
}
</code>```

Only difference between Sample2 and Sample3 is Text at the bottom is reading update1 mutableState which causing entire composable to be recomposed. As you can see in gif changing update1 recomposes or changes entire color schema for Sample3.

What's the reason for recomposing entire composable?

```<code>        Column(
            modifier = Modifier.background(getRandomColor())
        ) {
            println("☕ Bottom Column")
            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }
    }
</code>```

答:
To have smart recomposition scopes play a pivotal role. You can check Vinay Gaba's What is “donut-hole skipping” in Jetpack Compose? article.

Leland Richardson explains in this tweet as

The part that is "donut hole skipping" is the fact that a new lambda
being passed into a composable (ie Button) can recompose without
recompiling the rest of it. The fact that the lambda are recompose
scopes are necessary for you to be able to do this,  but not
sufficient

In other words, composable lambda are "special" :)

We wanted to do this for a long time but thought it was too
complicated until @chuckjaz had the brilliant realization that if the
lambdas were state objects, and invokes were reads, then this is
exactly the result

You can also check other answers about smart recomposition here, and here.

https://dev.to/zachklipp/scoped-recomposition-jetpack-compose-what-happens-when-state-changes-l78

When a State is read it triggers recomposition in nearest scope. And a scope is a function that is not marked with inline and returns Unit. Column, Row and Box are inline functions and because of that they don't create scopes.

Created RandomColorColumn that take other Composables and its scope content: @Composable () -> Unit

```<code>@Composable
fun RandomColorColumn(content: @Composable () -> Unit) {

    Column(
        modifier = Modifier
            .padding(4.dp)
            .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp))
            .background(getRandomColor())
            .padding(4.dp)
    ) {
        content()
    }
}
</code>```

And replaced

```<code> Column(
        modifier = Modifier.background(getRandomColor())
    ) {
        println("☕ Bottom Column")
        Text(
            text = "Update1: $update1",
            textAlign = TextAlign.Center,
            color = getRandomColor()
        )
    }
}
</code>```

with

```<code>    RandomColorColumn() {

        println("☕ Bottom Column")
        /*
             Observing update(mutableState) does NOT causes entire composable to recompose
         */
        Text(
            text = " Update1: $update1",
            textAlign = TextAlign.Center,
            color = getRandomColor()
        )
    }
}
</code>```

Only this scope gets updated as expected and we have smart recomposition.

What causes Text, or any Composable, inside Column to not have a scope, thus being recomposed when a mutableState value changes is Column having inline keyword in function signature.

```<code>@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope.() -> Unit
) {
    val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment)
    Layout(
        content = { ColumnScopeInstance.content() },
        measurePolicy = measurePolicy,
        modifier = modifier
    )
}
</code>```

If you add inline to RandomColorColumn function signature you will see that it causes whole Composable to recompose.

Compose uses call sites defined as

The call site is the source code location in which a composable is
called. This influences its place in Composition, and therefore, the
UI tree.

If during a recomposition a composable calls different composables
than it did during the previous composition, Compose will identify
which composables were called or not called and for the composables
that were called in both compositions, Compose will avoid recomposing
them if their inputs haven't changed.

Consider the following example:

```<code>@Composable
fun LoginScreen(showError: Boolean) {
    if (showError) {
        LoginError()
    }
    LoginInput() // This call site affects where LoginInput is placed in Composition
}

@Composable
fun LoginInput() { /* ... */ }
</code>```

Call site of a Composable function affects smart recomposition, and having inline keyword in a Composable sets its child Composables call site same level, not one level below.

For anyone interested here is the github repo to play/test recomposition

Title: Jetpack Compose Smart Recomposition

Body:
I'm doing experiments to comprehend recomposition and smart recomposition and made a sample

Sorry for the colors, they are generated with Random.nextIn() to observe recomposition visually, setting colors has no effect on recomposition, tried without changing colors either.

What's in gif is composed of three parts

Sample1

@Composable
private fun Sample1() {

    Column(
        modifier = Modifier
            .background(getRandomColor())
            .fillMaxWidth()
            .padding(4.dp)
    ) {
        var counter by remember { mutableStateOf(0) }

        Text("Sample1", color = getRandomColor())

        Button(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 4.dp),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                counter++
            }) {
            Text("Counter: $counter", color = getRandomColor())
        }
    }
}

I have no questions here since smart composition works as expected, Text on top is not reading changes in counter so recomposition only occurs for Text inside Button.

Sample2

@Composable
private fun Sample2() {
    Column(
        modifier = Modifier.background(getRandomColor())
    ) {

        var update1 by remember { mutableStateOf(0) }
        var update2 by remember { mutableStateOf(0) }

        println("ROOT")
        Text("Sample2", color = getRandomColor())

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 4.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                update1++
            },
            shape = RoundedCornerShape(5.dp)
        ) {

            println(" Button1")

            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )

        }

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = { update2++ },
            shape = RoundedCornerShape(5.dp)
        ) {
            println(" Button 2")

            Text(
                text = "Update2: $update2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

        Column(
            modifier = Modifier.background(getRandomColor())
        ) {

            println(" Inner Column")
            var update3 by remember { mutableStateOf(0) }

            Button(
                modifier = Modifier
                    .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                    .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
                onClick = { update3++ },
                shape = RoundedCornerShape(5.dp)
            ) {

                println("✅ Button 3")
                Text(
                    text = "Update2: $update2, Update3: $update3",
                    textAlign = TextAlign.Center,
                    color = getRandomColor()
                )

            }
        }

        Column() {
            println("☕ Bottom Column")
            Text(
                text = "Sample2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

    }
}

It also works as expected each mutableState is updating only the scope they have been observed in. Only Text that observes update2 and update3 is changed when either of these mutableStates are updated.

Sample3

@Composable
private fun Sample3() {
    Column(
        modifier = Modifier.background(getRandomColor())
    ) {

        var update1 by remember { mutableStateOf(0) }
        var update2 by remember { mutableStateOf(0) }

        println("ROOT")
        Text("Sample3", color = getRandomColor())

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 4.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = {
                update1++
            },
            shape = RoundedCornerShape(5.dp)
        ) {

            println(" Button1")

            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )

        }

        Button(
            modifier = Modifier
                .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                .fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
            onClick = { update2++ },
            shape = RoundedCornerShape(5.dp)
        ) {
            println(" Button 2")

            Text(
                text = "Update2: $update2",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }

        Column {

            println(" Inner Column")
            var update3 by remember { mutableStateOf(0) }

            Button(
                modifier = Modifier
                    .padding(start = 8.dp, end = 8.dp, top = 2.dp)
                    .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(backgroundColor = getRandomColor()),
                onClick = { update3++ },
                shape = RoundedCornerShape(5.dp)
            ) {

                println("✅ Button 3")
                Text(
                    text = "Update2: $update2, Update3: $update3",
                    textAlign = TextAlign.Center,
                    color = getRandomColor()
                )

            }
        }
       //  Reading update1 causes entire composable to recompose
        Column(
            modifier = Modifier.background(getRandomColor())
        ) {
            println("☕ Bottom Column")
            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }
    }
}

Only difference between Sample2 and Sample3 is Text at the bottom is reading update1 mutableState which causing entire composable to be recomposed. As you can see in gif changing update1 recomposes or changes entire color schema for Sample3.

What's the reason for recomposing entire composable?

        Column(
            modifier = Modifier.background(getRandomColor())
        ) {
            println("☕ Bottom Column")
            Text(
                text = "Update1: $update1",
                textAlign = TextAlign.Center,
                color = getRandomColor()
            )
        }
    }

Body:
To have smart recomposition scopes play a pivotal role. You can check Vinay Gaba's What is “donut-hole skipping” in Jetpack Compose? article.

Leland Richardson explains in this tweet as

The part that is "donut hole skipping" is the fact that a new lambda
being passed into a composable (ie Button) can recompose without
recompiling the rest of it. The fact that the lambda are recompose
scopes are necessary for you to be able to do this,  but not
sufficient

In other words, composable lambda are "special" :)

We wanted to do this for a long time but thought it was too
complicated until @chuckjaz had the brilliant realization that if the
lambdas were state objects, and invokes were reads, then this is
exactly the result

You can also check other answers about smart recomposition here, and here.

https://dev.to/zachklipp/scoped-recomposition-jetpack-compose-what-happens-when-state-changes-l78

When a State is read it triggers recomposition in nearest scope. And a scope is a function that is not marked with inline and returns Unit. Column, Row and Box are inline functions and because of that they don't create scopes.

Created RandomColorColumn that take other Composables and its scope content: @Composable () -> Unit

@Composable
fun RandomColorColumn(content: @Composable () -> Unit) {

    Column(
        modifier = Modifier
            .padding(4.dp)
            .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp))
            .background(getRandomColor())
            .padding(4.dp)
    ) {
        content()
    }
}

And replaced

 Column(
        modifier = Modifier.background(getRandomColor())
    ) {
        println("☕ Bottom Column")
        Text(
            text = "Update1: $update1",
            textAlign = TextAlign.Center,
            color = getRandomColor()
        )
    }
}

with

    RandomColorColumn() {

        println("☕ Bottom Column")
        /*
             Observing update(mutableState) does NOT causes entire composable to recompose
         */
        Text(
            text = " Update1: $update1",
            textAlign = TextAlign.Center,
            color = getRandomColor()
        )
    }
}

Only this scope gets updated as expected and we have smart recomposition.

What causes Text, or any Composable, inside Column to not have a scope, thus being recomposed when a mutableState value changes is Column having inline keyword in function signature.

@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope.() -> Unit
) {
    val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment)
    Layout(
        content = { ColumnScopeInstance.content() },
        measurePolicy = measurePolicy,
        modifier = modifier
    )
}

If you add inline to RandomColorColumn function signature you will see that it causes whole Composable to recompose.

Compose uses call sites defined as

The call site is the source code location in which a composable is
called. This influences its place in Composition, and therefore, the
UI tree.

If during a recomposition a composable calls different composables
than it did during the previous composition, Compose will identify
which composables were called or not called and for the composables
that were called in both compositions, Compose will avoid recomposing
them if their inputs haven't changed.

Consider the following example:

@Composable
fun LoginScreen(showError: Boolean) {
    if (showError) {
        LoginError()
    }
    LoginInput() // This call site affects where LoginInput is placed in Composition
}

@Composable
fun LoginInput() { /* ... */ }

Call site of a Composable function affects smart recomposition, and having inline keyword in a Composable sets its child Composables call site same level, not one level below.

For anyone interested here is the github repo to play/test recomposition


来源: stackexchange

问:
Unable to override role name with meta/main.yml role_name for molecule test
I created an example role project with this  command:

```<code> molecule init role cranberry --driver-name docker
</code>```

If you pull it:

```<code>git clone git@github.com:natemarks/cranberry.git
</code>```

and run it:

```<code>make clean-venv && make molecule-test
</code>```

It should set up the virtualenv and run the test successfully because it uses the project directory name 'cranberry' as the role name. If I want to override that so that my role_name is still 'cranberry' but my project directory is 'role-cranberry'. I should be able to just rename/move the project directory to 'role-cranberry' and set meta/main.yaml role_name: cranberry.  This doesn't work.

similarly , I should be able to break the test without changing the project directory by just adding some garbage value to meta/main.yml role_name,like;

```<code>galaxy_info:
  role_name: badrole
</code>```

but that doesn't work either.

I think I'm using the latest python packages. Thanks in advance for tips

答:
You are mixing up two things: the repository name in which the role is versioned remotely and the directory name in which the role is stored on your disk and which makes-up the name by which ansible knows that role on your local machine.

The role_name in your metadata only gives an indication to https://galaxy.ansible.com (i.e. the online service) of which name it should use when importing it. That name will be used later if you install the role from the ansible-galaxy command line (e.g. ansible-galaxy role install geerlingguy.security).

When molecule runs from your current role dir, it adds the current directory to the ANSIBLE_ROLES_PATH. From there, ansible is simply doing a normal role lookup and will know your current role after its containing directory name.

You gave as an example a role and its molecule test security by Jeff Geerling. The git repository name is ansible-role-security.

If you do a basic clone (git clone https://github.com/geerlingguy/ansible-role-security) and run the test from the freshly cloned directory (cd ansible-role-security && molecule test), it will fail complaining that geerlingguy.security was not found.

If you rename the directory to the expected name (cd .. && mv ansible-role-security geerlinguy.security && cd geerlinguy.security && molecule test), it will now succeed.

Note that the best practice to import such a role is to install it through ansible galaxy either by

installing it from the galaxy web site
```<code>ansible-galaxy role install geerlingguy.security
</code>```

installing it from a git repo using a requirement file

roles/requirements.yml

- src: https://github.com/geerlingguy/ansible-role-security
  scm: git
  version: main
  name: geerlingguy.security
```
</li>
<li>Install role keeping the scm metadata (to interact with git, commit...)
```ansible-galaxy role install -fgr roles/requirements.yaml
```

To finish with, you can have a look at the ci-pipeline in the same example repository where you will see that the author has forced the working directory name as well as the git clone directory target to align the directory name to what is expected for running the tests.

ContentLicense: CC BY-SA 4.0

Body:
I created an example role project with this  command:

 molecule init role cranberry --driver-name docker

If you pull it:

git clone git@github.com:natemarks/cranberry.git

and run it:

make clean-venv && make molecule-test

It should set up the virtualenv and run the test successfully because it uses the project directory name 'cranberry' as the role name. If I want to override that so that my role_name is still 'cranberry' but my project directory is 'role-cranberry'. I should be able to just rename/move the project directory to 'role-cranberry' and set meta/main.yaml role_name: cranberry.  This doesn't work.

similarly , I should be able to break the test without changing the project directory by just adding some garbage value to meta/main.yml role_name,like;

galaxy_info:
  role_name: badrole

but that doesn't work either.

I think I'm using the latest python packages. Thanks in advance for tips

Body:
You are mixing up two things: the repository name in which the role is versioned remotely and the directory name in which the role is stored on your disk and which makes-up the name by which ansible knows that role on your local machine.

The role_name in your metadata only gives an indication to https://galaxy.ansible.com (i.e. the online service) of which name it should use when importing it. That name will be used later if you install the role from the ansible-galaxy command line (e.g. ansible-galaxy role install geerlingguy.security).

When molecule runs from your current role dir, it adds the current directory to the ANSIBLE_ROLES_PATH. From there, ansible is simply doing a normal role lookup and will know your current role after its containing directory name.

You gave as an example a role and its molecule test security by Jeff Geerling. The git repository name is ansible-role-security.

If you do a basic clone (git clone https://github.com/geerlingguy/ansible-role-security) and run the test from the freshly cloned directory (cd ansible-role-security && molecule test), it will fail complaining that geerlingguy.security was not found.

If you rename the directory to the expected name (cd .. && mv ansible-role-security geerlinguy.security && cd geerlinguy.security && molecule test), it will now succeed.

Note that the best practice to import such a role is to install it through ansible galaxy either by

installing it from the galaxy web site

ansible-galaxy role install geerlingguy.security

installing it from a git repo using a requirement file

roles/requirements.yml

- src: https://github.com/geerlingguy/ansible-role-security
  scm: git
  version: main
  name: geerlingguy.security

Install role keeping the scm metadata (to interact with git, commit...)

ansible-galaxy role install -fgr roles/requirements.yaml

To finish with, you can have a look at the ci-pipeline in the same example repository where you will see that the author has forced the working directory name as well as the git clone directory target to align the directory name to what is expected for running the tests.


问:
How to fix encoding in react?
I built a react app but special char (like => é,è,ç...) appears like this :

I found this solution here but I just don't understand how to apply it, can anyone please help how to use it

答: Found a question that looks similar to the one you've asked about and it has this answer as the accepted answer</p>

Title: How to fix encoding in react?


问:
When does std::format throw an exception?
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView.

Today I am using std::stringstream to format messages:

```<code>int value = 5;
std::stringstream ss;
ss << "value=" << value;
OutputDebugStringA(ss.str().c_str());
</code>```

This is rather verbose and I am looking into using std::format() instead:

```<code>int value = 5;
OutputDebugStringA(std::format("value={0}",value).c_str());
</code>```

which seems nice.
My only worry is that std::format may throw an exception.
But under which circumstances?

It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program.

EDIT:
example that throws an exception:

```<code>std::string s = std::format("value={},{}", value);
</code>```

答:
According to cppreference:

https://en.cppreference.com/w/cpp/utility/format/format

Throws std::bad_alloc on allocation failure. Also propagates exception thrown by any formatter.

The million dollar question: when is std::bad_alloc thrown??

Again in the doc:

std::bad_alloc is the type of the object thrown as exceptions by the allocation functions to report failure to allocate storage.

Body:
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView.

Today I am using std::stringstream to format messages:

int value = 5;
std::stringstream ss;
ss << "value=" << value;
OutputDebugStringA(ss.str().c_str());

This is rather verbose and I am looking into using std::format() instead:

int value = 5;
OutputDebugStringA(std::format("value={0}",value).c_str());

which seems nice.
My only worry is that std::format may throw an exception.
But under which circumstances?

It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program.

EDIT:
example that throws an exception:

std::string s = std::format("value={},{}", value);


问:
Does assetlinks.json file for Android App Links have a size limit like the iOS counterpart?
In order to only allow authorized apps to open https links, Android has App Links, and iOS has Universal Links. In both, one needs to upload a file, viz. assetlinks.json for Android and apple-app-site-association file for iOS on https://domain.name/.well-known/ path. I could find that for iOS, the file size can be max 128 KB, however, couldn't find any such information for assetlinks.json. Is there a size limit for it?

答:
Officially there is no limit mentioned any where in the document. But when I have tried using Branch.io common link in my app, the app links verification was failing when app was installed. Figured out the same from the logs and the reason for the same was read timeout.

The file hosted here is very huge and mentions a lot of apps which support Branch's bnc.lt links.

https://bnc.lt/.well-known/assetlinks.json

Which causes it to fail as Android fails to verify the same during installation and hence also causes other links configured also not to work.

A file link with just 8-10 apps won't be that huge and won't cause a problem.


问:
monaco editor set range text color programatically without css in style.css
I am trying to use Monaco editor to create an application for simple text processing
(eg: select a range of text, change its foreground and background color).
Is there an easy way to do this? or even best, is there any best free opensource rich text like Grammarly, I just need some mark-down features with color.

This example uses a CSS class name, but not what I am looking for.
https://microsoft.github.io/monaco-editor/playground.html#interacting-with-the-editor-line-and-inline-decorations
The CSS is predefined, not dynamically generated.

Thanks

Body:
Actually my solution is still using deltaDecorations just like official playground examples.

But in practice, you can use sass iteration to speed up creating batch styles, below is my real project code, FYI:

  $palette: (
    '30': rgba(0,0,0,1),
    '31': rgba(247,49,49,1),
    '32': rgba(127,202,84,1),
    '33': rgba(246,222,84,1),
    '34': rgba(0,0,255,1),
    '35': rgba(255,0,255,1),
    '36': rgba(0,255,255,1),
    '37': rgba(255,255,255,1),
    '90': rgba(128,128,128,1),
    '40': rgba(0,0,0,1),
    '41': rgba(247,49,49,1),
    '42': rgba(127,202,84,1),
    '43': rgba(246,222,84,1),
    '44': rgba(0,0,255,1),
    '45': rgba(255,0,255,1),
    '46': rgba(0,255,255,1),
    '47': rgba(255,255,255,1),
  );
  @each $key, $color in $palette {
    :deep(.monaco-color-#{$key}) {
      color: $color;
    }
  }


问:
Workaround for SSL bug
There seems to be a bug in the SSL implementation of an https server I'm connecting to; the problem initially arose in my application, but I've since been debugging / reproducing it with the openssl commandline utility, so I'm fairly certain it has nothing to do with my application at this point.

If I connect to the remote server with no options other than -connect, OpenSSL sends an SSLv2 CLIENT-HELLO, the server responds with a TLSv1 ServerHello, and everything proceeds normally.

If I connect with -ssl3, OpenSSL sends an SSLv3 ClientHello, the server responds with an SSLv3 ServerHello, and again everything is fine.

However, if I connect with -no_ssl2 or -tls1, OpenSSL sends a TLSv1 ClientHello, and the server responds with "TLS 1.0 Alert [length 0002], fatal unexpected_message", which is the original problem I was seeing in my application.

There are a number of possible workarounds that suggest themselves at this point, but I'm ideally looking for something generic, rather than special-casing this particular server, so I'm hoping there's some kind of "standard" workaround for this.

答:
It seems the problem was actually caused by the RFC 5077 session ticket extension; disabling this (by passing -no_ticket to openssl, for example) allowed the TLSv1 ClientHello to succeed with the remote server. Since I have no particular need for this extension in my application, this workaround seems like the most appropriate way to proceed.

A little research suggests that the problem may just be empty session ticket extensions, but I didn't bother trying to figure out whether this particular server had problems with non-empty ones.

OwnerDisplayName: mithrandi

ContentLicense: CC BY-SA 2.5

Title: Workaround for SSL bug


问:
How to show a yaml file content in a table with filename in the header section of the table using in LINUX commandline
I would like to customize my bash/zsh in such a way so that when I cat (view) a yaml file it shows the content in a table with filename in the header section in it using in LINUX command line. I am referring to the attached image.

答:
The cat clone bat would exactly do that when fed with a .yaml file.

If you setup an alias alias cat=bat (eg. in your .bashrc) then calling cat would have the same behaviour.


问:
formatting tables in xlsx files
I am trying to create function for formatting every tables in xlsx file.

I want to save N numbers of Tables in xlsx and formatting all the tables in xlsx file. but its formatting the first table only.

```<code>library(openxlsx)
format_tbl <- function(workbook,tbll){
  setColWidths(workbook, 1,cols = 1:ncol(tbll), widths = "auto")
  writeData(workbook, 1, tbll)

  header_style <- createStyle(fgFill = "#009DE0", halign = "center", textDecoration = "bold", fontColour = "white")
  addStyle(workbook, 1, style = header_style, rows = 1, cols = 1:ncol(tbll))

  name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
  addStyle(workbook, 1, style = name_style, rows = 2 : nrow(tbll), cols = 1)

  percent_style <- createStyle(halign = "center", numFmt = "00%")
  addStyle(workbook, 1, style = percent_style, rows = 2 : nrow(tbll), which(colnames(tbll) == "disp"))

  center_style <- createStyle(halign = "center")
  addStyle(workbook, 1, style = center_style, rows = 2 : nrow(tbll), cols = which(!colnames(tbll) %in% c("model", "disp")), gridExpand = TRUE)

  total_style <- createStyle(fgFill = "#009DE0", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = total_style, rows = nrow(tbll), cols = 1:ncol(tbll))

  Na_style <- createStyle(fgFill = "#00968F", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = Na_style, rows = nrow(tbll)+1, cols = 1:ncol(tbll))

}

t1 = mtcars
t2 = mtcars[,1:5]
t3= iris
t4 = iris[1:8,]

format_tbl(workbook=wb,tbll=t1)
format_tbl(workbook=wb,tbll=t2)
format_tbl(workbook=wb,tbll=t3)
format_tbl(workbook=wb,tbll=t4)

tbls <- list(t1,t2,t3,t4)

startRows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1

fn <- tempfile(fileext = "xlsx")

wb <- createWorkbook()
addWorksheet(wb, "tbls")
mapply(function(tbl, startRow) writeData(wb, "tbls", x = tbl, startRow = startRow), tbls, startRows)

saveWorkbook(wb, fn, overwrite = TRUE) %>% file.show(.)

</code>```

答:
Here is a function that formats each element of the list of data frames. With R scoping rules what they are, notice format_tbls returns a workbook object, which allows the updates that occur inside the function to be passed to the object that is eventually saved to a file.

Note: I attempted to follow the formatting shown in the original question, but I have excluded the 'Na_string' addStyle call. This probably was intended to highlight NA's in the data.frames. The current code does not do that.

```<code>library(openxlsx)
library(expss)

# make list of tables
tbls <- list( mtcars,mtcars[,1:5],iris,iris[1:8,])

# function that formats each table in a list
format_tbls <- function(tbls, wb){

  # add worksheet
  addWorksheet(wb, "tbls")

  # calculate start rows
  rows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1

  # styles
  header_style <- createStyle(fgFill = "#009DE0", halign = "center", textDecoration = "bold", fontColour = "white")
  name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
  percent_style <- createStyle(halign = "center", numFmt = "00%")
  center_style <- createStyle(halign = "center")
  total_style <- createStyle(fgFill = "#009DE0", halign = "center", fontColour = "black", fontSize = 12)
  Na_style <- createStyle(fgFill = "#00968F", halign = "center", fontColour = "black", fontSize = 12)

  setColWidths(wb, 1,cols = 1:100, widths = "auto")

  for(i in seq_along(tbls)){

    #writeData(wb, 1, tbls[[i]], startRow = rows[i]) # this works
    expss::xl_write(tbls[[i]], wb, "tbls", row = rows[i]) # this also works

    addStyle(wb, 1, style = total_style, rows = rows[i]:(rows[i]+nrow(tbls[[i]])),
             cols = 1:ncol(tbls[[i]]), gridExpand = TRUE) # set

    addStyle(wb, 1, style = header_style,
             rows = rows[i], cols = 1:ncol(tbls[[i]]))

    addStyle(wb, 1, style = name_style,
             rows = rows[i]+1, cols = 1)

    addStyle(wb, 1, style = percent_style, rows = rows[i]+1,
               which(colnames(tbls[[i]]) == "disp"))

    addStyle(wb, 1, style = center_style, rows = rows[i]+1,
             cols = which(!colnames(tbls[i]) %in% c("model", "disp")), gridExpand = TRUE)

    # not included. probably needs conditional formatting to detect NA values?
    #addStyle(wb, 1, style = Na_style, rows = rows[i]+1:(rows[i]+nrow(tbls[[i]])),
             #cols = 1:ncol(tbls[[i]]), gridExpand = TRUE) # set stack = TRUE to allow styles to be merged
  }

  return(wb)

}

# create wb
wb <- createWorkbook()

# use function
wb <- format_tbls(tbls = tbls, wb = wb)

# save to file
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)
</code>```

Title: formatting tables in xlsx files

Body:
I am trying to create function for formatting every tables in xlsx file.

I want to save N numbers of Tables in xlsx and formatting all the tables in xlsx file. but its formatting the first table only.

library(openxlsx)
format_tbl <- function(workbook,tbll){
  setColWidths(workbook, 1,cols = 1:ncol(tbll), widths = "auto")
  writeData(workbook, 1, tbll)

  header_style <- createStyle(fgFill = "#009DE0", halign = "center", textDecoration = "bold", fontColour = "white")
  addStyle(workbook, 1, style = header_style, rows = 1, cols = 1:ncol(tbll))

  name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
  addStyle(workbook, 1, style = name_style, rows = 2 : nrow(tbll), cols = 1)

  percent_style <- createStyle(halign = "center", numFmt = "00%")
  addStyle(workbook, 1, style = percent_style, rows = 2 : nrow(tbll), which(colnames(tbll) == "disp"))

  center_style <- createStyle(halign = "center")
  addStyle(workbook, 1, style = center_style, rows = 2 : nrow(tbll), cols = which(!colnames(tbll) %in% c("model", "disp")), gridExpand = TRUE)

  total_style <- createStyle(fgFill = "#009DE0", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = total_style, rows = nrow(tbll), cols = 1:ncol(tbll))

  Na_style <- createStyle(fgFill = "#00968F", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = Na_style, rows = nrow(tbll)+1, cols = 1:ncol(tbll))

}

t1 = mtcars
t2 = mtcars[,1:5]
t3= iris
t4 = iris[1:8,]

format_tbl(workbook=wb,tbll=t1)
format_tbl(workbook=wb,tbll=t2)
format_tbl(workbook=wb,tbll=t3)
format_tbl(workbook=wb,tbll=t4)

tbls <- list(t1,t2,t3,t4)

startRows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1

fn <- tempfile(fileext = "xlsx")

wb <- createWorkbook()
addWorksheet(wb, "tbls")
mapply(function(tbl, startRow) writeData(wb, "tbls", x = tbl, startRow = startRow), tbls, startRows)

saveWorkbook(wb, fn, overwrite = TRUE) %>% file.show(.)

Body:
Here is a function that formats each element of the list of data frames. With R scoping rules what they are, notice format_tbls returns a workbook object, which allows the updates that occur inside the function to be passed to the object that is eventually saved to a file.

Note: I attempted to follow the formatting shown in the original question, but I have excluded the 'Na_string' addStyle call. This probably was intended to highlight NA's in the data.frames. The current code does not do that.

library(openxlsx)
library(expss)

# make list of tables
tbls <- list( mtcars,mtcars[,1:5],iris,iris[1:8,])

# function that formats each table in a list
format_tbls <- function(tbls, wb){

  # add worksheet
  addWorksheet(wb, "tbls")

  # calculate start rows
  rows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1

  # styles
  header_style <- createStyle(fgFill = "#009DE0", halign = "center", textDecoration = "bold", fontColour = "white")
  name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
  percent_style <- createStyle(halign = "center", numFmt = "00%")
  center_style <- createStyle(halign = "center")
  total_style <- createStyle(fgFill = "#009DE0", halign = "center", fontColour = "black", fontSize = 12)
  Na_style <- createStyle(fgFill = "#00968F", halign = "center", fontColour = "black", fontSize = 12)

  setColWidths(wb, 1,cols = 1:100, widths = "auto")

  for(i in seq_along(tbls)){

    #writeData(wb, 1, tbls[[i]], startRow = rows[i]) # this works
    expss::xl_write(tbls[[i]], wb, "tbls", row = rows[i]) # this also works

    addStyle(wb, 1, style = total_style, rows = rows[i]:(rows[i]+nrow(tbls[[i]])),
             cols = 1:ncol(tbls[[i]]), gridExpand = TRUE) # set

    addStyle(wb, 1, style = header_style,
             rows = rows[i], cols = 1:ncol(tbls[[i]]))

    addStyle(wb, 1, style = name_style,
             rows = rows[i]+1, cols = 1)

    addStyle(wb, 1, style = percent_style, rows = rows[i]+1,
               which(colnames(tbls[[i]]) == "disp"))

    addStyle(wb, 1, style = center_style, rows = rows[i]+1,
             cols = which(!colnames(tbls[i]) %in% c("model", "disp")), gridExpand = TRUE)

    # not included. probably needs conditional formatting to detect NA values?
    #addStyle(wb, 1, style = Na_style, rows = rows[i]+1:(rows[i]+nrow(tbls[[i]])),
             #cols = 1:ncol(tbls[[i]]), gridExpand = TRUE) # set stack = TRUE to allow styles to be merged
  }

  return(wb)

}

# create wb
wb <- createWorkbook()

# use function
wb <- format_tbls(tbls = tbls, wb = wb)

# save to file
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)


问:
Spring boot Kubernetes readyness / liveness probes 404 on local deployment
I've enabled liveness and readiness endpoints using Spring Boot actuator (v2.6.1)

What I have is the following config:

```<code>management
  endpoint:
    health:
      enabled: true
      probes:
        enabled: true
      group:
        readiness:
          include: readinessStateProbeIndicator
        exploratory:
          include:
            - livenessState
            - readinessState
            - ping
          show-details: always
  health:
    enabled: true
    probes:
      livenessstate:
        enabled: true
      readinessstate:
        enabled: true
</code>```

Probably endpoint.health.enabled, endpoint.health.group.explotatory... are not required but I set it because I've seen it for some working solution, but I don't think there will affect if are not needed.

What I have read, but not in official docs, is that this endpoints are not available in a local deployment (running the application). Is this the reason why I'm getting 404 when I try to call http://localhost:8080/actuator/health/readiness and /actuator/health/liveness or I'm missing something?

I checked some posts like this but it seems management.health.enabled has been deprecated and management.endpoint.health.probes.enabled should be enough.

Thanks

答:
This is the setting I was looking for, and it works fine on localhost:</p>
```<code>endpoint:
    health:
      probes:
        enabled: true
      enabled: true
</code>```

Body:
I've enabled liveness and readiness endpoints using Spring Boot actuator (v2.6.1)

What I have is the following config:

management
  endpoint:
    health:
      enabled: true
      probes:
        enabled: true
      group:
        readiness:
          include: readinessStateProbeIndicator
        exploratory:
          include:
            - livenessState
            - readinessState
            - ping
          show-details: always
  health:
    enabled: true
    probes:
      livenessstate:
        enabled: true
      readinessstate:
        enabled: true

Probably endpoint.health.enabled, endpoint.health.group.explotatory... are not required but I set it because I've seen it for some working solution, but I don't think there will affect if are not needed.

What I have read, but not in official docs, is that this endpoints are not available in a local deployment (running the application). Is this the reason why I'm getting 404 when I try to call http://localhost:8080/actuator/health/readiness and /actuator/health/liveness or I'm missing something?

I checked some posts like this but it seems management.health.enabled has been deprecated and management.endpoint.health.probes.enabled should be enough.

Thanks

Body:
This is the setting I was looking for, and it works fine on localhost:

endpoint:
    health:
      probes:
        enabled: true
      enabled: true


问:
vue-template-compiler/package.json missing module with every new project
Currently, I switched from linux to windows and started to create a programming environment. I don't remember similar problem on linux, but to the point:
1. Installed Node.js
2. npm install -g @vue/cli for CLI install
3. vue create my-app
4. npm run serve
Gave:

```<code>    ERROR Error: Cannot find module 'vue-template-compiler/package.json'
Error: Cannot find module 'vue-template-compiler/package.json'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at api.chainWebpack.webpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\config\base.js:73:32)
at webpackChainFns.forEach.fn (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:225:40)
at Array.forEach (<anonymous>)
at Service.resolveChainableWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:225:26)
at Service.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:229:48)
at PluginAPI.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\PluginAPI.js:115:25)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test@0.1.0 serve: vue-cli-service serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test@0.1.0 serve script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Michal\AppData\Roaming\npm-cache_logs\2018-12-09T203013_264Z-debug.log`
</code>```

5. vue-cli-service inspect --mode production

```<code>ERROR Error: Cannot find module 'vue-template-compiler/package.json'

Error: Cannot find module 'vue-template-compiler/package.json'
at Function.Module.resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module.load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at api.chainWebpack.webpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\config\base.js:73:32)
at webpackChainFns.forEach.fn (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:225:40)
at Array.forEach (<anonymous>)
at Service.resolveChainableWebpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:225:26)
at Service.resolveWebpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:229:48)
at PluginAPI.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\PluginAPI.js:115:25)`
</code>```

6. I tried through vue ui but same story, so I installed missing module for created app: npm install vue-template-compiler, went smooth, package added.
7. vue run serve, starting building and then:

```<code> ERROR  Failed to compile with 3 errors
This dependency was not found:

* vue in ./src/main.js, ./src/App.vue and 1 other

To install it, you can run: npm install --save vue
</code>```

8. So i run npm install --save vue and then at last npm run serve worked:

```<code> DONE  Compiled successfully in 2536ms
</code>```

Every single project I created with vue crate my-app-name must have had vue-template-compiler installed manually, but then I tried with create vue init webpack-simple my-next-app everything build up without problems and run.
What is difference with creating new vue project with create - create a new project powered by vue-cli-service and init - generate a project from a remote template (legacy API, requires @vue/cli-init)

Ps. Yes i tried install vue-template-compiler globally.

```<code>Environment Info:

  System:
    OS: Windows 10
    CPU: (8) x64 Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz
  Binaries:
    Node: Not Found
    Yarn: Not Found
    npm: 5.0.4 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: 42.17134.1.0
  npmPackages:
    @vue/babel-preset-app:  3.2.0
    @vue/cli-overlay:  3.2.0
    @vue/cli-plugin-babel: ^3.2.0 => 3.2.0
    @vue/cli-plugin-eslint: ^3.2.0 => 3.2.1
    @vue/cli-service: ^3.2.0 => 3.2.0
    @vue/cli-shared-utils:  3.2.0
    @vue/component-compiler-utils:  2.3.0
    @vue/preload-webpack-plugin:  1.1.0
    @vue/web-component-wrapper:  1.2.0
    babel-helper-vue-jsx-merge-props:  2.0.3
    babel-plugin-transform-vue-jsx:  4.0.1
    eslint-plugin-vue: ^5.0.0-0 => 4.7.1
    vue-eslint-parser:  2.0.3
    vue-hot-reload-api:  2.3.1
    vue-loader:  15.4.2
    vue-style-loader:  4.1.2
    vue-template-es2015-compiler:  1.6.0
  npmGlobalPackages:
    @vue/cli: Not Found
</code>```

Why vue does not see @vue/cli in new project? That was first thing I installed :/

答:
I am running Vue 2 and got this error seemingly out of nowhere. The solutions for Vue 3 did not work for me. What worked was rolling back to an old version of package.json. I had run npm fix and updated packages were introduced which caused this error. Reverting those solved the issue.

delete package-lock.json

change package.json to a version that worked

run npm install

Body:
Currently, I switched from linux to windows and started to create a programming environment. I don't remember similar problem on linux, but to the point:
1. Installed Node.js
2. npm install -g @vue/cli for CLI install
3. vue create my-app
4. npm run serve
Gave:

    ERROR Error: Cannot find module 'vue-template-compiler/package.json'
Error: Cannot find module 'vue-template-compiler/package.json'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at api.chainWebpack.webpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\config\base.js:73:32)
at webpackChainFns.forEach.fn (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:225:40)
at Array.forEach (<anonymous>)
at Service.resolveChainableWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:225:26)
at Service.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\Service.js:229:48)
at PluginAPI.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\PluginAPI.js:115:25)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test@0.1.0 serve: vue-cli-service serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test@0.1.0 serve script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Michal\AppData\Roaming\npm-cache_logs\2018-12-09T203013_264Z-debug.log`

5. vue-cli-service inspect --mode production

ERROR Error: Cannot find module 'vue-template-compiler/package.json'

Error: Cannot find module 'vue-template-compiler/package.json'
at Function.Module.resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module.load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at api.chainWebpack.webpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\config\base.js:73:32)
at webpackChainFns.forEach.fn (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:225:40)
at Array.forEach (<anonymous>)
at Service.resolveChainableWebpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:225:26)
at Service.resolveWebpackConfig (D:\vueTest\test\nodemodules\@vue\cli-service\lib\Service.js:229:48)
at PluginAPI.resolveWebpackConfig (D:\vueTest\test\node_modules\@vue\cli-service\lib\PluginAPI.js:115:25)`

6. I tried through vue ui but same story, so I installed missing module for created app: npm install vue-template-compiler, went smooth, package added.
7. vue run serve, starting building and then:

 ERROR  Failed to compile with 3 errors
This dependency was not found:

* vue in ./src/main.js, ./src/App.vue and 1 other

To install it, you can run: npm install --save vue

8. So i run npm install --save vue and then at last npm run serve worked:

 DONE  Compiled successfully in 2536ms

Every single project I created with vue crate my-app-name must have had vue-template-compiler installed manually, but then I tried with create vue init webpack-simple my-next-app everything build up without problems and run.
What is difference with creating new vue project with create - create a new project powered by vue-cli-service and init - generate a project from a remote template (legacy API, requires @vue/cli-init)

Ps. Yes i tried install vue-template-compiler globally.

Environment Info:

  System:
    OS: Windows 10
    CPU: (8) x64 Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz
  Binaries:
    Node: Not Found
    Yarn: Not Found
    npm: 5.0.4 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: 42.17134.1.0
  npmPackages:
    @vue/babel-preset-app:  3.2.0
    @vue/cli-overlay:  3.2.0
    @vue/cli-plugin-babel: ^3.2.0 => 3.2.0
    @vue/cli-plugin-eslint: ^3.2.0 => 3.2.1
    @vue/cli-service: ^3.2.0 => 3.2.0
    @vue/cli-shared-utils:  3.2.0
    @vue/component-compiler-utils:  2.3.0
    @vue/preload-webpack-plugin:  1.1.0
    @vue/web-component-wrapper:  1.2.0
    babel-helper-vue-jsx-merge-props:  2.0.3
    babel-plugin-transform-vue-jsx:  4.0.1
    eslint-plugin-vue: ^5.0.0-0 => 4.7.1
    vue-eslint-parser:  2.0.3
    vue-hot-reload-api:  2.3.1
    vue-loader:  15.4.2
    vue-style-loader:  4.1.2
    vue-template-es2015-compiler:  1.6.0
  npmGlobalPackages:
    @vue/cli: Not Found

Why vue does not see @vue/cli in new project? That was first thing I installed :/


问:
Javascript - Show a div with a given class after clicking on a given class
Several spans that have certain classes.

```<code><span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>
</code>```

Clicking on a given  displays a DIV that contains the same class. How to do it?

```<code><div class="click-1">Hello!</div>
<div class="click-2">Hello 2!</div>
<div class="click-3">Hello 3!</div>
<div class="click-4">Hello 4!</div>
</code>```

I need such a solution because it is development on the CMS side. User can add much more span and div. So the script has to be universal.

答:
```<code>var testElements = document.getElementsByClassName('click-1');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
  return testElement.nodeName === 'DIV';
});
</code>```

Body:
Several spans that have certain classes.

1
2
4
4

Clicking on a given  displays a DIV that contains the same class. How to do it?

Hello!

Hello 2!

Hello 3!

Hello 4!

I need such a solution because it is development on the CMS side. User can add much more span and div. So the script has to be universal.


问:
setting image for UIBarButtonItem - image stretched
When I try to use UIBarButtonItem's "initWithImage" to initialize a navigation bar custom image, it comes out washed-up and stretched against a black navigation bar. This is how I create it:

```<code>UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"gear.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(showSetting:)];
</code>```

Here is what it looks like:

Any idea if it's a problem with the image? I got it from a set of icons I bought.

答:
The displayed images on bar button items are 'derived' from the source image (it uses only the alpha channel values in rendering but that all looks ok in your image).  Its possibly just not the right size - you might need to open the image file and crop it to the right size.

You could also try looking at whether setting the imageInsets property (inherited by UIBarButtonItem from UIBarItem) can be used to adjust the size in a way to stop it getting stretched.

Doco on the bar item images says the following:

The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points.

ContentLicense: CC BY-SA 3.0

Body:
When I try to use UIBarButtonItem's "initWithImage" to initialize a navigation bar custom image, it comes out washed-up and stretched against a black navigation bar. This is how I create it:

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"gear.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(showSetting:)];

Here is what it looks like:

Any idea if it's a problem with the image? I got it from a set of icons I bought.


问:
String Join with Mutiple String
I am trying to concat my string with List.

For Example:

```<code>ID Number, List string 1, List string 2...
</code>```

because I need the "," between the string.
So I use string join but it won't work.
Here is my code below.

My code:

```<code>String IDnumber = string.Join(", ", owner.ID , customerID.Select(x => x.ID).ToList());
</code>```

I am wondering if there is any workaround.

答:
In your example, you appear to be using

```<code>public static string Join (char separator, params object?[] values)
</code>```

Therefore, you are essentially calling

```<code>string.Join(", ", [first part], [second part])
</code>```

If your owner.ID is 123, with your list of customers, I presume your output looks something like this

```<code>123, System.Collections.Generic.List`1[System.String]
</code>```

This happens because you are not joining your owner.ID and each element in the list of customers, but rather the owner.ID and the entire list of customers as one object.

The correct approach would be something like

```<code>string.Join(", ", customerID.Select(x => x.ID).Prepend(owner.ID))
</code>```

or

```<code>$"{owner.ID}, {string.Join(", ", customerID.Select(x => x.ID))}"
</code>```

or

```<code>new StringBuilder().Append(owner.ID).Append(", ").Append(string.Join(", ", customerID.Select(x => x.ID))).ToString()
</code>```

Title: String Join with Mutiple String

Body:
I am trying to concat my string with List.

For Example:

ID Number, List string 1, List string 2...

because I need the "," between the string.
So I use string join but it won't work.
Here is my code below.

My code:

String IDnumber = string.Join(", ", owner.ID , customerID.Select(x => x.ID).ToList());

I am wondering if there is any workaround.

Body:
In your example, you appear to be using

public static string Join (char separator, params object?[] values)

Therefore, you are essentially calling

string.Join(", ", [first part], [second part])

If your owner.ID is 123, with your list of customers, I presume your output looks something like this

123, System.Collections.Generic.List`1[System.String]

This happens because you are not joining your owner.ID and each element in the list of customers, but rather the owner.ID and the entire list of customers as one object.

The correct approach would be something like

string.Join(", ", customerID.Select(x => x.ID).Prepend(owner.ID))

or

$"{owner.ID}, {string.Join(", ", customerID.Select(x => x.ID))}"

or

new StringBuilder().Append(owner.ID).Append(", ").Append(string.Join(", ", customerID.Select(x => x.ID))).ToString()


问:
Updating column according to index within group
In our databases we have a table called conditions which references a table called attributes.

So it looks like this (ignoring some other columns that aren't relevant to the question)

id
attribute_id
execution_index

1
1000
1

2
1000
2

3
1000
1

4
2000
1

5
2000
2

6
2000
2

In theory the combination of attribute_id and execution_index should always be unique, but in practice they're not, and the software ends up essentially using the id to decide which comes first between two conditions with the same execution index. We want to add a uniqueness constraint to the table, but before we do that we need to update the execution indexes. So essentially we want to group them by attribute_id, order them by execution_index then id, and give them new execution indexes so that it becomes

id
attribute_id
execution_index

1
1000
1

2
1000
3

3
1000
2

4
2000
1

5
2000
2

6
2000
3

I'm not sure how to do this without just ordering by attribute_id, execution_index, id and then iterating through incrementing the execution_index by 1 each time and resetting it to be 1 whenever the attribute_id changes. (That would work but it'd be slow and someone is going to have to run this script on several dozen databases so I'd rather it didn't take more than a couple of seconds per database.)

Really I'd like to do something along the lines of

```<code>UPDATE c
SET c.execution_index = [this needs to be the index within the group somehow]
FROM condities c
GROUP BY c.attribute_id
ORDER BY c.execution_index asc, c.id asc
</code>```

But I don't know how to make that actually work.

答:
```<code>WITH cte AS
(
    SELECT
        *,
        ROW_NUMBER() OVER
        (
            PARTITION BY attribute_id
            ORDER BY execution_index, id
        ) AS RowNum
    FROM condities
)
UPDATE cte
SET execution_index = RowNum
</code>```

Body:
In our databases we have a table called conditions which references a table called attributes.

So it looks like this (ignoring some other columns that aren't relevant to the question)

id
attribute_id
execution_index

1
1000
1

2
1000
2

3
1000
1

4
2000
1

5
2000
2

6
2000
2

In theory the combination of attribute_id and execution_index should always be unique, but in practice they're not, and the software ends up essentially using the id to decide which comes first between two conditions with the same execution index. We want to add a uniqueness constraint to the table, but before we do that we need to update the execution indexes. So essentially we want to group them by attribute_id, order them by execution_index then id, and give them new execution indexes so that it becomes

id
attribute_id
execution_index

1
1000
1

2
1000
3

3
1000
2

4
2000
1

5
2000
2

6
2000
3

I'm not sure how to do this without just ordering by attribute_id, execution_index, id and then iterating through incrementing the execution_index by 1 each time and resetting it to be 1 whenever the attribute_id changes. (That would work but it'd be slow and someone is going to have to run this script on several dozen databases so I'd rather it didn't take more than a couple of seconds per database.)

Really I'd like to do something along the lines of

UPDATE c
SET c.execution_index = [this needs to be the index within the group somehow]
FROM condities c
GROUP BY c.attribute_id
ORDER BY c.execution_index asc, c.id asc

But I don't know how to make that actually work.


问:
Is default navbar on Material UI exist like Bootstrap does?
I found it hard to create navbar with menus on Material UI. I've read it's AppBar documentation. But, it seems they doesn't provide that feature.

1) Material UI AppBar

2) React Bootstrap Navbar

How to create navbar menu on Material UI like React Bootstrap does ?

答:
You need to use the appbar (https://mui.com/components/app-bar/) component with something like the drawer component (https://mui.com/components/drawers/).

Apparently this 'atomic' approach is what MUI proposes to us (configure the building blocks and make your own components). I struggled a bit with grasping this component as well but I m starting to get the hang of it.


问:
Container-fluid padding is not working in css and navbar brand css not working
```<code>    <!DOCTYPE html>
    <html>

    <head>
      <meta charset="utf-8">
      <title>TinDog</title>
      <link rel="stylesheet" href="css/styles.css">
      <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
      <link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

    </head>

    <body>
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

      <section id="title">
        <div class="container-fluid">

          <!-- Nav Bar -->
          <nav class="navbar  navbar-expand-lg navbar-dark">
            <a class="navbar-brand" href="">tindog</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                  <a class="nav-link" href="">Contact</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="">Pricing</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="">Download</a>
                </li>
              </ul>
            </div>
          </nav>
</section>
</body>

</html>

    .container-fluid
{
  padding-left: 150px;
  padding-right: 150px;

}
.navbar-brand
{
  font-family: 'Ubuntu', sans-serif;
  font-size: 32px:
}
</code>```

The above CSS doesn't give padding to container-fluid, it takes the default padding, same behaviour when I give it in percentage adding even If I style the code within the HTML, the padding gets cancelled. Using container also doesn't improve the situation, the padding also gets cancelled. The code works in codeply.com but doesn't work in the atom. The font size of the navbar brand is also not changing, I tried all the values rem, px and %, then also it shows no change.

答: Try to shift the bootstrap link above your styles.css file because that should be the hierarchical order. Default bootstrap styling will be applied then.</p>

Body:
    <!DOCTYPE html>

      <meta charset="utf-8">
      <title>TinDog</title>
      <link rel="stylesheet" href="css/styles.css">
      <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      <link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

            tindog
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                  Contact

                  Pricing

                  Download

    .container-fluid
{
  padding-left: 150px;
  padding-right: 150px;

}
.navbar-brand
{
  font-family: 'Ubuntu', sans-serif;
  font-size: 32px:
}

The above CSS doesn't give padding to container-fluid, it takes the default padding, same behaviour when I give it in percentage adding even If I style the code within the HTML, the padding gets cancelled. Using container also doesn't improve the situation, the padding also gets cancelled. The code works in codeply.com but doesn't work in the atom. The font size of the navbar brand is also not changing, I tried all the values rem, px and %, then also it shows no change.


问:
Get the NOT IN values into an array in postgres SQL
I am looking to obtain a set of results where I receive a user_id and a collection of books that the user HAS NOT reviewed. I would like the following as the required output:

user_id
Array of books not reviewed

1
{Array of books not reviewed}

2
{Array of books not reviewed}.

Currently there are two tables that this query would require to be pulled from. One contains "reviews" that possesses the user_id of the review, and the book_id that the user HAS reviewed. The book_id is a foreign key to the the "books" table where the total list of books is contained. Therefore for each user_id in the output,  I would require the total list of books, excluding the ones that have been reviewed per user.

See the insert statements below for the reviews and books tables:

Reviews tables -

```<code>CREATE TABLE reviews (
    review_id SERIAL PRIMARY KEY,
    rating INT CHECK (rating BETWEEN 0 AND 10),
    review_text TEXT,
    book_id INT REFERENCES books(id),
    user_id INT
);
</code>```

Example of a snippet of the table data:

review_id
rating
book_id.
user_id

1
8
2
1

2
6
3
3

Books table -

```<code>CREATE TABLE books (
    id SERIAL PRIMARY KEY,
    title VARCHAR(100),
    price_in_pence INTEGER,
    quantity_in_stock INTEGER
);
</code>```

Example of a snippet of books data:

id
title
price_in_pence
quantity_in_stock

1
bookname
549
12

2
LOTR
799
9

I have tried the following query, however this is not dynamic and only works per user_id entered (identified below using '**'):

```<code>SELECT r.user_id,
       array( SELECT b.title
              FROM books b
              WHERE b.id NOT IN (SELECT r.book_id
                                 FROM reviews r
                                 WHERE user_id = <b>'4'</b>)
               ) AS Books_not_reviewed
FROM reviews r
GROUP BY (r.user_id);
</code>```

Apologies I am somewhat new to SQL. Any help would be greatly appreciated. I am using Postgres version 14.1

答:
You can make your query dynamic, if you make the userid as a parameter and use prepared statements.

Also, the below query can give you the list of all books NOT reviewed by each user, you can modify the query to suit your needs.

```<code>select u.userid, array( select bookid from books
where bookid not in (select
           bookid from reviews r
            where r.userid=u.userid) )
    from users u
</code>```

Body:
I am looking to obtain a set of results where I receive a user_id and a collection of books that the user HAS NOT reviewed. I would like the following as the required output:

user_id
Array of books not reviewed

1
{Array of books not reviewed}

2
{Array of books not reviewed}.

Currently there are two tables that this query would require to be pulled from. One contains "reviews" that possesses the user_id of the review, and the book_id that the user HAS reviewed. The book_id is a foreign key to the the "books" table where the total list of books is contained. Therefore for each user_id in the output,  I would require the total list of books, excluding the ones that have been reviewed per user.

See the insert statements below for the reviews and books tables:

Reviews tables -

CREATE TABLE reviews (
    review_id SERIAL PRIMARY KEY,
    rating INT CHECK (rating BETWEEN 0 AND 10),
    review_text TEXT,
    book_id INT REFERENCES books(id),
    user_id INT
);

Example of a snippet of the table data:

review_id
rating
book_id.
user_id

1
8
2
1

2
6
3
3

Books table -

CREATE TABLE books (
    id SERIAL PRIMARY KEY,
    title VARCHAR(100),
    price_in_pence INTEGER,
    quantity_in_stock INTEGER
);

Example of a snippet of books data:

id
title
price_in_pence
quantity_in_stock

1
bookname
549
12

2
LOTR
799
9

I have tried the following query, however this is not dynamic and only works per user_id entered (identified below using '**'):

SELECT r.user_id,
       array( SELECT b.title
              FROM books b
              WHERE b.id NOT IN (SELECT r.book_id
                                 FROM reviews r
                                 WHERE user_id = '4')
               ) AS Books_not_reviewed
FROM reviews r
GROUP BY (r.user_id);

Apologies I am somewhat new to SQL. Any help would be greatly appreciated. I am using Postgres version 14.1

Body:
You can make your query dynamic, if you make the userid as a parameter and use prepared statements.

Also, the below query can give you the list of all books NOT reviewed by each user, you can modify the query to suit your needs.

select u.userid, array( select bookid from books
where bookid not in (select
           bookid from reviews r
            where r.userid=u.userid) )
    from users u


问:
Is jQuery image lazy load still solution for optimizing web load speed
For sometime ago, I notice that few big design blog like SmashingMagazine, Noupe and other implement lazy loading on their image. I suppose this helps in optimizing their load time and save server resource.

Then I come to this jQuery lazyload for image, but the plugin is broke and not working for new browser. Would like to know is lazyload still recommended for optimizing website?

答:
Odd that it is broke.  Maybe it's conflicting with your version of jQuery?

I use lazy load of images. It is a nice technique to use in certain situations.


答:
It looks like you can use an updatable CTE:

```<code>with cte as (
    select *,
      Row_Number() over(partition by attribute_id order by execution_index, id) new
    from conditions
)
update cte set execution_index = new
</code>```

I would suggest adding a new column and first updating that and checking the results are as expected.

Example Fiddle

Title: Updating column according to index within group

Body:
It looks like you can use an updatable CTE:

with cte as (
    select *,
      Row_Number() over(partition by attribute_id order by execution_index, id) new
    from conditions
)
update cte set execution_index = new

I would suggest adding a new column and first updating that and checking the results are as expected.

Example Fiddle


问:
Compare 2 columns in same excel sheet in pandas
In excel sheet i want to compare the 2 columns. The column names like file_1 and file_2. by using these 2 cols want to create the another col like 'diff' by using excel formula [countifs]. In case , if file_1 and file_2 column records matched it should be 0 (Zero) in diff column otherwise it should be 1. But, i am not as excepted result. Could please help anyone.

here is my inputs :

```<code>   file_1    file_2
    G          G
    A          B
    C          F
    E          H
    A          C
    H          E
</code>```

Output Dataframe :

```<code>    file_1       file_2       diff
     G          G              0
     A          B              1
     C          F              1
     E          H              0
     A          C              0
     H          E              0
</code>```

Sample code :

```<code>     df = pd.read_excel('file1.xlsx')
     df1 = df[df['file_1'].isin(df['file_2'])]
     df['diff'] = df1
     print(df)
</code>```

答:
You can use isin and convert to boolean:

```<code>df['diff'] = (~df['file_2'].isin(df['file_1'])).astype(int)
</code>```

output:

```<code>  file_1 file_2  diff
0      G      G     0
1      A      B     1
2      C      F     1
3      E      H     0
4      A      C     0
5      H      E     0
</code>```

Body:
In excel sheet i want to compare the 2 columns. The column names like file_1 and file_2. by using these 2 cols want to create the another col like 'diff' by using excel formula [countifs]. In case , if file_1 and file_2 column records matched it should be 0 (Zero) in diff column otherwise it should be 1. But, i am not as excepted result. Could please help anyone.

here is my inputs :

   file_1    file_2
    G          G
    A          B
    C          F
    E          H
    A          C
    H          E

Output Dataframe :

    file_1       file_2       diff
     G          G              0
     A          B              1
     C          F              1
     E          H              0
     A          C              0
     H          E              0

Sample code :

     df = pd.read_excel('file1.xlsx')
     df1 = df[df['file_1'].isin(df['file_2'])]
     df['diff'] = df1
     print(df)

Body:
You can use isin and convert to boolean:

df['diff'] = (~df['file_2'].isin(df['file_1'])).astype(int)

output:

  file_1 file_2  diff
0      G      G     0
1      A      B     1
2      C      F     1
3      E      H     0
4      A      C     0
5      H      E     0


问:
Bold particular text in string on runtime jQuery
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags

For Example: "I am more #FromSide #FromSide  and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide

Here's my code:

```<code> `$('#custm-field').keyup(function(){`
            `let str = $(this).val();`
            `let arr = str.split(" ");`
            `$(arr).each((i,e)=>{`
                `if(e=="#")`
                `{ // $(e).css('font-weight','bold');`
                    `arr[i].replace(e,"<strong>"+e+"</strong>");}
                    `let newStr = arr.join(" ");`
            `$('#custm-field').val(newStr)`
            `});`
</code>```

答:
I've constructed a solution for you,

First of all, you can't add HTML tags inside the value of an input tag. So you have to make use of contenteditable HTML attribute, by setting it to true contenteditable="true" on any element you can start to edit the content of it (write inside it).

NOTE: I added a background-color to make it visible when its empty

```<code><div contentEditable="true" id="text" style="background-color: #eee;"></div>
</code>```

Your JavaScript (JQuery) would look like this:

Note that your code had many errors I had to fix.

$('#text').keyup(function(){
            // get the div element
            let e = document.querySelector('#text');
            // get only the text inside the element (without the HTML tags)
            let str = e.innerText;
            e.innerHTML = '';
            // create a new element to contain our text because you cant add HTML text inside a DOM element directly
            let tag = document.createElement('div');
            let arr = str.split(" ");
            // this string will contain our HTML and text
            let newStr = ``;
            $(arr).each((i,e)=>{
                if(e[0]=="#")
                {
                    newStr += `<strong>${e}</strong>`;
                }
                else{
                    newStr += `${e}`
                }
                newStr += ` `;
            })
            // add the string to the inner HTML of the element we created
            tag.innerHTML = newStr;
            // append the newly created element inside the div
            e.append(tag);

            // based on Vito Gentile answer
            // this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
            cursorManager.setEndOfContenteditable(e);
        });
```
<p>I made use of the code of this answer, this is where this line <code>cursorManager.setEndOfContenteditable(e);</code> came from. Here is their code for convenience.</p>
<pre class="lang-js prettyprint-override"><code>(function( cursorManager ) {

            //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
            var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

            //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
            Array.prototype.contains = function(obj) {
                var i = this.length;
                while (i--) {
                    if (this[i] === obj) {
                        return true;
                    }
                }
                return false;
            }

            //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
            function canContainText(node) {
                if(node.nodeType == 1) { //is an element node
                    return !voidNodeTags.contains(node.nodeName);
                } else { //is not an element node
                    return false;
                }
            };

            function getLastChildElement(el){
                var lc = el.lastChild;
                while(lc && lc.nodeType != 1) {
                    if(lc.previousSibling)
                        lc = lc.previousSibling;
                    else
                        break;
                }
                return lc;
            }

            //Based on Nico Burns's answer
            cursorManager.setEndOfContenteditable = function(contentEditableElement)
            {

                while(getLastChildElement(contentEditableElement) &&
                    canContainText(getLastChildElement(contentEditableElement))) {
                    contentEditableElement = getLastChildElement(contentEditableElement);
                }

                var range,selection;
                if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
                {
                    range = document.createRange();//Create a range (a range is a like the selection but invisible)
                    range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    selection = window.getSelection();//get the selection object (allows you to change selection)
                    selection.removeAllRanges();//remove any selections already made
                    selection.addRange(range);//make the range you have just created the visible selection
                }
                else if(document.selection)//IE 8 and lower
                {
                    range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                    range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    range.select();//Select the range (make it the visible selection
                }
            }

}( window.cursorManager = window.cursorManager || {}));
</code>```

Hopefully this works like what you want.

Body:
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags

For Example: "I am more #FromSide #FromSide  and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide

Here's my code:

 `$('#custm-field').keyup(function(){`
            `let str = $(this).val();`
            `let arr = str.split(" ");`
            `$(arr).each((i,e)=>{`
                `if(e=="#")`
                `{ // $(e).css('font-weight','bold');`
                    `arr[i].replace(e,""+e+"");}
                    `let newStr = arr.join(" ");`
            `$('#custm-field').val(newStr)`
            `});`

Body:
I've constructed a solution for you,

First of all, you can't add HTML tags inside the value of an input tag. So you have to make use of contenteditable HTML attribute, by setting it to true contenteditable="true" on any element you can start to edit the content of it (write inside it).

NOTE: I added a background-color to make it visible when its empty

<div contentEditable="true" id="text" style="background-color: #eee;"></div>

Your JavaScript (JQuery) would look like this:

Note that your code had many errors I had to fix.

$('#text').keyup(function(){
            // get the div element
            let e = document.querySelector('#text');
            // get only the text inside the element (without the HTML tags)
            let str = e.innerText;
            e.innerHTML = '';
            // create a new element to contain our text because you cant add HTML text inside a DOM element directly
            let tag = document.createElement('div');
            let arr = str.split(" ");
            // this string will contain our HTML and text
            let newStr = ``;
            $(arr).each((i,e)=>{
                if(e[0]=="#")
                {
                    newStr += `<strong>${e}</strong>`;
                }
                else{
                    newStr += `${e}`
                }
                newStr += ` `;
            })
            // add the string to the inner HTML of the element we created
            tag.innerHTML = newStr;
            // append the newly created element inside the div
            e.append(tag);

            // based on Vito Gentile answer
            // this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
            cursorManager.setEndOfContenteditable(e);
        });

I made use of the code of this answer, this is where this line cursorManager.setEndOfContenteditable(e); came from. Here is their code for convenience.

(function( cursorManager ) {

            //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
            var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

            //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
            Array.prototype.contains = function(obj) {
                var i = this.length;
                while (i--) {
                    if (this[i] === obj) {
                        return true;
                    }
                }
                return false;
            }

            //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
            function canContainText(node) {
                if(node.nodeType == 1) { //is an element node
                    return !voidNodeTags.contains(node.nodeName);
                } else { //is not an element node
                    return false;
                }
            };

            function getLastChildElement(el){
                var lc = el.lastChild;
                while(lc && lc.nodeType != 1) {
                    if(lc.previousSibling)
                        lc = lc.previousSibling;
                    else
                        break;
                }
                return lc;
            }

            //Based on Nico Burns's answer
            cursorManager.setEndOfContenteditable = function(contentEditableElement)
            {

                while(getLastChildElement(contentEditableElement) &&
                    canContainText(getLastChildElement(contentEditableElement))) {
                    contentEditableElement = getLastChildElement(contentEditableElement);
                }

                var range,selection;
                if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
                {
                    range = document.createRange();//Create a range (a range is a like the selection but invisible)
                    range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    selection = window.getSelection();//get the selection object (allows you to change selection)
                    selection.removeAllRanges();//remove any selections already made
                    selection.addRange(range);//make the range you have just created the visible selection
                }
                else if(document.selection)//IE 8 and lower
                {
                    range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                    range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    range.select();//Select the range (make it the visible selection
                }
            }

}( window.cursorManager = window.cursorManager || {}));

Hopefully this works like what you want.


问:
Can't access Microsoft To Do list using the MS Graph API
I try to make programm in python to add appointments to Microsoft To Do
I'm using the Microsoft Graph API with following code:

```<code>import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]

cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)

if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')

</code>```

This is the error I get:

```<code>{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}
</code>```

I tried to google the error but I didn't found any solution that worked for me.

答:
Just for Curiosity ,I would like to know have you entered your TENANT_Id and CLIENT_ID in place of "X" and "Y". if yes and still its not working.

Could you please try to run the URL - https://graph.microsoft.com/v1.0/me/todo/lists on Graph explorer and postman. let us know if you are still facing the issue.

Body:
I try to make programm in python to add appointments to Microsoft To Do
I'm using the Microsoft Graph API with following code:

import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]

cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)

if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')

This is the error I get:

{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}

I tried to google the error but I didn't found any solution that worked for me.


问:
iOS - Updating View Controllers in applicationDidBecomeActive
I'm currently developing an iPhone app communicating via REST with a web server.

Each time the app starts it checks for remote data updates. If the data has not been loaded I start an async request in the app delegates applicationDidBecomeActive and show a modal progress view while the request is running. Some of my view controllers also need a data update which should be handled while the same progress view is visible and after the first request has finished.

What is the best approach to handle this scenario? Post a notification to the view controllers after the first request has finished and call back the delegate to dismiss the progress view?
Or is this considered a bad solution?

Best Regards

Carsten

答:
Posting a notification should be used if the sender does not know anything about (should not depend on) the observers. For example, data object posts notification when it changes, so the visual objects connected to it could update themselves.

In your case you need to have a root object, the owner of your view controllers. It may be your Application Delegate or a subclass of a Navigation Controller. Since the owner knows about the view controllers, it can directly tell them to update when the request finishes.

Generally, do not send notifications between the owner and its dependants. Owners can directly call dependants' methods. Dependants can have weak links to their owners and let them know when they update. If you need to make dependants independent on the owner's class, define a delegate protocol.