问:
Using fork() and execlp() to create process hierarchy in C
I MUST use fork() and execlp() to create and annotate the given process hierarchy:

I cannot wrap my head around when each process should be forked in order to reflect this hierarchy, add to that the non-negotiable use of execlp() which replaces the current process image.

Here is what I managed to come up with (please excuse the very non-DRY code, I'm new to these concepts):

```<code>#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <unistd.h>
#include    <errno.h>
#include    <sys/types.h>
#include    <sys/wait.h>

#define oops(m) {perror(m); exit(EXIT_FAILURE);}

int main() {
    pid_t pid1_1, pid1_2, pid1_1_1, pid1_1_2, pid1_2_1, pid1_2_2;

    pid1_1 = fork();

    if (pid1_1 < 0) {
        oops("Fork Failed!");
    }

    // child 1.1
    if (pid1_1 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.1", NULL) < 0)
        oops("Execlp Failed!");

    } else {
        // grandchild 1.1.1
        pid1_1_1 = fork();
        if (pid1_1_1 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_1_1 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.1.1", NULL) < 0)
            oops("Execlp Failed!");
        }
        //grandchild 1.1.2
        pid1_1_2 = fork();
        if (pid1_1_2 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_1_2 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.1.2", NULL) < 0)
            oops("Execlp Failed!");
        }
    }

    pid1_2 = fork();

    if (pid1_2 < 0) {
        oops("Fork Failed!");
    }
    // child 1.2
    if (pid1_2 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.2", NULL) < 0)
        oops("Execlp Failed!");
    } else {
        // grandchild 1.2.1
        pid1_2_1 = fork();
        if (pid1_2_1 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_2_1 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.2.1", NULL) < 0)
            oops("Execlp Failed!");
        }
        // grandchild 1.2.2
        pid1_2_2 = fork();
        if (pid1_2_2 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_2_2 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.2.2", NULL) < 0)
            oops("Execlp Failed!");
        }
    }

    // pid > 0 ==> must be parent
    printf("I am the parent %d\n", getpid());
    /* parent will wait for the child to complete */
    if (waitpid(-1, NULL, 0) < 0)
        printf("-1 from wait() with errno = %d\n", errno);

    printf("Child terminated; parent exiting\n");
    exit(EXIT_SUCCESS);
}
</code>```

My output shows that this hierarchy is not set up correctly. For example, manually stepping through with gdb and finishing the PID for 1.2 terminates the entire process tree (when 1.1 sub-tree should be left in tact).

Any suggestions for where I'm going wrong with logically replicating this process hierarchy would be really appreciated. Thanks!

答:
Any suggestions for where I'm going wrong with logically replicating this process hierarchy would be really appreciated.

Check this part of code at start of your program:

```<code>pid1_1 = fork();
</code>```

this will fork a child process. After this you are doing:

```<code>    if (pid1_1 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.1", NULL) < 0)
        ......
</code>```

That means, now the child process image will be replaced by another process image.

As per picture you have shown, a process is supposed to fork 2 child process before calling execlp(), if it is a parent process in the given process tree. Similar kind of problems are there in below part of your code.

I cannot wrap my head around when each process should be forked in order to reflect this hierarchy, .....

Look at the process tree closely and you will find it as a perfect binary tree where every internal node has 2 child and all leaf nodes are at same level.

That said, every process should create 2 child process and then call execlp() and as soon as you reach to the given height (which is 2 in your case), no child process should fork further.

I will show you how to create the process hierarchy and you can add the execlp() call to replace the current process image with some other process image.

add to that the non-negotiable use of execlp() which replaces the current process image.

I believe, here, the current process means the process which is forking of child processes and this includes the top most process (equivalent to root in tree) as well.

To create the hierarchy of process as perfect binary tree, you can do:

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

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

    int height;

    if (argc != 2) {
        printf ("Invalid number of arguments, exiting..\n");
        exit (0);
    }

    height = atoi (argv[1]);

    if (height < 0) {
        printf ("Invalid input.\n"); // error handling can be better
        exit (0);
    }

    printf ("Parent process, my pid = %d, height = %d\n", getpid(), height);

    for (int i = 0; i < height; ++i) {
        printf ("\nMy pid : %d, current height of tree : %d, forking..\n", getpid(), i);

        pid_t pid = fork();

        if (pid == -1) {
            printf ("Fork failed\n");
        } else if (pid == 0) {
            printf ("My pid = %d, [my parent : %d], I am child 1..\n", getpid(), getppid());

            // this sleep is for sequenced output, otherwise it's not needed
            // sleeping for 1 second
            sleep (1);
            continue;
        }

        pid = fork();

        if (pid == -1) {
            printf ("Fork failed\n");
        } else if (pid == 0) {
            printf ("My pid = %d, [my parent : %d], I am child 2..\n", getpid(), getppid());

            // this sleep is for sequenced output, otherwise it's not needed
            // sleeping for 1 second
            sleep (1);
            continue;
        }

        // break the loop as the current process is done with forking 2 child process
        break;
    }

    // ADD execlp call here

    // This part of code is to just show you the hierarchy.
    // If you add execlp call above then part is not needed.
    while (wait(NULL) > 0);
    printf ("pid %d : I am EXITING\n", getpid());

    // added sleep for sequenced output, otherwise it's not needed
    sleep (1);
    return 0;
}
</code>```

Usage: ./a.out <height_of_process_tree>

Output:

```<code># ./a.out 0
Parent process, my pid = 50807, height = 0
pid 50807 : I am EXITING

# ./a.out 1
Parent process, my pid = 50808, height = 1

My pid : 50808, current height of tree : 0, forking..
My pid = 50809, [my parent : 50808], I am child 1..
My pid = 50810, [my parent : 50808], I am child 2..
pid 50810 : I am EXITING
pid 50809 : I am EXITING
pid 50808 : I am EXITING

# ./a.out 2
Parent process, my pid = 50811, height = 2

My pid : 50811, current height of tree : 0, forking..
My pid = 50812, [my parent : 50811], I am child 1..
My pid = 50813, [my parent : 50811], I am child 2..

My pid : 50812, current height of tree : 1, forking..

My pid : 50813, current height of tree : 1, forking..
My pid = 50814, [my parent : 50812], I am child 1..
My pid = 50815, [my parent : 50813], I am child 1..
My pid = 50816, [my parent : 50812], I am child 2..
My pid = 50817, [my parent : 50813], I am child 2..
pid 50814 : I am EXITING
pid 50815 : I am EXITING
pid 50816 : I am EXITING
pid 50817 : I am EXITING
pid 50812 : I am EXITING
pid 50813 : I am EXITING
pid 50811 : I am EXITING
</code>```

Body:
I MUST use fork() and execlp() to create and annotate the given process hierarchy:

I cannot wrap my head around when each process should be forked in order to reflect this hierarchy, add to that the non-negotiable use of execlp() which replaces the current process image.

Here is what I managed to come up with (please excuse the very non-DRY code, I'm new to these concepts):

#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <unistd.h>
#include    <errno.h>
#include    <sys/types.h>
#include    <sys/wait.h>

#define oops(m) {perror(m); exit(EXIT_FAILURE);}

int main() {
    pid_t pid1_1, pid1_2, pid1_1_1, pid1_1_2, pid1_2_1, pid1_2_2;

    pid1_1 = fork();

    if (pid1_1 < 0) {
        oops("Fork Failed!");
    }

    // child 1.1
    if (pid1_1 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.1", NULL) < 0)
        oops("Execlp Failed!");

    } else {
        // grandchild 1.1.1
        pid1_1_1 = fork();
        if (pid1_1_1 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_1_1 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.1.1", NULL) < 0)
            oops("Execlp Failed!");
        }
        //grandchild 1.1.2
        pid1_1_2 = fork();
        if (pid1_1_2 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_1_2 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.1.2", NULL) < 0)
            oops("Execlp Failed!");
        }
    }

    pid1_2 = fork();

    if (pid1_2 < 0) {
        oops("Fork Failed!");
    }
    // child 1.2
    if (pid1_2 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.2", NULL) < 0)
        oops("Execlp Failed!");
    } else {
        // grandchild 1.2.1
        pid1_2_1 = fork();
        if (pid1_2_1 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_2_1 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.2.1", NULL) < 0)
            oops("Execlp Failed!");
        }
        // grandchild 1.2.2
        pid1_2_2 = fork();
        if (pid1_2_2 < 0) {
            oops("Fork Failed!");
        }
        if (pid1_2_2 == 0) {
            printf("I am the grandchild %d\n", getpid());
            if (execlp("./iam", "iam", "1.2.2", NULL) < 0)
            oops("Execlp Failed!");
        }
    }

    // pid > 0 ==> must be parent
    printf("I am the parent %d\n", getpid());
    /* parent will wait for the child to complete */
    if (waitpid(-1, NULL, 0) < 0)
        printf("-1 from wait() with errno = %d\n", errno);

    printf("Child terminated; parent exiting\n");
    exit(EXIT_SUCCESS);
}

My output shows that this hierarchy is not set up correctly. For example, manually stepping through with gdb and finishing the PID for 1.2 terminates the entire process tree (when 1.1 sub-tree should be left in tact).

Any suggestions for where I'm going wrong with logically replicating this process hierarchy would be really appreciated. Thanks!

Body:
Any suggestions for where I'm going wrong with logically replicating this process hierarchy would be really appreciated.

Check this part of code at start of your program:

pid1_1 = fork();

this will fork a child process. After this you are doing:

    if (pid1_1 == 0) {
        printf("I am the child %d\n", getpid());
        if (execlp("./iam", "iam", "1.1", NULL) < 0)
        ......

That means, now the child process image will be replaced by another process image.

As per picture you have shown, a process is supposed to fork 2 child process before calling execlp(), if it is a parent process in the given process tree. Similar kind of problems are there in below part of your code.

I cannot wrap my head around when each process should be forked in order to reflect this hierarchy, .....

Look at the process tree closely and you will find it as a perfect binary tree where every internal node has 2 child and all leaf nodes are at same level.

That said, every process should create 2 child process and then call execlp() and as soon as you reach to the given height (which is 2 in your case), no child process should fork further.

I will show you how to create the process hierarchy and you can add the execlp() call to replace the current process image with some other process image.

add to that the non-negotiable use of execlp() which replaces the current process image.

I believe, here, the current process means the process which is forking of child processes and this includes the top most process (equivalent to root in tree) as well.

To create the hierarchy of process as perfect binary tree, you can do:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

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

    int height;

    if (argc != 2) {
        printf ("Invalid number of arguments, exiting..\n");
        exit (0);
    }

    height = atoi (argv[1]);

    if (height < 0) {
        printf ("Invalid input.\n"); // error handling can be better
        exit (0);
    }

    printf ("Parent process, my pid = %d, height = %d\n", getpid(), height);

    for (int i = 0; i < height; ++i) {
        printf ("\nMy pid : %d, current height of tree : %d, forking..\n", getpid(), i);

        pid_t pid = fork();

        if (pid == -1) {
            printf ("Fork failed\n");
        } else if (pid == 0) {
            printf ("My pid = %d, [my parent : %d], I am child 1..\n", getpid(), getppid());

            // this sleep is for sequenced output, otherwise it's not needed
            // sleeping for 1 second
            sleep (1);
            continue;
        }

        pid = fork();

        if (pid == -1) {
            printf ("Fork failed\n");
        } else if (pid == 0) {
            printf ("My pid = %d, [my parent : %d], I am child 2..\n", getpid(), getppid());

            // this sleep is for sequenced output, otherwise it's not needed
            // sleeping for 1 second
            sleep (1);
            continue;
        }

        // break the loop as the current process is done with forking 2 child process
        break;
    }

    // ADD execlp call here

    // This part of code is to just show you the hierarchy.
    // If you add execlp call above then part is not needed.
    while (wait(NULL) > 0);
    printf ("pid %d : I am EXITING\n", getpid());

    // added sleep for sequenced output, otherwise it's not needed
    sleep (1);
    return 0;
}

Usage: ./a.out <height_of_process_tree>

Output:

# ./a.out 0
Parent process, my pid = 50807, height = 0
pid 50807 : I am EXITING

# ./a.out 1
Parent process, my pid = 50808, height = 1

My pid : 50808, current height of tree : 0, forking..
My pid = 50809, [my parent : 50808], I am child 1..
My pid = 50810, [my parent : 50808], I am child 2..
pid 50810 : I am EXITING
pid 50809 : I am EXITING
pid 50808 : I am EXITING

# ./a.out 2
Parent process, my pid = 50811, height = 2

My pid : 50811, current height of tree : 0, forking..
My pid = 50812, [my parent : 50811], I am child 1..
My pid = 50813, [my parent : 50811], I am child 2..

My pid : 50812, current height of tree : 1, forking..

My pid : 50813, current height of tree : 1, forking..
My pid = 50814, [my parent : 50812], I am child 1..
My pid = 50815, [my parent : 50813], I am child 1..
My pid = 50816, [my parent : 50812], I am child 2..
My pid = 50817, [my parent : 50813], I am child 2..
pid 50814 : I am EXITING
pid 50815 : I am EXITING
pid 50816 : I am EXITING
pid 50817 : I am EXITING
pid 50812 : I am EXITING
pid 50813 : I am EXITING
pid 50811 : I am EXITING


来源: stackexchange

问:
Script Component does not work in next.js
I'm working in Tiny Editor, it's necessary to define a key for the editor, following the documentation I can consult this key through the tag

答:
If Script component is inside  component, use it outside

Try in a different browser. It might be browser-specific issue

default value for the strategy prop is afterInteractive. with this, script is fetched and executed after the page is interactive. Use beforeInteractive for critical scripts that need to be fetched and executed before the page is interactive.

use onError props for debugging.

```<code> onError={(e) => {
        console.error('Script failed to load', e)
      }}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If Script component is inside <Head> component, use it outside <Head>

Try in a different browser. It might be browser-specific issue

default value for the strategy prop is afterInteractive. with this, script is fetched and executed after the page is interactive. Use beforeInteractive for critical scripts that need to be fetched and executed before the page is interactive.

use onError props for debugging.

 onError={(e) => {
        console.error('Script failed to load', e)
      }}


问:
How do I Instantiate component as Singleton at registration?
I can imagine this might be quite straight forward to do in Castle but I'm new to the technology and have been Googling for hours with no luck!

I have the following:

```<code>container.Register(
Component.For<MySpecialClass>().UsingFactoryMethod(
    () => new MySpecialClass()).LifeStyle.Singleton);
</code>```

Now quite rightly this is being lazy-loaded, i.e. the lambda expression passed in to UsingFactoryMethod() isn't being executed until I actually ask Castle to Resolve me the instance of the class.

But I would like Castle to create the instance as soon as I have registered it. Is this possible?

答:
For this simple case you could just register an existing instance:</p>

```<code>var special = new MySpecialClass();
container.Register(Component.For<MySpecialClass>().Instance(special));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I can imagine this might be quite straight forward to do in Castle but I'm new to the technology and have been Googling for hours with no luck!

I have the following:

container.Register(
Component.For<MySpecialClass>().UsingFactoryMethod(
    () => new MySpecialClass()).LifeStyle.Singleton);

Now quite rightly this is being lazy-loaded, i.e. the lambda expression passed in to UsingFactoryMethod() isn't being executed until I actually ask Castle to Resolve me the instance of the class.

But I would like Castle to create the instance as soon as I have registered it. Is this possible?

Body:
For this simple case you could just register an existing instance:

var special = new MySpecialClass();
container.Register(Component.For<MySpecialClass>().Instance(special));


问:
vue3 creating global variables returns undefined
I am currently working on upgrading a project to Vue3.  Inside the project we have several files that create global variables inside a boot directory:

```<code>src/boot/auth.js
src/boot/axios.js
src/boot/cranky.js
....
</code>```

Each of these files creates global variables that I am using throughout the project.  For example my auth.js file:

import auth from '../app/auth';
import { createApp } from 'vue';

export default async ({
    router,
    Vue
}) => {
    const app = createApp({});
app.config.globalProperties.$auth = auth;
    // Vue.prototype.$auth = auth;
    //This works with logic in MainLayout to permit users to see particular screens
    //after they are logged in.
    router.beforeResolve((to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
            // eslint-disable-next-line no-unused-vars
            let user;
            if (app.config.globalProperties.$auth.isAuthenticated()) {
                // TODO: record screens viewed by router url
                next();
            } else {
                next({
                    path: '/home'
                });
            }
        }
        next();
    });
};
```
<p>After research and reading I understand that global variables are created like this:
<code>app.config.globalProperties.$auth = auth;</code>, Which then should be called from other component files using <code>this.$auth</code>.  In my case, however, this returns as undefined.</p>
<p>My theory is that there is an issue with my createapp.  Am I calling that correctly, or am I missing something else?</p>
<p>Thanks.</p>
<p><strong>EDIT</strong></p>
<p>added code requested by @tony19
The following the full script tag.  My understanding and I probably am wrong, is that the <code>this</code> works as a global in vue3.</p>
<pre class="lang-html prettyprint-override"><code><script>
import HeaderScoreIndicator from '../components/HeaderScoreIndicator.vue';
import ExitResearchControl from '../components/ExitResearchControl.vue';
import {mq} from 'src/boot/mq'

export default {
    components: {
        HeaderScoreIndicator,
        ExitResearchControl
    },
    data: function () {
        return {
            tab: 'denial',
            signedIn: false,
            username: null,
            user: null
        };
    },
    computed: {
        /*
            These 4 functions bind the colors to the background elements
        */
        title: function () {
            return this.$store.state.globals.title;
        },
        toolbarStyle: function () {
            return 'padding-top: 10px; background-color: ' + this.$store.state.globals.toolbarColor;
        },
        footerStyle: function () {
            return `background-color: ${this.$store.state.globals.toolbarColor};`;
        },
        backgroundStyle: function () {
            if(!this.$mq.phone){
                return `background: linear-gradient(180deg, ${this.$store.state.globals.backgroundGradientTop} 0%,  ${this.$store.state.globals.backgroundGradientBottom} 100%);
                display: flex;
                justify-content: center;`;
            } else{
                return `background: linear-gradient(180deg, ${this.$store.state.globals.backgroundGradientTop} 0%,  ${this.$store.state.globals.backgroundGradientBottom} 100%);`;
            };
        },
        limitSize: function(){
            if(!this.$mq.phone){
                return 'max-width: 1023px; width: 100%;'
            } else{
                return
            };
        }
    },
    /*
        In the beforeCreate function, we're setting up an event listener to detect
        when we've logged in.  At the successful login we can push the user to
        the correct screen.
    */
    beforeCreate: function () {
        console.log(this.$auth);
        return this.$auth.getState().then(data => {
            if (this.$auth.isAuthenticated()) {
                this.username = this.$auth.getEmail();
                return this.initialize(data).then(() => this.signedIn = true);
            } else {
                this.signedIn = false;
                return newUserLanguageSelection()
            }
        }).catch(e => {
            this.signedIn = false;
            console.error(e);
        });

    },
    methods: {
        newUserLanguageSelection: function(){
            if(localStorage.getItem('languageSet') != 'true'){
                    return this.$router.push('/language');
            }
        },
        initialize: function (data) {
            this.$store.commit('globals/dataLoaded');
            this.$store.commit('scoring/setUsername', this.username);
            return this.$store.dispatch('scoring/initializeScoring', { points: data.score | 0 })
                .then(() => {
                    if(this.$store.state.globals.testQuiz){
                        return;
                    } else if(localStorage.getItem('languageSet') != 'true'){
                        return this.$router.push('/language');
                    }else if (data.seenAnalyticsDialog == true) {
                        return this.$router.push('/home');
                    } else {
                        return this.$router.push('/consent');
                    }
                })
                .catch(e => {
                    //silence NavigationDuplicated errors
                    if (e.name != "NavigationDuplicated")
                        throw e;
                });
        }
    }
};

</script>
</code>```

答:
In the previous Vue 2 project, it looks like Vue was passed to the auth.js module so that it could attach $auth to the Vue prototype.

However, in an attempt to upgrade that particular code in the auth.js module to Vue 3, you ignore the Vue argument, and create a throwaway application instance to create the $auth global property:

// src/boot/auth.js
export default async ({
    router,
    Vue,
}) => {
    const app = createApp({}); ❌ local app instance
    app.config.globalProperties.$auth = auth;
    ⋮
}
```
<p>But that won't work because the <code>app</code> instance is not somehow hooked into the application instance you'll eventually mount in <code>main.js</code>.</p>
<h3>Fixing the upgrade</h3>
<p>Your <code>main.js</code> probably looks similar to this:</p>
<pre class="lang-js prettyprint-override"><code>// src/main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

auth({ router, Vue });
⋮
Vue.createApp(App).mount('#app');
</code>```

To correctly upgrade the original code, you should pass the app instance from main.js to auth.js:

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

const app = createApp(App);

auth({ router, app });
⋮
app.mount('#app');
```
<p>And use that <code>app</code> in the <code>auth.js</code> module:</p>
<pre class="lang-js prettyprint-override"><code>// src/boot/auth.js
export default async ({
    router,
    app,
}) => {

    app.config.globalProperties.$auth = auth;
    ⋮
}
</code>```

Convert to Vue plugin

Assuming you don't need to await the return of the auth.js module, you could make that module a Vue plugin instead, which automatically receives the app instance as the first argument. The second argument receives the options passed in from app.use():

// src/boot/auth.js
export default {
  install(app, { router }) {
    app.config.globalProperties.$auth = auth;

    router.beforeResolve(⋯);
  }
}
```
<pre class="lang-js prettyprint-override"><code>// src/main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

const app = createApp(App);
app.use(auth, { router });
⋮
app.mount('#app');
</code>```

Body:
I am currently working on upgrading a project to Vue3.  Inside the project we have several files that create global variables inside a boot directory:

src/boot/auth.js
src/boot/axios.js
src/boot/cranky.js
....

Each of these files creates global variables that I am using throughout the project.  For example my auth.js file:

import auth from '../app/auth';
import { createApp } from 'vue';

export default async ({
    router,
    Vue
}) => {
    const app = createApp({});
app.config.globalProperties.$auth = auth;
    // Vue.prototype.$auth = auth;
    //This works with logic in MainLayout to permit users to see particular screens
    //after they are logged in.
    router.beforeResolve((to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
            // eslint-disable-next-line no-unused-vars
            let user;
            if (app.config.globalProperties.$auth.isAuthenticated()) {
                // TODO: record screens viewed by router url
                next();
            } else {
                next({
                    path: '/home'
                });
            }
        }
        next();
    });
};

After research and reading I understand that global variables are created like this:
app.config.globalProperties.$auth = auth;, Which then should be called from other component files using this.$auth.  In my case, however, this returns as undefined.

My theory is that there is an issue with my createapp.  Am I calling that correctly, or am I missing something else?

Thanks.

EDIT

added code requested by @tony19
The following the full script tag.  My understanding and I probably am wrong, is that the this works as a global in vue3.

Body:
In the previous Vue 2 project, it looks like Vue was passed to the auth.js module so that it could attach $auth to the Vue prototype.

However, in an attempt to upgrade that particular code in the auth.js module to Vue 3, you ignore the Vue argument, and create a throwaway application instance to create the $auth global property:

// src/boot/auth.js
export default async ({
    router,
    Vue,
}) => {
    const app = createApp({}); ❌ local app instance
    app.config.globalProperties.$auth = auth;
    ⋮
}

But that won't work because the app instance is not somehow hooked into the application instance you'll eventually mount in main.js.

Fixing the upgrade

Your main.js probably looks similar to this:

// src/main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

auth({ router, Vue });
⋮
Vue.createApp(App).mount('#app');

To correctly upgrade the original code, you should pass the app instance from main.js to auth.js:

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

const app = createApp(App);

auth({ router, app });
⋮
app.mount('#app');

And use that app in the auth.js module:

// src/boot/auth.js
export default async ({
    router,
    app,
}) => {

    app.config.globalProperties.$auth = auth;
    ⋮
}

Convert to Vue plugin

Assuming you don't need to await the return of the auth.js module, you could make that module a Vue plugin instead, which automatically receives the app instance as the first argument. The second argument receives the options passed in from app.use():

// src/boot/auth.js
export default {
  install(app, { router }) {
    app.config.globalProperties.$auth = auth;

    router.beforeResolve(⋯);
  }
}

// src/main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import auth from './boot/auth';

const app = createApp(App);
app.use(auth, { router });
⋮
app.mount('#app');


问:
I can't install "python-gtk2" on kali 20.04
I need to install "python-gtk2" on kali 20.04 which is running on virtual box.

I used sudo apt-get install python-gtk2 and the output:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-gtk2
</code>```

Here is the full details:

```<code>┌──(kali㉿kali)-[~]
└─$ sudo apt-get install python-gtk2                                                                                100 ⨯
[sudo] password for kali:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-gtk2
</code>```

Here is my /etc/apt/sources.list file content:

```<code># See https://www.kali.org/docs/general-use/kali-linux-sources-list-repositories/
deb http://http.kali.org/kali kali-rolling main contrib non-free

# Additional line for source packages
deb-src http://http.kali.org/kali kali-rolling main contrib non-free
</code>```

Thanks in advance!!!

答:
There is Debian Package of python-gtk2 available. You can try to install it from there.

Link: https://pkgs.org/download/python-gtk2

apt install command will not work as gtk2 removed from Kali distro repository.

Body:
I need to install "python-gtk2" on kali 20.04 which is running on virtual box.

I used sudo apt-get install python-gtk2 and the output:

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-gtk2

Here is the full details:

┌──(kali㉿kali)-[~]
└─$ sudo apt-get install python-gtk2                                                                                100 ⨯
[sudo] password for kali:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-gtk2

Here is my /etc/apt/sources.list file content:

# See https://www.kali.org/docs/general-use/kali-linux-sources-list-repositories/
deb http://http.kali.org/kali kali-rolling main contrib non-free

# Additional line for source packages
deb-src http://http.kali.org/kali kali-rolling main contrib non-free

Thanks in advance!!!


问:
how to detect wallet change in JS when i connect with Solflare extention
hello guys am working on a blockchain app that uses many wallets extensions like phantom , slope , solflare ...
now i authorize only few public keys to be connected to my app , but the problem is if i connect with an authorized public key i can change to unauthorized one from the extension (SOLFLARE) and do what i want , please how can i detect current public key in solflare for example when using phantom here is how to access it :

```<code>window.solana.publicKey
</code>```

any way to access solflare like that or any other solution i need the public key or an event that i can attach to it ...

答:
hello guys i just figured it out , it's the same thing we can access it using :</p>
```<code>window.solflare.publicKey
</code>```

Body:
hello guys am working on a blockchain app that uses many wallets extensions like phantom , slope , solflare ...
now i authorize only few public keys to be connected to my app , but the problem is if i connect with an authorized public key i can change to unauthorized one from the extension (SOLFLARE) and do what i want , please how can i detect current public key in solflare for example when using phantom here is how to access it :

window.solana.publicKey

any way to access solflare like that or any other solution i need the public key or an event that i can attach to it ...

Body:
hello guys i just figured it out , it's the same thing we can access it using :

window.solflare.publicKey


问:
How to write fluent bit input logs to localhost syslog server
I'm working on collecting logs from docker containerized application. I'm able to bring the logs to stdout output plugin but when I am trying syslog output plugin then it is not writing on syslog server.
Below is the configuration file.

```<code>[SERVICE]
    Parsers_File        /etc/td-agent-bit/parsers.conf

[INPUT]
    Name                forward

[Output]
    name                syslog
    match               *
    host                127.0.0.1
    port                514
    mode                udp
    syslog_format       rfc5424
    syslog_hostname_key hostname
    syslog_appname_key  appname
    syslog_procid_key   procid
    syslog_message_key  log
</code>```

The logging property for container application is set to

```<code>logging:
  driver: fluentd
  options:
    fluentd-address: localhost:24224
    tag: logs
</code>```

After running the fluent bit /opt/td-agent-bit/bin/td-agent-bit -c fluent.conf

```<code>[2021/09/20 08:47:16] [ warn] [engine] failed to flush chunk '8481-1632152835.361162854.flb', retry in 7 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:47:23] [ warn] [engine] chunk '8481-1632152835.361162854.flb' cannot be retried: task_id=0, input=forward.0 > output=syslog.0
[2021/09/20 08:47:26] [ warn] [engine] failed to flush chunk '8481-1632152845.361118393.flb', retry in 6 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:47:32] [ warn] [engine] chunk '8481-1632152845.361118393.flb' cannot be retried: task_id=0, input=forward.0 > output=syslog.0
[2021/09/20 08:47:36] [ warn] [engine] failed to flush chunk '8481-1632152855.361556013.flb', retry in 8 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)
</code>```

Can anyone tell what is going wrong here?

Even for simple cpu input plugin syslog does not work. like

```<code>/opt/td-agent-bit/bin/td-agent-bit -i cpu -o syslog
</code>```

output

```<code>[2021/09/20 08:53:43] [ info] [cmetrics] version=0.2.1
[2021/09/20 08:53:43] [ info] [output:syslog:syslog.0] setup done for 127.0.0.1:514
[2021/09/20 08:53:43] [ info] [sp] stream processor started
[2021/09/20 08:53:48] [ warn] [engine] failed to flush chunk '8765-1632153224.515974981.flb', retry in 10 seconds: task_id=0, input=cpu.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:53:53] [ warn] [engine] failed to flush chunk '8765-1632153228.516869744.flb', retry in 6 seconds: task_id=1, input=cpu.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:53:58] [ warn] [engine] chunk '8765-1632153224.515974981.flb' cannot be retried: task_id=0, input=cpu.0 > output=syslog.0
</code>```

答:
i faced similar issue, happening because fluentbit pod itself is 127.0.0.1. i created another rsyslog pod and used its IP to get logs from fluentbit.
https://artifacthub.io/packages/helm/rsyslog/rsyslog</p>

Body:
I'm working on collecting logs from docker containerized application. I'm able to bring the logs to stdout output plugin but when I am trying syslog output plugin then it is not writing on syslog server.
Below is the configuration file.

[SERVICE]
    Parsers_File        /etc/td-agent-bit/parsers.conf

[INPUT]
    Name                forward

[Output]
    name                syslog
    match               *
    host                127.0.0.1
    port                514
    mode                udp
    syslog_format       rfc5424
    syslog_hostname_key hostname
    syslog_appname_key  appname
    syslog_procid_key   procid
    syslog_message_key  log

The logging property for container application is set to

logging:
  driver: fluentd
  options:
    fluentd-address: localhost:24224
    tag: logs

After running the fluent bit /opt/td-agent-bit/bin/td-agent-bit -c fluent.conf

[2021/09/20 08:47:16] [ warn] [engine] failed to flush chunk '8481-1632152835.361162854.flb', retry in 7 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:47:23] [ warn] [engine] chunk '8481-1632152835.361162854.flb' cannot be retried: task_id=0, input=forward.0 > output=syslog.0
[2021/09/20 08:47:26] [ warn] [engine] failed to flush chunk '8481-1632152845.361118393.flb', retry in 6 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:47:32] [ warn] [engine] chunk '8481-1632152845.361118393.flb' cannot be retried: task_id=0, input=forward.0 > output=syslog.0
[2021/09/20 08:47:36] [ warn] [engine] failed to flush chunk '8481-1632152855.361556013.flb', retry in 8 seconds: task_id=0, input=forward.0 > output=syslog.0 (out_id=0)

Can anyone tell what is going wrong here?

Even for simple cpu input plugin syslog does not work. like

/opt/td-agent-bit/bin/td-agent-bit -i cpu -o syslog

output

[2021/09/20 08:53:43] [ info] [cmetrics] version=0.2.1
[2021/09/20 08:53:43] [ info] [output:syslog:syslog.0] setup done for 127.0.0.1:514
[2021/09/20 08:53:43] [ info] [sp] stream processor started
[2021/09/20 08:53:48] [ warn] [engine] failed to flush chunk '8765-1632153224.515974981.flb', retry in 10 seconds: task_id=0, input=cpu.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:53:53] [ warn] [engine] failed to flush chunk '8765-1632153228.516869744.flb', retry in 6 seconds: task_id=1, input=cpu.0 > output=syslog.0 (out_id=0)
[2021/09/20 08:53:58] [ warn] [engine] chunk '8765-1632153224.515974981.flb' cannot be retried: task_id=0, input=cpu.0 > output=syslog.0


问:
How to convert dataframe with datetimes to daily time series in + mean aggregation R
I have a dataframe that looks like this:

```<code>Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00", "2009-01-01 10:25:00",
                     "2009-01-02 07:45:00", "2009-01-02 15:32:00", "2009-01-02 11:15:00",
                     "2009-01-02 12:35:00")
Cust_ID = c("1214", "2643", "31231", "41244", "1214", "15317", "51591")
Wait_Time_Mins = c("54","43","88","94","12","130", "170")
df_have = data.frame(Arrival_DateTime, Cust_ID, Wait_Time_Mins)
</code>```

and want to convert it so I get the number of customer visits per day, and also their average wait time per day, so it looks something like this:

```<code>dates = c("2009-01-01", "2009-01-02")
num_visits = c("3", "4")
avg_wait_time = c("61.7","101.5")
df_want = data.frame(dates, num_visits, avg_wait_time)
</code>```

How would I go about doing this?

Similarly, is there a way to do monthly aggregations as well?

答:
You can use -</p>
```<code>library(dplyr)

df_have %>%
  mutate(Arrival_DateTime = lubridate::ymd_hms(Arrival_DateTime),
         Date = as.Date(Arrival_DateTime),
         #For monthly aggregation -
         #Date = format(Arrival_DateTime, '%Y-%m'),
         Wait_Time_Mins = as.numeric(Wait_Time_Mins)) %>%
  group_by(Date) %>%
  summarise(num_visits = n_distinct(Cust_ID),
            avg_wait_time = mean(Wait_Time_Mins))

#        Date num_visits avg_wait_time
#1 2009-01-01          3      61.66667
#2 2009-01-02          4     101.50000
</code>```

Body:
I have a dataframe that looks like this:

Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00", "2009-01-01 10:25:00",
                     "2009-01-02 07:45:00", "2009-01-02 15:32:00", "2009-01-02 11:15:00",
                     "2009-01-02 12:35:00")
Cust_ID = c("1214", "2643", "31231", "41244", "1214", "15317", "51591")
Wait_Time_Mins = c("54","43","88","94","12","130", "170")
df_have = data.frame(Arrival_DateTime, Cust_ID, Wait_Time_Mins)

and want to convert it so I get the number of customer visits per day, and also their average wait time per day, so it looks something like this:

dates = c("2009-01-01", "2009-01-02")
num_visits = c("3", "4")
avg_wait_time = c("61.7","101.5")
df_want = data.frame(dates, num_visits, avg_wait_time)

How would I go about doing this?

Similarly, is there a way to do monthly aggregations as well?

Body:
You can use -

library(dplyr)

df_have %>%
  mutate(Arrival_DateTime = lubridate::ymd_hms(Arrival_DateTime),
         Date = as.Date(Arrival_DateTime),
         #For monthly aggregation -
         #Date = format(Arrival_DateTime, '%Y-%m'),
         Wait_Time_Mins = as.numeric(Wait_Time_Mins)) %>%
  group_by(Date) %>%
  summarise(num_visits = n_distinct(Cust_ID),
            avg_wait_time = mean(Wait_Time_Mins))

#        Date num_visits avg_wait_time
#1 2009-01-01          3      61.66667
#2 2009-01-02          4     101.50000


问:
Unable to Update Configuration Settings in Azure App
I have a pretty standard website running on Azure App Service.  Within that App, I have a couple of deployment slots (ex. /staging, /test).

Today, I was trying to update a configuration setting in the app and got an error message Updating web app settings  Failed to update web app settings: The hostname [nameofmyapp]-staging2.azurewebsites.net is invalid.

For a brief time, I had a slot named 'staging2' but I deleted it.  Somehow, its still sticking around and now I can't update any configuration settings anywhere.  Any ideas on how I completely kill that slot so I can update things?

答: Any chance you can still see the slot or any related configuration if you navigate to the app service via https://resources.azure.com? If so, perhaps try removing extraneous configuration either via the Azure CLI or PowerShell. Though if this not a production app service, the easiest thing is probably to create a new App Service.</p>


问:
how to send element values from parent window to child layer window element?
i have an array of comments from DB and each comment have a reply links. when i click on the anchor reply i need to open a new layer window.. and i need that particular comment id in the newly popup layer window.</p>

答:
Whether you are doing this with a popup window or an iframe you can pass the information you need in the url of the reply anchor...

If you need to access it on the server then send in the url as a query string (php for example). layer.php?comment_id=123

If you need to access it in javascript then use a hash to pass it: layer.html#comment_id=123

You could then use javascript to get the hash

```<code>var id = document.location.hash.match(/comment_id=([1-9][0-9]*)/)[1];
</code>```

Body:
Whether you are doing this with a popup window or an iframe you can pass the information you need in the url of the reply anchor...

If you need to access it on the server then send in the url as a query string (php for example). layer.php?comment_id=123

If you need to access it in javascript then use a hash to pass it: layer.html#comment_id=123

You could then use javascript to get the hash

var id = document.location.hash.match(/comment_id=([1-9][0-9]*)/)[1];


问:
How to customize dropdown item in react semantic-ui-react?
I'm using dropdown from semantic-ui-react.
I am dynamically creating a dropdown option, and I want to change the background color of the item dynamically.
How can I fill the background color to 100%?

Campaign

import {
  Dropdown,
  Menu,
} from "semantic-ui-react";
//make customize option
  getCustomerGroupOptions = () => {
    let options = [
      {
        text: "none",
        key: "none",
        value: {},
      },
    ];
   for (let tag of this.props.tags || []) {
      options = [
        ...options,
        {
          text: tag.label,
          key: tag.id,
          value: tag,
          content: (

              {tag.label}

          ),
        },
      ];
    }
}

//Dropdown
                  <Dropdown
          error={errors.recipientFlag}
          placeholder={I18n.get(
            `${scope}.normalModal.title3.group.placeholder`
          )}
          className="mb-5 width-75 max-width-350px"
          name="recipient"
          value={campaign.recipient ? campaign.recipient : null}
          selection
          options={groupOptions}
          onChange={onChange}
        />
```

答:
If you use inspector, you'll find that the css you're overriding is only set to the div.item.text element. It's a lot easier to get what you want if you just set the css to div.item created by semantic-ui-react.

Use Dropdown.Item and set your css to that component. I've removed some stuff for which you didn't provide logic, but you can interpolate from something like this:

```<code>import {
    Dropdown
  } from "semantic-ui-react";
const Campaign = (props) => {
    const getCustomerGroupOptions = () => {
      let options = [
      ];
     for (let tag of props.tags || []) {
        options = [...options,
              <Dropdown.Item
                style={{ backgroundColor: tag.color, color: "#fff"}}
              >
                {tag.label}
              </Dropdown.Item>
        ];
      }

      return options;
  }

  return (
         <Dropdown
            className="mb-5 width-75 max-width-350px"
            placeholder='Select Friend'
            name="recipient"
            selection
          >
              <Dropdown.Menu>
                {getCustomerGroupOptions()}
              </Dropdown.Menu>
          </Dropdown>
    );
}

export default Campaign;
</code>```

Body:
If you use inspector, you'll find that the css you're overriding is only set to the div.item.text element. It's a lot easier to get what you want if you just set the css to div.item created by semantic-ui-react.

Use Dropdown.Item and set your css to that component. I've removed some stuff for which you didn't provide logic, but you can interpolate from something like this:

import {
    Dropdown
  } from "semantic-ui-react";
const Campaign = (props) => {
    const getCustomerGroupOptions = () => {
      let options = [
      ];
     for (let tag of props.tags || []) {
        options = [...options,
              <Dropdown.Item
                style={{ backgroundColor: tag.color, color: "#fff"}}
              >
                {tag.label}
              </Dropdown.Item>
        ];
      }

      return options;
  }

  return (
         <Dropdown
            className="mb-5 width-75 max-width-350px"
            placeholder='Select Friend'
            name="recipient"
            selection
          >
              <Dropdown.Menu>
                {getCustomerGroupOptions()}
              </Dropdown.Menu>
          </Dropdown>
    );
}

export default Campaign;


问:
Cannot connect to database in Vue data tables
I am using vuetify data in my php script and it works fine previously and now every page showing that error as Your search for "{{ search }}" found no results.

Seems this problem comes as when it cannot fetch data from the database. Here is my database class.

```<code>class Database
{
    public $id;
    public $user;
    public $user_name;
    public $password;

    public static function db()
    {

      $host = 'localhost';
      $dbName = 'newdata';
      $userName = "root";
      $password = "";

        $db = "mysql:host=$host;dbname=$dbName";

        try {
            $pdo = new PDO($db, $userName, $password);
        } catch (PDOException $e) {
            throw new PDOException($e->getMessage());
        }
        return $pdo;
    }

}
</code>```

This username and password works fine and I can connect to sql in my remote server using that password as well.

Here is some of the code which results above error.

```<code><v-app>
                  <v-card>

                    <div class="row card-body">
                    <div class="col-sm-12">
                      <div class="row col-sm-12">

                        <div class=" col-sm-3">
                          <div class="form-group row">
                            <label for="inputEmail3" class="col-sm-2 col-form-label">TO</label>
                            <div class="col-sm-10">
                              <input type="date" class="form-control form-control-sm" v-model="endDate">
                            </div>
                          </div>
                        </div>

                        <div class="col-sm-2">
                          <button type="submit" class="btn btn-success btn-sm"  v-on:click="getReport(ts)"style="margin-top:-5px">Submit</button>
                        </div>
                      </div>
                    </div>
                  </div>
                    <v-card-title>
                      <b>Balance Report</b>
                      </details>
                      <v-spacer></v-spacer>
                      <v-text-field
                        append-icon="search"
                        label="Search"
                        single-line
                        hide-details
                        v-model="search"
                      ></v-text-field>
                    </v-card-title>
                    <v-data-table
                      :headers="headers"
                      :items="Report"
                      :search="search"
                    >
                      <template slot="items" slot-scope="props">

                        <td>{{ props.item.col1 }}</td>
                        <td>{{ props.item.col2}}</td>
                        <td>{{ props.item.col3}}</td>
                        <td>{{ props.item.col4}}</td>
                        <td>{{ props.item.col5}}</td>
                      </template>
                      <v-alert slot="no-results" :value="true" color="error" icon="warning">
                        Your search for "{{ search }}" found no results.
                      </v-alert>
                    </v-data-table>
                  </v-card>
                </v-app>
</code>```

Can anyone suggest where it has stucked?
Sorry for not attaching the whole php code here since It worked for many days and it sudddenly didnt worked.

Here is my vue class.

```<code>var UsageReport = new Vue({
  el:'#UsageReport',
  data(){
    return{
      Report:[],
      search: '',
      headers: [
                    { text: 'value1', value: 'col1 ' },
        { text: 'value2', value: 'col2 ' },
        { text: 'value3', value: 'col3 ' },
        { text: 'value4', value: 'col4 ' },
        { text: 'value5', value: 'col5 ' },
      ],
      variabl1:'',
      variabl2:'',
      variabl3:'',
      variabl4:''

    }
  },
</code>```

答:
You've bound your value (of v-alert) to true.

<v-alert .... :value="true" color="error" icon="warning">

This should be replaced by a variable that you set to "true" if nothing is returned by your XHR call for example.

For example, if "Report" is an array of objects that you set after your call to the backend, then you could use the following instead:

```<code>              <v-alert slot="no-results" :value="Report.length == 0" color="error" icon="warning">
                Your search for "{{ search }}" found no results.
              </v-alert>
</code>```

Notice how the value of v-alert is bound to the length of the variable named Report. Which is an array in your component. If we fill it with data (see below), it should no longer show you the mssage.

```<code>var UsageReport = new Vue({
  el:'#UsageReport',
  data(){
    return{
      Report:['sample item1','sample item2'],
      search: '',
      headers: [
                    { text: 'value1', value: 'col1 ' },
        { text: 'value2', value: 'col2 ' },
        { text: 'value3', value: 'col3 ' },
        { text: 'value4', value: 'col4 ' },
        { text: 'value5', value: 'col5 ' },
      ],
      variabl1:'',
      variabl2:'',
      variabl3:'',
      variabl4:''

    }
  },
</code>```

Body:
I am using vuetify data in my php script and it works fine previously and now every page showing that error as Your search for "{{ search }}" found no results.

Seems this problem comes as when it cannot fetch data from the database. Here is my database class.

class Database
{
    public $id;
    public $user;
    public $user_name;
    public $password;

    public static function db()
    {

      $host = 'localhost';
      $dbName = 'newdata';
      $userName = "root";
      $password = "";

        $db = "mysql:host=$host;dbname=$dbName";

        try {
            $pdo = new PDO($db, $userName, $password);
        } catch (PDOException $e) {
            throw new PDOException($e->getMessage());
        }
        return $pdo;
    }

}

This username and password works fine and I can connect to sql in my remote server using that password as well.

Here is some of the code which results above error.

<v-app>
                  <v-card>

                            TO

                              <input type="date" class="form-control form-control-sm" v-model="endDate">

                          <button type="submit" class="btn btn-success btn-sm"  v-on:click="getReport(ts)"style="margin-top:-5px">Submit</button>

                    <v-card-title>
                      Balance Report

                      <v-spacer></v-spacer>
                      <v-text-field
                        append-icon="search"
                        label="Search"
                        single-line
                        hide-details
                        v-model="search"
                      ></v-text-field>
                    </v-card-title>
                    <v-data-table
                      :headers="headers"
                      :items="Report"
                      :search="search"
                    >
                      <template slot="items" slot-scope="props">

                        {{ props.item.col1 }}
                        {{ props.item.col2}}
                        {{ props.item.col3}}
                        {{ props.item.col4}}
                        {{ props.item.col5}}
                      </template>
                      <v-alert slot="no-results" :value="true" color="error" icon="warning">
                        Your search for "{{ search }}" found no results.
                      </v-alert>
                    </v-data-table>
                  </v-card>
                </v-app>

Can anyone suggest where it has stucked?
Sorry for not attaching the whole php code here since It worked for many days and it sudddenly didnt worked.

Here is my vue class.

var UsageReport = new Vue({
  el:'#UsageReport',
  data(){
    return{
      Report:[],
      search: '',
      headers: [
                    { text: 'value1', value: 'col1 ' },
        { text: 'value2', value: 'col2 ' },
        { text: 'value3', value: 'col3 ' },
        { text: 'value4', value: 'col4 ' },
        { text: 'value5', value: 'col5 ' },
      ],
      variabl1:'',
      variabl2:'',
      variabl3:'',
      variabl4:''

    }
  },

Body:
You've bound your value (of v-alert) to true.

<v-alert .... :value="true" color="error" icon="warning">

This should be replaced by a variable that you set to "true" if nothing is returned by your XHR call for example.

For example, if "Report" is an array of objects that you set after your call to the backend, then you could use the following instead:

              <v-alert slot="no-results" :value="Report.length == 0" color="error" icon="warning">
                Your search for "{{ search }}" found no results.
              </v-alert>

Notice how the value of v-alert is bound to the length of the variable named Report. Which is an array in your component. If we fill it with data (see below), it should no longer show you the mssage.

var UsageReport = new Vue({
  el:'#UsageReport',
  data(){
    return{
      Report:['sample item1','sample item2'],
      search: '',
      headers: [
                    { text: 'value1', value: 'col1 ' },
        { text: 'value2', value: 'col2 ' },
        { text: 'value3', value: 'col3 ' },
        { text: 'value4', value: 'col4 ' },
        { text: 'value5', value: 'col5 ' },
      ],
      variabl1:'',
      variabl2:'',
      variabl3:'',
      variabl4:''

    }
  },


问:
Destructuring to get the last element of an array in es6
In coffeescript this is straightforward:

```<code>coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
</code>```

Does es6 allow for something similar?

```<code>> const [, b] = [1, 2, 3]
'use strict'
> b  // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
    |                  ^
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)
</code>```

Of course I can do it the es5 way -

```<code>const a = b[b.length - 1]
</code>```

But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?

答:
You can try using object destructuring applied to an array to extract the length and then get last item: e.g.:

const { length, 0: first, [length - 1]: last } = ['a', 'b', 'c', 'd']

// length = 4
// first = 'a'
// last = 'd'
```
<h2>UPDATE</h2>
<p>Another approach Array.prototype.at()</p>
<blockquote>
<p>The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers...</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>const last = ['a', 'b', 'c', 'd'].at(-1)
// 'd'
</code>```

Body:
In coffeescript this is straightforward:

coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'

Does es6 allow for something similar?

> const [, b] = [1, 2, 3]
'use strict'
> b  // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
    |                  ^
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)

Of course I can do it the es5 way -

const a = b[b.length - 1]

But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?

Body:
You can try using object destructuring applied to an array to extract the length and then get last item: e.g.:

const { length, 0: first, [length - 1]: last } = ['a', 'b', 'c', 'd']

// length = 4
// first = 'a'
// last = 'd'

UPDATE

Another approach Array.prototype.at()

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers...

const last = ['a', 'b', 'c', 'd'].at(-1)
// 'd'


问:
SQL Server query is slow but when testing on tempdb, it works fast
I have a slow query which contains more than 10 left join and 10 like operators. see bellow.

SystemContact has approx. 10K of data, the other two have more than 100k of data.
The query looks not optimized, this is because it is generated by a program used to search SystemContact.

The problem that I faced is, the query is running very slow on our system which takes at least a minute to run. We have done updating statistics and defragging tables but it does not seem to improve performance much.

Initially I was thinking it might be related to the string DataType which is currently using nvarchar, but when I load all those tables with data into tempdb on the same server, the query runs about 2 seconds.

I am wondering what could be cause of the slowness?

```<code>SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

    select
    Id, Context1, Context2, Context3, LastModifiedBy

    from SystemContact
    left join SystemField as SF1 on SystemContact.Id = SF1.ContactId and SF1.FieldId = 1111
    left join SystemField as SF2 on SystemContact.Id = SF2.ContactId and SF2.FieldId = 5445
    left join SystemField as SF3 on SystemContact.Id = SF3.ContactId and SF3.FieldId = 3423
    left join SystemField as SF4 on SystemContact.Id = SF4.ContactId and SF4.FieldId = 6545
    left join SystemField as SF5 on SystemContact.Id = SF5.ContactId and SF5.FieldId = 5464
    left join SystemFieldText as SFT1 on SystemContact.Id = SFT1.ContactId and SFT1.FieldId = 546
    left join SystemFieldText as SFT2 on SystemContact.Id = SFT2.ContactId and SFT2.FieldId = 7565
    left join SystemFieldText as SFT3 on SystemContact.Id = SFT3.ContactId and SFT3.FieldId = 456
    left join SystemFieldText as SFT4 on SystemContact.Id = SFT4.ContactId and SFT4.FieldId = 457
    left join SystemFieldText as SFT5 on SystemContact.Id = SFT5.ContactId and SFT5.FieldId = 56
    left join SystemFieldText as SFT6 on SystemContact.Id = SFT6.ContactId and SFT6.FieldId = 85

    where
    (SF1.Value like '%john.smith@example.com%') or (SF2.Value like '%john.smith@example.com%') or (SF3.Value like '%john.smith@example.com%')
    or (SF4.Value like '%john.smith@example.com%') or (SF5.Value like '%john.smith@example.com%')
    or (SFT2.Value like '%john.smith@example.com%') or (SFT3.Value like '%john.smith@example.com%') or (SFT4.Value like '%john.smith@example.com%')
    or (SFT5.Value like '%john.smith@example.com%') or (SFT6.Value like '%john.smith@example.com%')
</code>```

EDIT:

Here is the link to the Execution Plan : https://goo.gl/gICWir

答:
Operations within tempdb are minimally logged so that transactions can be rolled back. tempdb is re-created every time SQL Server is started so that the system always starts with a clean copy of the database. Temporary tables and stored procedures are dropped automatically on disconnect, and no connections are active when the system is shut down.

tempdb never has anything to be saved from one session of SQL Server to another. Backup and restore operations are not allowed on tempdb.

https://learn.microsoft.com/en-us/sql/relational-databases/databases/tempdb-database?view=sql-server-ver15#:~:text=The%20tempdb%20system%20database%20is,%2Dvalued%20functions%2C%20and%20cursors.

Body:
I have a slow query which contains more than 10 left join and 10 like operators. see bellow.

SystemContact has approx. 10K of data, the other two have more than 100k of data.
The query looks not optimized, this is because it is generated by a program used to search SystemContact.

The problem that I faced is, the query is running very slow on our system which takes at least a minute to run. We have done updating statistics and defragging tables but it does not seem to improve performance much.

Initially I was thinking it might be related to the string DataType which is currently using nvarchar, but when I load all those tables with data into tempdb on the same server, the query runs about 2 seconds.

I am wondering what could be cause of the slowness?

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

    select
    Id, Context1, Context2, Context3, LastModifiedBy

    from SystemContact
    left join SystemField as SF1 on SystemContact.Id = SF1.ContactId and SF1.FieldId = 1111
    left join SystemField as SF2 on SystemContact.Id = SF2.ContactId and SF2.FieldId = 5445
    left join SystemField as SF3 on SystemContact.Id = SF3.ContactId and SF3.FieldId = 3423
    left join SystemField as SF4 on SystemContact.Id = SF4.ContactId and SF4.FieldId = 6545
    left join SystemField as SF5 on SystemContact.Id = SF5.ContactId and SF5.FieldId = 5464
    left join SystemFieldText as SFT1 on SystemContact.Id = SFT1.ContactId and SFT1.FieldId = 546
    left join SystemFieldText as SFT2 on SystemContact.Id = SFT2.ContactId and SFT2.FieldId = 7565
    left join SystemFieldText as SFT3 on SystemContact.Id = SFT3.ContactId and SFT3.FieldId = 456
    left join SystemFieldText as SFT4 on SystemContact.Id = SFT4.ContactId and SFT4.FieldId = 457
    left join SystemFieldText as SFT5 on SystemContact.Id = SFT5.ContactId and SFT5.FieldId = 56
    left join SystemFieldText as SFT6 on SystemContact.Id = SFT6.ContactId and SFT6.FieldId = 85

    where
    (SF1.Value like '%john.smith@example.com%') or (SF2.Value like '%john.smith@example.com%') or (SF3.Value like '%john.smith@example.com%')
    or (SF4.Value like '%john.smith@example.com%') or (SF5.Value like '%john.smith@example.com%')
    or (SFT2.Value like '%john.smith@example.com%') or (SFT3.Value like '%john.smith@example.com%') or (SFT4.Value like '%john.smith@example.com%')
    or (SFT5.Value like '%john.smith@example.com%') or (SFT6.Value like '%john.smith@example.com%')

EDIT:

Here is the link to the Execution Plan : https://goo.gl/gICWir


问:
What PHP function(s) should I use to cut off the end of a string?
I have a filename stored with the directory as a value.

Ex. /var/www/remove_this.php

In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.

There are so many string editing functions, I don't know a good approach. Thanks!

答:
Use pathinfo() to get info about the file itself.

```<code>$file = '/var/www/remove_this.php';
$pathinfo = pathinfo($file);
$dir = $pathinfo['dirname']; // '/var/www/'
</code>```

Body:
Use pathinfo() to get info about the file itself.

$file = '/var/www/remove_this.php';
$pathinfo = pathinfo($file);
$dir = $pathinfo['dirname']; // '/var/www/'


问:
Cannot define path: TypeError: unsupported operand type(s) for /: 'str' and 'str'
I've been facing an issue with defining a directory to use for the function open(). Unfortunately, it tells me that there is a TypeError: unsupported operand type(s) for /: 'str' and 'str'. How can I define in what folder to put the file without using a forward slash? I tried a backslash, but that prompted another error. I checked out a similar post's solution, but I got an error saying SyntaxError: expected ':'.

```<code>import pathlib
from pathlib import Path
dragonfly = input("name?")
directory = pathlib.Path("insects")
directory.mkdir(exist_ok=True)
r = "this is a test"
with open("insects" / f'{dragonfly}.pdf', 'wb') as file:
    file.write(r)
</code>```

答:
Just wrap the entire path in the f-string:</p>
```<code>with open(f'insects/{dragonfly}.pdf', 'wb')
</code>```

Body:
I've been facing an issue with defining a directory to use for the function open(). Unfortunately, it tells me that there is a TypeError: unsupported operand type(s) for /: 'str' and 'str'. How can I define in what folder to put the file without using a forward slash? I tried a backslash, but that prompted another error. I checked out a similar post's solution, but I got an error saying SyntaxError: expected ':'.

import pathlib
from pathlib import Path
dragonfly = input("name?")
directory = pathlib.Path("insects")
directory.mkdir(exist_ok=True)
r = "this is a test"
with open("insects" / f'{dragonfly}.pdf', 'wb') as file:
    file.write(r)

Body:
Just wrap the entire path in the f-string:

with open(f'insects/{dragonfly}.pdf', 'wb')


问:
How to display the contents of an array as a list?
I'd like to output the contents of an array as a list:

value

value

value

However, it's currently outputting the array like this:

value,value,value

What can I change to display the array contents as a vertical list?

For context, this is displaying an array that updates by adding/removing items based on connections/disconnections to a server. So, when a user connects, their name is added to the array, when they disconnect, the array is wiped and all connected clients send their username back to the array, updating it. The below code simply displays these changes.

HTML:

```<code><section class="membersList">
  <div class="dispUser"></div>
</section>
</code>```

CSS:

```<code>.membersList {
    text-align: center;
    padding: 10px;
    margin-bottom: 10px;
    margin-right: 10px;
    background: #ACD8F0;
    width: 150px;
    border: 1px solid #000000;
    overflow: auto;
    float: right;
}
</code>```

JavaScript:

```<code>socket.on('theitems', function (data) {
      $('.dispUser').html('<p>' + data + '</p>');
      console.log(data);
    });
</code>```

If I replace .html with .append, it will display it as a list, but will show the changes of the array as they happen, rather than replacing it as a whole, which is what I want.

答:
I had a similar issue today, and I tried the above suggestions without any success.

Brainstorming with a colleague, we used array.toString() to convert the array to a string. Then we added on a

```<code>.replaceAll(',','<br>')
</code>```

to add line breaks between each entry. Finally we passed that variable to the innerHTML.

It worked for our purposes with only a single line of code outside the innerHTML section.

const myArray = ["Learning", "to", "code", "has", "been", "fun!"];
let myString = myArray.toString().replaceAll(",", "
");
let myDiv = document.getElementById("myArrayDiv");
let myInnerHTML = document.createElement("div");
myInnerHTML.innerHTML = `<div><p>${myString}</p></div>`;
myDiv.appendChild(myInnerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myArrayDiv"></div></code>```

Body:
I'd like to output the contents of an array as a list:

value

value

value

However, it's currently outputting the array like this:

value,value,value

What can I change to display the array contents as a vertical list?

For context, this is displaying an array that updates by adding/removing items based on connections/disconnections to a server. So, when a user connects, their name is added to the array, when they disconnect, the array is wiped and all connected clients send their username back to the array, updating it. The below code simply displays these changes.

HTML:

CSS:

.membersList {
    text-align: center;
    padding: 10px;
    margin-bottom: 10px;
    margin-right: 10px;
    background: #ACD8F0;
    width: 150px;
    border: 1px solid #000000;
    overflow: auto;
    float: right;
}

JavaScript:

socket.on('theitems', function (data) {
      $('.dispUser').html('
' + data + '
');
      console.log(data);
    });

If I replace .html with .append, it will display it as a list, but will show the changes of the array as they happen, rather than replacing it as a whole, which is what I want.

Body:
I had a similar issue today, and I tried the above suggestions without any success.

Brainstorming with a colleague, we used array.toString() to convert the array to a string. Then we added on a

.replaceAll(',','<br>')

to add line breaks between each entry. Finally we passed that variable to the innerHTML.

It worked for our purposes with only a single line of code outside the innerHTML section.

const myArray = ["Learning", "to", "code", "has", "been", "fun!"];
let myString = myArray.toString().replaceAll(",", "<br>");
let myDiv = document.getElementById("myArrayDiv");
let myInnerHTML = document.createElement("div");
myInnerHTML.innerHTML = `<div><p>${myString}</p></div>`;
myDiv.appendChild(myInnerHTML);

<div id="myArrayDiv"></div>


问:
AppEngine error message on Flask Web Application
I'm implementing a Flask web application (that it's running locally on Python 3.1) on Google's App Engine (Python 3.7) and getting the following error:

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

That's the error log:

```<code>{
  "textPayload": "Traceback (most recent call last):\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2447, in wsgi_app\n    response = self.full_dispatch_request()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1953, in full_dispatch_request\n    return self.finalize_request(rv)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1970, in finalize_request\n    response = self.process_response(response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2269, in process_response\n    self.session_interface.save_session(self, ctx.session, response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask_session/sessions.py\", line 354, in save_session\n    total_seconds(app.permanent_session_lifetime))\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 224, in set\n    self._prune()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 159, in _prune\n    if self._over_threshold():\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 102, in _over_threshold\n    return self._threshold != 0 and self._file_count > self._threshold\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 69, in _file_count\n    return self.get(self._fs_count_file) or 0\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 193, in get\n    pickle_time = self.serializer.load(f)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/serializers.py\", line 29, in load\n    data = pickle.load(f)\nValueError: unsupported pickle protocol: 5",
  "insertId": "62069f77000ddb77156b638a",
  "resource": {
    "type": "gae_app",
    "labels": {
      "version_id": "{VERSION_ID}",
      "module_id": "default",
      "project_id": "{PROJECT_ID",
      "zone": "{ZONE}
    }
  },
  "timestamp": "{DATE}",
  "severity": "ERROR",
  "labels": {
    "clone_id": "00c61b117ccbf120db0bbf309ad2da98e7fc043e3476b10e04eb7dec8eacd8a8fff7a965420d11f752ea4b643abc9f95f12446cbbacbd7d3c1bdefcc1a1f8e9445f4a6d8b98de1d3fe4073120f2464989ace693a"
  },
  "logName": "projects/{PROJECT_NAME}/logs/stderr",
  "receiveTimestamp": "{DATE}"
}
</code>```

答:
It's complaining about protocol 5 in pickle. Protocol 5 is available from Python 3.8.

From the documentation

Protocol version 5 was added in Python 3.8. It adds support for out-of-band data and speedup for in-band data. Refer to PEP 574 for information about improvements brought by protocol 5.

You can either upgrade to Python 3.8 or use Pickle5 on a lower python version (i.e. your current Python 3.1 and Python 3.7)

Body:
I'm implementing a Flask web application (that it's running locally on Python 3.1) on Google's App Engine (Python 3.7) and getting the following error:

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

That's the error log:

{
  "textPayload": "Traceback (most recent call last):\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2447, in wsgi_app\n    response = self.full_dispatch_request()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1953, in full_dispatch_request\n    return self.finalize_request(rv)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1970, in finalize_request\n    response = self.process_response(response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2269, in process_response\n    self.session_interface.save_session(self, ctx.session, response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask_session/sessions.py\", line 354, in save_session\n    total_seconds(app.permanent_session_lifetime))\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 224, in set\n    self._prune()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 159, in _prune\n    if self._over_threshold():\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 102, in _over_threshold\n    return self._threshold != 0 and self._file_count > self._threshold\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 69, in _file_count\n    return self.get(self._fs_count_file) or 0\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 193, in get\n    pickle_time = self.serializer.load(f)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/serializers.py\", line 29, in load\n    data = pickle.load(f)\nValueError: unsupported pickle protocol: 5",
  "insertId": "62069f77000ddb77156b638a",
  "resource": {
    "type": "gae_app",
    "labels": {
      "version_id": "{VERSION_ID}",
      "module_id": "default",
      "project_id": "{PROJECT_ID",
      "zone": "{ZONE}
    }
  },
  "timestamp": "{DATE}",
  "severity": "ERROR",
  "labels": {
    "clone_id": "00c61b117ccbf120db0bbf309ad2da98e7fc043e3476b10e04eb7dec8eacd8a8fff7a965420d11f752ea4b643abc9f95f12446cbbacbd7d3c1bdefcc1a1f8e9445f4a6d8b98de1d3fe4073120f2464989ace693a"
  },
  "logName": "projects/{PROJECT_NAME}/logs/stderr",
  "receiveTimestamp": "{DATE}"
}


问:
Public key creation in AWS cloudformation giving following error: Invalid request provided: AWS::CloudFront::PublicKey
I have the following Cloudformation template (.yml file) where I am creating Public key to add to a Keygroup, also created in same template. (The public key below is just for example purpose.)

```<code>AWSTemplateFormatVersion: "2010-09-09"
Resources:
  CloudfrontPublicKey:
    Type: AWS::CloudFront::PublicKey
    Properties:
      PublicKeyConfig:
        CallerReference: 'some-caller-reference'
        Comment: 'Public key for signed url'
        Name: 'cloudfront-public-key'
        EncodedKey: '-----BEGIN PUBLIC KEY-----aaaabbbb-----END PUBLIC KEY-----'
  CloudFrontKeyGroup:
    Type: AWS::CloudFront::KeyGroup
    Properties:
      KeyGroupConfig:
        Comment: 'Key group for signed url'
        Items:
          - !Ref CloudfrontPublicKey
        Name: 'cloudfront-key-group'
</code>```

However, I am getting the following error relating to the public key

```<code>  Invalid request provided: AWS::CloudFront::PublicKey
</code>```

The original public key is multi-line, for example:

```<code>-----BEGIN PUBLIC KEY-----
aaaa
bbbb
-----END PUBLIC KEY-----
</code>```

I tried to make it fit in single line by adding new line character as follows

```<code>-----BEGIN PUBLIC KEY-----\naaaa\nbbbb\n-----END PUBLIC KEY-----
</code>```

I also tried without the new line character

```<code>-----BEGIN PUBLIC KEY-----aaaabbbb-----END PUBLIC KEY-----
</code>```

Both attempts did not work, and I am still getting the same error.

答:
You might also get the same error if you try to update an AWS::CloudFront::PublicKey resource. These resources are immutable. If you want to change the Name, EncodedKey, or CallerReference values, you have to create a new PublicKey and add it to the KeyGroup.  (Or delete the CloudfrontPublicKey in your example above, deploy, recreate the CloudfrontPublicKey, and deploy again.)

I've documented more in a blog post: You’re getting "Invalid request provided: AWS::CloudFront::PublicKey" because CloudFront Public Keys are immutable.

Body:
I have the following Cloudformation template (.yml file) where I am creating Public key to add to a Keygroup, also created in same template. (The public key below is just for example purpose.)

AWSTemplateFormatVersion: "2010-09-09"
Resources:
  CloudfrontPublicKey:
    Type: AWS::CloudFront::PublicKey
    Properties:
      PublicKeyConfig:
        CallerReference: 'some-caller-reference'
        Comment: 'Public key for signed url'
        Name: 'cloudfront-public-key'
        EncodedKey: '-----BEGIN PUBLIC KEY-----aaaabbbb-----END PUBLIC KEY-----'
  CloudFrontKeyGroup:
    Type: AWS::CloudFront::KeyGroup
    Properties:
      KeyGroupConfig:
        Comment: 'Key group for signed url'
        Items:
          - !Ref CloudfrontPublicKey
        Name: 'cloudfront-key-group'

However, I am getting the following error relating to the public key

  Invalid request provided: AWS::CloudFront::PublicKey

The original public key is multi-line, for example:

-----BEGIN PUBLIC KEY-----
aaaa
bbbb
-----END PUBLIC KEY-----

I tried to make it fit in single line by adding new line character as follows

-----BEGIN PUBLIC KEY-----\naaaa\nbbbb\n-----END PUBLIC KEY-----

I also tried without the new line character

-----BEGIN PUBLIC KEY-----aaaabbbb-----END PUBLIC KEY-----

Both attempts did not work, and I am still getting the same error.


问:
Arduino IR Transmittor not working with my TV
I try to do my DIY project with Arduino and IR transmitter. I connected and written code as per mentioned in web. but it is not working properly.

connections:

first IR pin connected to Ground

second IR pin connected to TX

```<code>#include <IRremote.h>
IRsend irsend;
void setup() {}
void loop() {
    irsend.sendRC5(0x1FC1, 32);
    delay(5000);
}
</code>```

This is my code in Arduino

for checking in serial monitor i used below code

```<code>#include <IRremote.h>
const int RECV_PIN = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
}

void loop() {
  if (irrecv.decode(&results)) {
    if (results.decode_type == NEC) {
      Serial.print("NEC: ");
    } else if (results.decode_type == SONY) {
      Serial.print("SONY: ");
    } else if (results.decode_type == RC5) {
      Serial.print("RC5: ");
    } else if (results.decode_type == RC6) {
      Serial.print("RC6: ");
    } else if (results.decode_type == UNKNOWN) {
      Serial.print("UNKNOWN: ");
    }
    Serial.println(results.value, HEX);
    irrecv.resume();
  }
}
</code>```

reference:  https://www.pjrc.com/teensy/td_libs_IRremote.html

results- serial monitor:
from remote:                   RC5: 1FC1
from Arduino:                  RC5: 1FC1

both are same. but still my TV not working with Arduino but working with original remote

what could be the issue?

答:
I got answer, even it shows warning, I can control my TV and other by below code.
instead of RC5 I used NEC</p>
```<code>#include <IRremote.h>
IRsend irsend;
void setup() {}
void loop() {
    irsend.sendNEC(0x1FC1, 32);
    delay(5000);
}
</code>```

Body:
I try to do my DIY project with Arduino and IR transmitter. I connected and written code as per mentioned in web. but it is not working properly.

connections:

first IR pin connected to Ground

second IR pin connected to TX

#include <IRremote.h>
IRsend irsend;
void setup() {}
void loop() {
    irsend.sendRC5(0x1FC1, 32);
    delay(5000);
}

This is my code in Arduino

for checking in serial monitor i used below code

#include <IRremote.h>
const int RECV_PIN = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
}

void loop() {
  if (irrecv.decode(&results)) {
    if (results.decode_type == NEC) {
      Serial.print("NEC: ");
    } else if (results.decode_type == SONY) {
      Serial.print("SONY: ");
    } else if (results.decode_type == RC5) {
      Serial.print("RC5: ");
    } else if (results.decode_type == RC6) {
      Serial.print("RC6: ");
    } else if (results.decode_type == UNKNOWN) {
      Serial.print("UNKNOWN: ");
    }
    Serial.println(results.value, HEX);
    irrecv.resume();
  }
}

reference:  https://www.pjrc.com/teensy/td_libs_IRremote.html

results- serial monitor:
from remote:                   RC5: 1FC1
from Arduino:                  RC5: 1FC1

both are same. but still my TV not working with Arduino but working with original remote

what could be the issue?

Body:
I got answer, even it shows warning, I can control my TV and other by below code.
instead of RC5 I used NEC

#include <IRremote.h>
IRsend irsend;
void setup() {}
void loop() {
    irsend.sendNEC(0x1FC1, 32);
    delay(5000);
}


问:
At the login of SAM2 itself can claims attributes be saved?
Checking all the available libraries, we decided to use ItFortec SAML library. The login happens without any issues, but it redirects to destination page. Before it redirects is there a way to capture the SAML response and store claims attributes in a variable.</p>

答: You can use free tools like Fiddler (https://www.telerik.com/download/fiddler), or use Saml Tracer for Chrome browser (extension). Both have numerous tutorials how to capture the full trace of the saml flow between IDP and SP. Hope this gets you started, if not post your question.</p>


问:
how to increase the limit for max.print in R
I am using the Graph package in R for maxclique analysis of 5461 items.

The final output item which I get is very long, so I am getting the following warning:

reached getOption("max.print") -- omitted 475569 rows

Can somebody please provide me the pointers with how to increase the limit
for max.print.

答:
You can use the options command to change the max.print value for the value limit you want to reach. For example:

```<code>options(max.print = 1000000)
</code>```

There you can change the value of the max.print in R.

Body:
You can use the options command to change the max.print value for the value limit you want to reach. For example:

options(max.print = 1000000)

There you can change the value of the max.print in R.


问:
Looking to form 2 sets of data from a object of arrays - Javascript
I am looking for help with the data in a football related app I am building.

Take this as a sample of the object I am dealing with:

```<code>const squad = {
  goalkeepers: [
    { player1: { score: 10 } },
    { player2: { score: 12 } }
  ],
  defenders: [
    { player3: { score: 3 } },
    { player4: { score: 19 } },
    { player5: { score: 5 } },
    { player6: { score: 21 } },
    { player7: { score: 6 } },
  ],
  midfielders: [
    { player8: { score: 7 } },
    { player9: { score: 1 } },
    { player10: { score: 18 } },
    { player11: { score: 11 } },
    { player12: { score: 8 } },
  ],
  attackers: [
    { player13: { score: 7 } },
    { player14: { score: 2 } },
    { player15: { score: 16 } }
  ]
}
</code>```

There are 15 players here and I want to divide them into two groups:

A strongest possible outfield team of 11 players based on their score value.

The remaining 4 players are to go on the bench.

The twist here is that there is a minimum and maximum number of players required in each position of the 11 outfield players.

Goalkeepers: EXACTLY 1.

Defenders: MIN 3, MAX 5.

Midfielders: MIN 2, MAX 5.

Forwards: MIN 1, MAX 3.

For anyone familiar with Fantasy Premier League, the rules work the same way:

Your team can play in any formation providing that 1 goalkeeper, at least 3 defenders and at least 1 forward are selected at all times.

I've tried concatinating the arrays to one large array and sorting them by player score value but I can't work out how to calculate the strongest first 11 players from that point while adhering to the position rules.

Any help would be greatly appreciated.

答:
I find a modular approach more intuitive and resilient.

This solution breaks the problem down into first converting your data to a more useful format, then finding all the combination of eleven players, then filtering out those that don't match the rules, then choosing the one with the largest score:

// utility functions
const maximumBy = (fn) => (xs) =>
  xs .reduce ((a, x, i) => fn (x) > fn (a) ? x : a, xs [0] || null)

const choose = (n, xs) =>
  n < 1 || n > xs .length
    ? []
  : n == 1
    ? [...xs .map (x => [x])]
  : [
      ...choose (n - 1, xs .slice (1)) .map (ys => [xs [0], ...ys]),
      ...choose (n , xs .slice (1))
    ]

// helper functions
const simplify = (squad) =>
  Object .entries (squad) .flatMap (
    ([position, vs]) => vs .flatMap (
      (v) => Object.entries (v) .flatMap (([name, s]) => ({position, name, ...s}))
    )
  )

const validate = (rules) => (lineup) => rules .every (({position, min, max}) => {
   const count = lineup .filter (({position: p}) => p == position) .length
   return count >= min && count <= max
})

const totalScore = (lineup) =>
  lineup .reduce ((t, {score}) => t + score, 0)

// main function
const bestLineup = (squad, rules) =>
  maximumBy (totalScore) (choose (11, simplify (squad)) .filter (validate (rules)))

// sample data
const rules = [{position: 'goalkeepers', min: 1, max: 1}, {position: 'defenders', min: 3, max: 5}, {position: 'midfielders', min: 2, max: 5}, {position: 'attackers', min: 1, max: 3}]

const squad = {goalkeepers: [{player1: {score: 10}}, {player2: {score: 12}}], defenders: [{player3: {score: 3}}, {player4: {score: 19}}, {player5: {score: 5}}, {player6: {score: 21}}, {player7: {score: 6}}], midfielders: [{player8: {score: 7}}, {player9: {score: 1}}, {player10: {score: 18}}, {player11: {score: 11}}, {player12: {score: 8}}], attackers: [{player13: {score: 7}}, {player14: {score: 2}}, {player15: {score: 16}}]}

// demo
console .log (bestLineup (squad, rules))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

We start with two general-purpose utility functions we might use in other projects

maximumBy takes a function that converts a value into a comparable one -- in this problem we use it to extract the score -- and return a function that accepts an array of values, runs that function on each and chooses the one with the largest score.  (This version is less efficient than it could be.  I'd rather focus on simplicity at the moment.

choose finds all subsets of n elements of your array of values.  For instance, choose (2, ['a', 'b', 'c', 'd']) returns [['a', 'b'], ['a', 'c'], ['a', 'd']. ['b', 'c'], ['b', 'd'], ['c', 'd']].

Then we have some helper functions,

simplify turns your initial squad format into something more tractable:

[
  {name: "player1", position: "goalkeepers", score: 10},
  {name: "player2", position: "goalkeepers", score: 12},
  {name: "player3", position: "defenders", score: 3},
  // ...
  {name: "player15", position: "attackers", score: 16}
]
```
</li>
<li><p><strong><code>validate</code></strong> takes an array of rules such as</p>
<pre class="lang-js prettyprint-override"><code>{position: 'defenders', min: 3, max: 5}
</code>```

and returns a function that takes a lineup from the squad and reports whether that lineup obeys all the rules.

totalScore takes a lineup and sums up the scores of all the players

Finally, our main function, bestLineup accepts a squad and an array of rules, simplifies the squad, chooses all lineups of eleven players, filters it down to just those which validate according to the rules, and chooses the maximum by our function that calculates their total score.

If you want the output in the same format as the input, we can just call one more helper to undo our simplify; let's call it complexify:

const complexify = (xs) =>
  xs .reduce (
    (a, {name, position, score}) => (
      (a [position] = a [position] || []), (a [position] .push ({[name]: {score}})), a
    ), {})
```
<p>which will transform an array of the simple format used above back into something like this:</p>
<pre class="lang-js prettyprint-override"><code>{
    goalkeepers: [
        {player2: {score: 12}}
    ],
    defenders: [
        {player4: {score: 19}},
        {player5: {score: 5}},
        {player6: {score: 21}},
        {player7: {score: 6}}
    ],
    midfielders: [
        {player8: {score: 7}},
        {player10: {score: 18}},
        {player11: {score: 11}},
        {player12: {score: 8}}
    ]
    attackers: [
        {player13: {score: 7}},
        {player15: {score: 16}}
    ],
}
</code>```

But I would only do this if your unusual data format is forced upon you.

Body:
I am looking for help with the data in a football related app I am building.

Take this as a sample of the object I am dealing with:

const squad = {
  goalkeepers: [
    { player1: { score: 10 } },
    { player2: { score: 12 } }
  ],
  defenders: [
    { player3: { score: 3 } },
    { player4: { score: 19 } },
    { player5: { score: 5 } },
    { player6: { score: 21 } },
    { player7: { score: 6 } },
  ],
  midfielders: [
    { player8: { score: 7 } },
    { player9: { score: 1 } },
    { player10: { score: 18 } },
    { player11: { score: 11 } },
    { player12: { score: 8 } },
  ],
  attackers: [
    { player13: { score: 7 } },
    { player14: { score: 2 } },
    { player15: { score: 16 } }
  ]
}

There are 15 players here and I want to divide them into two groups:

A strongest possible outfield team of 11 players based on their score value.

The remaining 4 players are to go on the bench.

The twist here is that there is a minimum and maximum number of players required in each position of the 11 outfield players.

Goalkeepers: EXACTLY 1.

Defenders: MIN 3, MAX 5.

Midfielders: MIN 2, MAX 5.

Forwards: MIN 1, MAX 3.

For anyone familiar with Fantasy Premier League, the rules work the same way:

Your team can play in any formation providing that 1 goalkeeper, at least 3 defenders and at least 1 forward are selected at all times.

I've tried concatinating the arrays to one large array and sorting them by player score value but I can't work out how to calculate the strongest first 11 players from that point while adhering to the position rules.

Any help would be greatly appreciated.

Body:
I find a modular approach more intuitive and resilient.

This solution breaks the problem down into first converting your data to a more useful format, then finding all the combination of eleven players, then filtering out those that don't match the rules, then choosing the one with the largest score:

// utility functions
const maximumBy = (fn) => (xs) =>
  xs .reduce ((a, x, i) => fn (x) > fn (a) ? x : a, xs [0] || null)

const choose = (n, xs) =>
  n < 1 || n > xs .length
    ? []
  : n == 1
    ? [...xs .map (x => [x])]
  : [
      ...choose (n - 1, xs .slice (1)) .map (ys => [xs [0], ...ys]),
      ...choose (n , xs .slice (1))
    ]

// helper functions
const simplify = (squad) =>
  Object .entries (squad) .flatMap (
    ([position, vs]) => vs .flatMap (
      (v) => Object.entries (v) .flatMap (([name, s]) => ({position, name, ...s}))
    )
  )

const validate = (rules) => (lineup) => rules .every (({position, min, max}) => {
   const count = lineup .filter (({position: p}) => p == position) .length
   return count >= min && count <= max
})

const totalScore = (lineup) =>
  lineup .reduce ((t, {score}) => t + score, 0)

// main function
const bestLineup = (squad, rules) =>
  maximumBy (totalScore) (choose (11, simplify (squad)) .filter (validate (rules)))

// sample data
const rules = [{position: 'goalkeepers', min: 1, max: 1}, {position: 'defenders', min: 3, max: 5}, {position: 'midfielders', min: 2, max: 5}, {position: 'attackers', min: 1, max: 3}]

const squad = {goalkeepers: [{player1: {score: 10}}, {player2: {score: 12}}], defenders: [{player3: {score: 3}}, {player4: {score: 19}}, {player5: {score: 5}}, {player6: {score: 21}}, {player7: {score: 6}}], midfielders: [{player8: {score: 7}}, {player9: {score: 1}}, {player10: {score: 18}}, {player11: {score: 11}}, {player12: {score: 8}}], attackers: [{player13: {score: 7}}, {player14: {score: 2}}, {player15: {score: 16}}]}

// demo
console .log (bestLineup (squad, rules))

.as-console-wrapper {max-height: 100% !important; top: 0}

We start with two general-purpose utility functions we might use in other projects

maximumBy takes a function that converts a value into a comparable one -- in this problem we use it to extract the score -- and return a function that accepts an array of values, runs that function on each and chooses the one with the largest score.  (This version is less efficient than it could be.  I'd rather focus on simplicity at the moment.

choose finds all subsets of n elements of your array of values.  For instance, choose (2, ['a', 'b', 'c', 'd']) returns [['a', 'b'], ['a', 'c'], ['a', 'd']. ['b', 'c'], ['b', 'd'], ['c', 'd']].

Then we have some helper functions,

simplify turns your initial squad format into something more tractable:

[
  {name: "player1", position: "goalkeepers", score: 10},
  {name: "player2", position: "goalkeepers", score: 12},
  {name: "player3", position: "defenders", score: 3},
  // ...
  {name: "player15", position: "attackers", score: 16}
]

validate takes an array of rules such as

{position: 'defenders', min: 3, max: 5}

and returns a function that takes a lineup from the squad and reports whether that lineup obeys all the rules.

totalScore takes a lineup and sums up the scores of all the players

Finally, our main function, bestLineup accepts a squad and an array of rules, simplifies the squad, chooses all lineups of eleven players, filters it down to just those which validate according to the rules, and chooses the maximum by our function that calculates their total score.

If you want the output in the same format as the input, we can just call one more helper to undo our simplify; let's call it complexify:

const complexify = (xs) =>
  xs .reduce (
    (a, {name, position, score}) => (
      (a [position] = a [position] || []), (a [position] .push ({[name]: {score}})), a
    ), {})

which will transform an array of the simple format used above back into something like this:

{
    goalkeepers: [
        {player2: {score: 12}}
    ],
    defenders: [
        {player4: {score: 19}},
        {player5: {score: 5}},
        {player6: {score: 21}},
        {player7: {score: 6}}
    ],
    midfielders: [
        {player8: {score: 7}},
        {player10: {score: 18}},
        {player11: {score: 11}},
        {player12: {score: 8}}
    ]
    attackers: [
        {player13: {score: 7}},
        {player15: {score: 16}}
    ],
}

But I would only do this if your unusual data format is forced upon you.