问:
Uncaught SyntaxError: expected expression, got keyword 'var' on she-header.js
I'm new to this forum and am currently receiving the error Uncaught SyntaxError: expected expression, got keyword 'var' on my she-header.js beginning at console.log and ending at header height shrink. Any help would be much appreciated. I have not tried much, and the support available is not very informative about this problem.

```<code>var $j = jQuery.noConflict();

$j( document ).ready( function() {
    "use strict";
    // She header
    sheHeader();
} );

/* ==============================================
HEADER EFFECTS
============================================== */

function sheHeader() {

    var header = $j('.she-header-yes'),
        container = $j('.she-header-yes .elementor-container, .she-header-yes.e-container'),
        header_elementor = $j('.elementor-edit-mode .she-header-yes'),
        header_logo = $j('.she-header-yes .elementor-widget-theme-site-logo .elementor-image, .she-header-yes .elementor-widget-image .elementor-image'),
        data_settings = header.data('settings');

    if ( typeof data_settings != 'undefined' ) {
        var responsive_settings = data_settings["transparent_on"];
        var width = $j(window).width(),
            header_height= header.height(),
            logo_width = header_logo.width(),
            logo_height = header_logo.height() ;
        }

    // Check responsive is enabled
    if( typeof width != 'undefined' && width) {
    if( width >= 1025 ) {
    var enabled = "desktop";
    }else if (width  > 767 && width < 1025  ) {
    var enabled = "tablet";
    }else if (width <= 767 ) {
    var enabled = "mobile";
    }
    }

    console.log($j.inArray(enabled, responsive_settings));

    if ($j.inArray(enabled, responsive_settings)!='-1') {

    var scroll_distance = data_settings["scroll_distance"];
    var transparent_header = data_settings["transparent_header_show"];
    var background = data_settings["background"];
    var bottom_border_color = data_settings["custom_bottom_border_color"],
        bottom_border_view = data_settings["bottom_border"],
        bottom_border_width = data_settings["custom_bottom_border_width"];

    var shrink_header = data_settings["shrink_header"],
        data_height = data_settings["custom_height_header"],
        data_height_tablet = data_settings["custom_height_header_tablet"],
        data_height_mobile = data_settings["custom_height_header_mobile"];
    var shrink_logo = data_settings["shrink_header_logo"],
        data_logo_height = data_settings["custom_height_header_logo"],
        data_logo_height_tablet = data_settings["custom_height_header_logo_tablet"],
        data_logo_height_mobile = data_settings["custom_height_header_logo_mobile"];

    var change_logo_color = data_settings["change_logo_color"];

    var blur_bg  = data_settings["blur_bg"];

    var scroll_distance_hide_header = data_settings["scroll_distance_hide_header"];**

    // add transparent class
    if(transparent_header == "yes" ){
        header.addClass('she-header-transparent-yes');
    }

    // header height shrink
    if( typeof data_height != 'undefined' && data_height) {
    if( width >= 1025 ) {
        var shrink_height = data_height["size"];
    }else if (width  > 767 && width < 1025  ) {
        var shrink_height = data_height_tablet["size"];
        if(shrink_height == ''){
           shrink_height = data_height["size"];
        }
    }else if (width <= 767 ) {
        var shrink_height = data_height_mobile["size"];
        if(shrink_height == ''){
           shrink_height = data_height["size"];
        }
    }
    }

        // border bottom
        if( typeof bottom_border_width != 'undefined' && bottom_border_width) {
        var bottom_border = bottom_border_width["size"] + "px solid " + bottom_border_color;
        }

        // hide header on scroll
        if( typeof scroll_distance_hide_header != 'undefined' && scroll_distance_hide_header) {

            var mywindow = $j(window);
            var mypos = mywindow.scrollTop();

                mywindow.scroll(function() {
                    if (mypos > scroll_distance_hide_header["size"]) {
                        if(mywindow.scrollTop() > mypos)
                        {
                            header.addClass('headerup');
                        }else{
                            header.removeClass('headerup');
                        }
                    }
                    mypos = mywindow.scrollTop();
                });
        }

        // scroll function
        $j(window).on("load scroll",function(e){
            var scroll = $j(window).scrollTop();

            if (header_elementor) {
                header_elementor.css("position", "relative");
            }

            if (scroll >= scroll_distance["size"]) {
                header.removeClass('header').addClass("she-header");
                header.css("background-color", background);
                header.css("border-bottom", bottom_border);
                header.removeClass('she-header-transparent-yes');

                if( shrink_header == "yes" ) {
                    header.css({"padding-top":"0", "padding-bottom":"0", "margin-top":"0", "margin-bottom":"0"});
                    container.css({"min-height": shrink_height, "transition": "all 0.4s ease-in-out", "-webkit-transition": "all 0.4s ease-in-out", "-moz-transition": "all 0.4s ease-in-out"});

                }

                if( change_logo_color == "yes" ) {
                    header_logo.addClass("change-logo-color");

                }

                if( blur_bg == "yes" ) {
                    header.css({"backdrop-filter": "saturate(180%) blur(20px)", "-webkit-backdrop-filter": "saturate(180%) blur(20px)"});

                }

                } else {
                    header.removeClass("she-header").addClass('header');
                    header.css("background-color", "");
                    header.css("border-bottom", "");

                    if(transparent_header == "yes" ){
                        header.addClass('she-header-transparent-yes');
                    }
                    if( shrink_header == "yes" ) {
                        header.css({"padding-top":"", "padding-bottom":"", "margin-top":"", "margin-bottom":""});
                        container.css("min-height", "");
                    }
                    if( change_logo_color == "yes" ) {
                    header_logo.removeClass("change-logo-color");

                }
                    if( blur_bg == "yes" ) {
                        header.css({"backdrop-filter": "", "-webkit-backdrop-filter": ""});
                    }
                }

        });
    }

};

</code>```

Body:
I'm new to this forum and am currently receiving the error Uncaught SyntaxError: expected expression, got keyword 'var' on my she-header.js beginning at console.log and ending at header height shrink. Any help would be much appreciated. I have not tried much, and the support available is not very informative about this problem.

var $j = jQuery.noConflict();

$j( document ).ready( function() {
    "use strict";
    // She header
    sheHeader();
} );

/* ==============================================
HEADER EFFECTS
============================================== */

function sheHeader() {

    var header = $j('.she-header-yes'),
        container = $j('.she-header-yes .elementor-container, .she-header-yes.e-container'),
        header_elementor = $j('.elementor-edit-mode .she-header-yes'),
        header_logo = $j('.she-header-yes .elementor-widget-theme-site-logo .elementor-image, .she-header-yes .elementor-widget-image .elementor-image'),
        data_settings = header.data('settings');

    if ( typeof data_settings != 'undefined' ) {
        var responsive_settings = data_settings["transparent_on"];
        var width = $j(window).width(),
            header_height= header.height(),
            logo_width = header_logo.width(),
            logo_height = header_logo.height() ;
        }

    // Check responsive is enabled
    if( typeof width != 'undefined' && width) {
    if( width >= 1025 ) {
    var enabled = "desktop";
    }else if (width  > 767 && width < 1025  ) {
    var enabled = "tablet";
    }else if (width <= 767 ) {
    var enabled = "mobile";
    }
    }

    console.log($j.inArray(enabled, responsive_settings));

    if ($j.inArray(enabled, responsive_settings)!='-1') {

    var scroll_distance = data_settings["scroll_distance"];
    var transparent_header = data_settings["transparent_header_show"];
    var background = data_settings["background"];
    var bottom_border_color = data_settings["custom_bottom_border_color"],
        bottom_border_view = data_settings["bottom_border"],
        bottom_border_width = data_settings["custom_bottom_border_width"];

    var shrink_header = data_settings["shrink_header"],
        data_height = data_settings["custom_height_header"],
        data_height_tablet = data_settings["custom_height_header_tablet"],
        data_height_mobile = data_settings["custom_height_header_mobile"];
    var shrink_logo = data_settings["shrink_header_logo"],
        data_logo_height = data_settings["custom_height_header_logo"],
        data_logo_height_tablet = data_settings["custom_height_header_logo_tablet"],
        data_logo_height_mobile = data_settings["custom_height_header_logo_mobile"];

    var change_logo_color = data_settings["change_logo_color"];

    var blur_bg  = data_settings["blur_bg"];

    var scroll_distance_hide_header = data_settings["scroll_distance_hide_header"];**

    // add transparent class
    if(transparent_header == "yes" ){
        header.addClass('she-header-transparent-yes');
    }

    // header height shrink
    if( typeof data_height != 'undefined' && data_height) {
    if( width >= 1025 ) {
        var shrink_height = data_height["size"];
    }else if (width  > 767 && width < 1025  ) {
        var shrink_height = data_height_tablet["size"];
        if(shrink_height == ''){
           shrink_height = data_height["size"];
        }
    }else if (width <= 767 ) {
        var shrink_height = data_height_mobile["size"];
        if(shrink_height == ''){
           shrink_height = data_height["size"];
        }
    }
    }

        // border bottom
        if( typeof bottom_border_width != 'undefined' && bottom_border_width) {
        var bottom_border = bottom_border_width["size"] + "px solid " + bottom_border_color;
        }

        // hide header on scroll
        if( typeof scroll_distance_hide_header != 'undefined' && scroll_distance_hide_header) {

            var mywindow = $j(window);
            var mypos = mywindow.scrollTop();

                mywindow.scroll(function() {
                    if (mypos > scroll_distance_hide_header["size"]) {
                        if(mywindow.scrollTop() > mypos)
                        {
                            header.addClass('headerup');
                        }else{
                            header.removeClass('headerup');
                        }
                    }
                    mypos = mywindow.scrollTop();
                });
        }

        // scroll function
        $j(window).on("load scroll",function(e){
            var scroll = $j(window).scrollTop();

            if (header_elementor) {
                header_elementor.css("position", "relative");
            }

            if (scroll >= scroll_distance["size"]) {
                header.removeClass('header').addClass("she-header");
                header.css("background-color", background);
                header.css("border-bottom", bottom_border);
                header.removeClass('she-header-transparent-yes');

                if( shrink_header == "yes" ) {
                    header.css({"padding-top":"0", "padding-bottom":"0", "margin-top":"0", "margin-bottom":"0"});
                    container.css({"min-height": shrink_height, "transition": "all 0.4s ease-in-out", "-webkit-transition": "all 0.4s ease-in-out", "-moz-transition": "all 0.4s ease-in-out"});

                }

                if( change_logo_color == "yes" ) {
                    header_logo.addClass("change-logo-color");

                }

                if( blur_bg == "yes" ) {
                    header.css({"backdrop-filter": "saturate(180%) blur(20px)", "-webkit-backdrop-filter": "saturate(180%) blur(20px)"});

                }

                } else {
                    header.removeClass("she-header").addClass('header');
                    header.css("background-color", "");
                    header.css("border-bottom", "");

                    if(transparent_header == "yes" ){
                        header.addClass('she-header-transparent-yes');
                    }
                    if( shrink_header == "yes" ) {
                        header.css({"padding-top":"", "padding-bottom":"", "margin-top":"", "margin-bottom":""});
                        container.css("min-height", "");
                    }
                    if( change_logo_color == "yes" ) {
                    header_logo.removeClass("change-logo-color");

                }
                    if( blur_bg == "yes" ) {
                        header.css({"backdrop-filter": "", "-webkit-backdrop-filter": ""});
                    }
                }

        });
    }

};


来源: stackexchange

问:
Examples set using @examples fails devtools::check()
I am making an R package, and using roxygen2 to create documentation.

I have provided an example for one of the functions using:

```<code>#' @examples
#' \dontrun{
#' Train_model()
#' }
</code>```

I have included an @export tag before this.

But, when I run devtools::check(). I get the following error:

```<code>Error in library("package1") :
there is no package called 'package1'
</code>```

package1 is the name of the package I am creating.

ContentLicense: CC BY-SA 4.0

Body:
I am making an R package, and using roxygen2 to create documentation.

I have provided an example for one of the functions using:

#' @examples
#' \dontrun{
#' Train_model()
#' }

I have included an @export tag before this.

But, when I run devtools::check(). I get the following error:

Error in library("package1") :
there is no package called 'package1'

package1 is the name of the package I am creating.


问:
Unable to send email based on CRON expression
I have a background service which runs every hour, will read the cron expression from my table
and would like to send an email at the exact time when the date time from the cron expression reaches or past the current date time :

```<code>if(DateTime.Now >= CronDatetime) //should be true but its always false
{
   //send email
}
</code>```

My cron expression is = "44 12 11 12 *"; run at 11 dec at 12:44 pm

I am using NCrontab library.

Code:

```<code>var cronExpression = CrontabSchedule.Parse("44 12 11 12 *");
var CronDatetime = cronExpression.GetNextOccurrence(DateTime.Now); // returns 2023-12-11 12:44:00 pm
if(DateTime.Now >= CronDatetime) //always false
{
   //send email
}
</code>```

Now the problem is that the code below always returns the future date time based on cron expression and hence I am not able to send email once the time is reached:

```<code>var CronDatetime = cronExpression.GetNextOccurrence(DateTime.Now); // returns 2023-12-11 12:44:00 pm
</code>```

How can I send email once the time is reached based on cron expression?

Body:
I have a background service which runs every hour, will read the cron expression from my table
and would like to send an email at the exact time when the date time from the cron expression reaches or past the current date time :

if(DateTime.Now >= CronDatetime) //should be true but its always false
{
   //send email
}

My cron expression is = "44 12 11 12 *"; run at 11 dec at 12:44 pm

I am using NCrontab library.

Code:

var cronExpression = CrontabSchedule.Parse("44 12 11 12 *");
var CronDatetime = cronExpression.GetNextOccurrence(DateTime.Now); // returns 2023-12-11 12:44:00 pm
if(DateTime.Now >= CronDatetime) //always false
{
   //send email
}

Now the problem is that the code below always returns the future date time based on cron expression and hence I am not able to send email once the time is reached:

var CronDatetime = cronExpression.GetNextOccurrence(DateTime.Now); // returns 2023-12-11 12:44:00 pm

How can I send email once the time is reached based on cron expression?


问:
PostgreSQL copy issues
I am trying to copy my PostgreSQL query result set into an excel file since Tableau Public does not connect to PostgreSQL.

I am unsure how to get my result set into excel. I've been watching countless YouTube vids and read numerous stack overflow & postgresql threads to no avail. I am using postgresql 14 on pgadmin on a Mac. Appreciate any response!

The code below is what I tried and I get this error message:

```<code>copy (select * from emp) to '/Users/my_name/Desktop/sql_query.csv' with csv

ERROR:  could not open file "/Users/my_name/Desktop/sql_query.csv" for writing: Permission denied
HINT:  COPY TO instructs the PostgreSQL server process to write a file. You may want a client-side facility such as psql's \copy.
SQL state: 42501

</code>```

I also tried \copy and got this error message:

```<code>ERROR:  syntax error at or near "\"
LINE 1: \copy (select * from emp) to '/Users/my_name/Desktop/sq...
        ^
SQL state: 42601
Character: 1
</code>```

Title: PostgreSQL copy issues

Body:
I am trying to copy my PostgreSQL query result set into an excel file since Tableau Public does not connect to PostgreSQL.

I am unsure how to get my result set into excel. I've been watching countless YouTube vids and read numerous stack overflow & postgresql threads to no avail. I am using postgresql 14 on pgadmin on a Mac. Appreciate any response!

The code below is what I tried and I get this error message:

copy (select * from emp) to '/Users/my_name/Desktop/sql_query.csv' with csv

ERROR:  could not open file "/Users/my_name/Desktop/sql_query.csv" for writing: Permission denied
HINT:  COPY TO instructs the PostgreSQL server process to write a file. You may want a client-side facility such as psql's \copy.
SQL state: 42501

I also tried \copy and got this error message:

ERROR:  syntax error at or near "\"
LINE 1: \copy (select * from emp) to '/Users/my_name/Desktop/sq...
        ^
SQL state: 42601
Character: 1


问:
How to console.log data of a nested object from API with axios?
I am learning to fetch data from api right now. I have a local database written on RoR. I have game model and a nested player model inside of it. When I go to http://localhost:3000/api/v1/games, I see right json data:

[
  {
    id: 1,
    code: "KR984",
    name: "Hello world",
    created_at: "2022-12-02T13:34:51.992Z",
    updated_at: "2022-12-07T10:32:35.827Z",
    slug: null,
    fight: false,
    players: [
      {
        id: 1,
        name: "PLAYER 1",
        initiative: null,
        hp: 20,
        languages: "sjdads",
        perc: "12",
        inv: "12",
        ins: "12",
        armor: 44,
        conc: true,
        created_at: "2022-12-11T17:18:33.745Z",
        updated_at: "2022-12-11T17:18:33.745Z",
        game_id: 1,
      },
    ],
  },
  {
    id: 2,
    code: "BT526",
    name: "Random game",
    created_at: "2022-12-07T10:14:16.948Z",
    updated_at: "2022-12-07T10:14:16.948Z",
    slug: null,
    fight: false,
    players: [],
  },
];
```
<p>As you can see, I have one player inside the game with id: 1</p>
<p>When I fetch this data with axios in my React-native app I get all the info about games:</p>
<p>Output in console:</p>
<pre class="lang-js prettyprint-override"><code>[
  {
    code: "KR984",
    created_at: "2022-12-02T13:34:51.992Z",
    fight: false,
    id: 1,
    name: "Hello world",
    players: [[Object]],
    slug: null,
    updated_at: "2022-12-07T10:32:35.827Z",
  },
  {
    code: "BT526",
    created_at: "2022-12-07T10:14:16.948Z",
    fight: false,
    id: 2,
    name: "Random game",
    players: [],
    slug: null,
    updated_at: "2022-12-07T10:14:16.948Z",
  },
];
</code>```

However, as you can see I can't get any data related to players. It's just an [[Object]].
What am I missing. And sorry, if it's a stupid question - I am a newbie.

That is how tried to fetch data firstly:

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);

useEffect(() => {
  axios
    .get("http://localhost:3000/api/v1/games")
    .then(({ data }) => {
      console.log(data);
      setData(data);
    })
    .catch((error) => console.error(error))
    .finally(() => setLoading(false));
}, []);
```
<p>Then I read that the problem might be solved with an asyns/await function, but got the same result:</p>
<pre class="lang-js prettyprint-override"><code>const [isLoading, setLoading] = useState(true);
const [testData, setTestData] = useState(null);

async function fetchData() {
  try {
    const response = await axios.get("http://localhost:3000/api/v1/games");
    setTestData(response.data);
    console.log(testData);
  } catch (err) {
    const errorMessage = "Error: " + err.message;
    setError(errorMessage);
    console.log(errorMessage);
  } finally {
    setLoading(false);
  }
}

useEffect(() => {
  fetchData();
}, []);
</code>```

Body:
I am learning to fetch data from api right now. I have a local database written on RoR. I have game model and a nested player model inside of it. When I go to http://localhost:3000/api/v1/games, I see right json data:

[
  {
    id: 1,
    code: "KR984",
    name: "Hello world",
    created_at: "2022-12-02T13:34:51.992Z",
    updated_at: "2022-12-07T10:32:35.827Z",
    slug: null,
    fight: false,
    players: [
      {
        id: 1,
        name: "PLAYER 1",
        initiative: null,
        hp: 20,
        languages: "sjdads",
        perc: "12",
        inv: "12",
        ins: "12",
        armor: 44,
        conc: true,
        created_at: "2022-12-11T17:18:33.745Z",
        updated_at: "2022-12-11T17:18:33.745Z",
        game_id: 1,
      },
    ],
  },
  {
    id: 2,
    code: "BT526",
    name: "Random game",
    created_at: "2022-12-07T10:14:16.948Z",
    updated_at: "2022-12-07T10:14:16.948Z",
    slug: null,
    fight: false,
    players: [],
  },
];

As you can see, I have one player inside the game with id: 1

When I fetch this data with axios in my React-native app I get all the info about games:

Output in console:

[
  {
    code: "KR984",
    created_at: "2022-12-02T13:34:51.992Z",
    fight: false,
    id: 1,
    name: "Hello world",
    players: [[Object]],
    slug: null,
    updated_at: "2022-12-07T10:32:35.827Z",
  },
  {
    code: "BT526",
    created_at: "2022-12-07T10:14:16.948Z",
    fight: false,
    id: 2,
    name: "Random game",
    players: [],
    slug: null,
    updated_at: "2022-12-07T10:14:16.948Z",
  },
];

However, as you can see I can't get any data related to players. It's just an [[Object]].
What am I missing. And sorry, if it's a stupid question - I am a newbie.

That is how tried to fetch data firstly:

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);

useEffect(() => {
  axios
    .get("http://localhost:3000/api/v1/games")
    .then(({ data }) => {
      console.log(data);
      setData(data);
    })
    .catch((error) => console.error(error))
    .finally(() => setLoading(false));
}, []);

Then I read that the problem might be solved with an asyns/await function, but got the same result:

const [isLoading, setLoading] = useState(true);
const [testData, setTestData] = useState(null);

async function fetchData() {
  try {
    const response = await axios.get("http://localhost:3000/api/v1/games");
    setTestData(response.data);
    console.log(testData);
  } catch (err) {
    const errorMessage = "Error: " + err.message;
    setError(errorMessage);
    console.log(errorMessage);
  } finally {
    setLoading(false);
  }
}

useEffect(() => {
  fetchData();
}, []);


问:
How do I avoid repeating HoC code when it differs by type between Animated and non-Animated components?
I'm trying to find a way of making my HoC handle both Animated and non-Animated versions of View and Text.

Right now I have two pieces of code that are similar except for the typings because Animated.View and View are different.

```<code>
/**
 * This wraps a view component so the styles are exposed.
 * @param Component component to wrap
 * @param options options for the HoC building
 * @typeParam Q the props for the wrapped component
 * @typeParam T type for ref attribute of the wrapped component
 * @typeParam O options for the HoC building
 * @returns A named exotic componentwith P props that accepts a ref
 */
export function withStyled<Q extends Animated.AnimateProps<ViewProps>, O = {}>(Component: ComponentType<Q>, options?: O): NamedExoticComponent<PropsWithoutRef<StyleProps & Q> & RefAttributes<Animated.View>> {
    function useWrapped(props: StyleProps & Q, ref: Ref<Animated.View>): ReactElement<Q> {
        // the an unknown as Q here is an example, but P and Q can be different.
        const componentProps: Q = props as unknown as Q;
        return <Component {...componentProps} ref={ref} />;
    }
    const displayName = Component.displayName || Component.name || "AnonymousComponent";
    useWrapped.displayName = displayName;
    return forwardRef(useWrapped);
}

/**
 * This wraps a view component so the styles are exposed.
 * @param Component component to wrap
 * @param options options for the HoC building
 * @typeParam Q the props for the wrapped component
 * @typeParam T type for ref attribute of the wrapped component
 * @typeParam O options for the HoC building
 * @returns A named exotic componentwith P props that accepts a ref
 */
export function withStyledNoAnimation<Q extends ViewProps, O = {}>(Component: ComponentType<Q>, options?: O): NamedExoticComponent<PropsWithoutRef<StyleProps & Q> & RefAttributes<View>> {
    function useWrapped(props: StyleProps & Q, ref: Ref<View>): ReactElement<Q> {
        // the an unknown as Q here is an example, but P and Q can be different.
        const componentProps: Q = props as unknown as Q;
        return <Component {...componentProps} ref={ref} />;
    }
    const displayName = Component.displayName || Component.name || "AnonymousComponent";
    useWrapped.displayName = displayName;
    return forwardRef(useWrapped);
}
</code>```

Body:
I'm trying to find a way of making my HoC handle both Animated and non-Animated versions of View and Text.

Right now I have two pieces of code that are similar except for the typings because Animated.View and View are different.

/**
 * This wraps a view component so the styles are exposed.
 * @param Component component to wrap
 * @param options options for the HoC building
 * @typeParam Q the props for the wrapped component
 * @typeParam T type for ref attribute of the wrapped component
 * @typeParam O options for the HoC building
 * @returns A named exotic componentwith P props that accepts a ref
 */
export function withStyled<Q extends Animated.AnimateProps<ViewProps>, O = {}>(Component: ComponentType<Q>, options?: O): NamedExoticComponent<PropsWithoutRef


问:
Compare files in VSCode and output the differences automatically to a separate file
I use VSCode to compare 2 large csv files (each is almost 140k lines).. I have used >compare active file with..

I want to extract only the difference to clean it up manually.

How can I do that?

Is there any extension or tip will help me on this?


问:
if else statement for netmiko
i want to write a python script that will check for variables in the switch configuration, if the variables are there, the script will not input them, but if the variables aren't there, the script will configure it. after the config, the script should print a CSV of all the commands attached to a particular ip.</p>
```<code>from netmiko import ConnectHandler
from getpass import getpass
import readline
import time
import os
from datetime import datetime
from csv import reader

with open("/Users/ben/desktop/ntptest.csv", "r") as f:
    devices_list = f.read().splitlines

for devices in devices_list():
    print ('connecting to device'  + devices)
    ip = devices

cisco1 = {
    "device_type": "cisco_ios",
    "host": devices,
    "username": "****",
    "password": getpass(),
    "port" : 22,
    'verbose' : True
    }

with ConnectHandler(**devices) as net_connect:
    output = net_connect.send_command['sh ntp status', 'sh clock det', 'sh ntp ass']
    net_connect.enable()
    print("Connected Successfully")

P = '192.168.1.1'
S = '192.1.1.1.'

if output [1] == P and output [2] == S:
    print ('Both Primary and Secondary NTP are present')
elif output [1] == None and output [2] == S:
    output1 = net_connect.send_config_set('conf t' , 'ntp 192.168.9.9')
    print(output, output1)
elif output [1] == P and output [2] == None:
    output2 = net_connect.send_config_set('conf t', 'ntp server 192.168.9.9')
    print(output, output2)
elif output [1] == None and output [2] == None:
    output3 = net_connect.send_config_set('conf t', 'ntp server 192.1.1.1', 'ntp server 134.174.17.6')
    print(output, output3)
else:
    print('None of the condition exist')
</code>```

Title: if else statement for netmiko

Body:
i want to write a python script that will check for variables in the switch configuration, if the variables are there, the script will not input them, but if the variables aren't there, the script will configure it. after the config, the script should print a CSV of all the commands attached to a particular ip.

from netmiko import ConnectHandler
from getpass import getpass
import readline
import time
import os
from datetime import datetime
from csv import reader

with open("/Users/ben/desktop/ntptest.csv", "r") as f:
    devices_list = f.read().splitlines

for devices in devices_list():
    print ('connecting to device'  + devices)
    ip = devices

cisco1 = {
    "device_type": "cisco_ios",
    "host": devices,
    "username": "****",
    "password": getpass(),
    "port" : 22,
    'verbose' : True
    }

with ConnectHandler(**devices) as net_connect:
    output = net_connect.send_command['sh ntp status', 'sh clock det', 'sh ntp ass']
    net_connect.enable()
    print("Connected Successfully")

P = '192.168.1.1'
S = '192.1.1.1.'

if output [1] == P and output [2] == S:
    print ('Both Primary and Secondary NTP are present')
elif output [1] == None and output [2] == S:
    output1 = net_connect.send_config_set('conf t' , 'ntp 192.168.9.9')
    print(output, output1)
elif output [1] == P and output [2] == None:
    output2 = net_connect.send_config_set('conf t', 'ntp server 192.168.9.9')
    print(output, output2)
elif output [1] == None and output [2] == None:
    output3 = net_connect.send_config_set('conf t', 'ntp server 192.1.1.1', 'ntp server 134.174.17.6')
    print(output, output3)
else:
    print('None of the condition exist')


问:
Extra Info printed with Cryptographic Hashing code in Python
So a while back I was working on a Cryptographic Hashing project for a class I am no longer in. The code works almost perfect but Prints out the letter "b" and then the given imput before t printing the hashes.

Example if imput is "I like pizza." Then the output wpuld be " b'I like pizza.'" then the hashes. Here is the code I figured a second set of eyes could give me an Idea of where I messed up. Its a mix of the code my professor provided and my own but it was about a year ago so I don't remember what is his and what is mine. He primarilly provided the hash list and the the code to import it from what I remember.

This is the code listed below:

```<code>import hashlib
import random

def main(s):
    hash_list = [
                    hashlib.md5(),
                    hashlib.sha1(),
                    hashlib.sha224(),
                    hashlib.sha256(),
                    hashlib.blake2b()
                ]
    hashing_name = ["md5", "sha1", "sha224", "sha256", "blake2b"]

    length_of_salt = 13
    salt = "".join(random.choice('0123456789') for i in range(length_of_salt))
    hexa = hex(int(salt))
    salt = hexa.split('x')[-1]
    salt = hexa.encode('utf-8')

    for i in range(5):
        m = hash_list[i]
        m.update(s+salt)
        print("Testing hash algorithm", hashing_name[i], "Hashed Password = ", m.hexdigest()+":"+hexa)

if __name__ == "__main__":
    s = input().encode('utf-8')
    print(s)
    main(s)
</code>```

I was trying to get hashes, which I got, but it prints out extran information first.

Body:
So a while back I was working on a Cryptographic Hashing project for a class I am no longer in. The code works almost perfect but Prints out the letter "b" and then the given imput before t printing the hashes.

Example if imput is "I like pizza." Then the output wpuld be " b'I like pizza.'" then the hashes. Here is the code I figured a second set of eyes could give me an Idea of where I messed up. Its a mix of the code my professor provided and my own but it was about a year ago so I don't remember what is his and what is mine. He primarilly provided the hash list and the the code to import it from what I remember.

This is the code listed below:

import hashlib
import random

def main(s):
    hash_list = [
                    hashlib.md5(),
                    hashlib.sha1(),
                    hashlib.sha224(),
                    hashlib.sha256(),
                    hashlib.blake2b()
                ]
    hashing_name = ["md5", "sha1", "sha224", "sha256", "blake2b"]

    length_of_salt = 13
    salt = "".join(random.choice('0123456789') for i in range(length_of_salt))
    hexa = hex(int(salt))
    salt = hexa.split('x')[-1]
    salt = hexa.encode('utf-8')

    for i in range(5):
        m = hash_list[i]
        m.update(s+salt)
        print("Testing hash algorithm", hashing_name[i], "Hashed Password = ", m.hexdigest()+":"+hexa)

if __name__ == "__main__":
    s = input().encode('utf-8')
    print(s)
    main(s)

I was trying to get hashes, which I got, but it prints out extran information first.


问:
HTML Code Works Different In Streamlit (General Problem)
Summary

While there is a video effect in the HTML and CSS files, this effect does not work when the same code is run in the streamlit.

I’ve had this problem before. Is this a general problem or is there a feature I’m not aware of?

Steps to reproduce

The video file must also be in the folder.

smoke video link: smoke.mp4 - Google Drivesmoke video link: https://drive.google.com/file/d/1ncI67cgjRGoQZHF6I0dEpXwvFwCKxFPK/view

Code snippet:

```<code>import streamlit as st

# Page config
st.set_page_config(
        page_title= "Multipage App",
        page_icon="")

# Customization for sidebar
st.markdown('<style>div[class="css-6qob1r e1fqkh3o3"] { background: url("https://media2.giphy.com/media/46hpy8xB3MiHfruixn/giphy.gif");background-repeat: no-repeat;background-size:350%;border:1px solid #36454F; border-top:none;} </style>', unsafe_allow_html=True)

# Hiding the Footer
hide_st_style =" <style>footer {visibility: hidden;}</style>"
st.markdown(hide_st_style, unsafe_allow_html=True)

st.markdown("""
  <style>
      ul[class="css-uc76bn e1fqkh3o9"]{
        position: relative;
        position: relative;
        padding-top: 3rem;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: left;
      }

      .css-17lntkn {
        font-weight: bold;
        font-size: 24px;
        color: yellow;
        font-family: arial;
        border:black;
      }

      .css-pkbazv {
        font-weight: bold;
        font-size: 24px;
        color: yellow;
        font-family: arial;
      }
  </style>""", unsafe_allow_html=True)

st.markdown("""
<body>
<section>
<video src="smoke.mp4" autoplay muted></video>

<h1>
<span>W</span>
<span>E</span>
<span>L</span>
<span>C</span>
<span>O</span>
<span>M</span>
<span>E</span>
</h1>
</section>

<style>

body
  {
  margin: 0;
  padding: 0;
  background:black;
  }

section
  {
  height:100vh;
  background:#000;

  }

video
  {
  object-fit:cover;
  }

h1
 {
 margin:0;
 padding:0;
 position:absolute;
 top:50%;
 transform: translateY(-50%);
 width:100%;
 text-align:center;
 color:#ddd;
 font-size:5em;
 font-family:sans-serif;
 letter-spacing:0.2em;

 }

h1 span
 {
 display:inline-block;
 animation: animate 1s linear forwards;

 }

@keyframes animate
 {

 0%
 {
  opacity:0;
  transform: rotateY(90deg);
  filter:blur(10px);
 }

100%
 {
  opacity:1;
   transform: rotateY(0deg);
   filter:blur(0px);
 }

 }

h1 span:nth-child(1)
{

 animation-delay: 1s;

}

h1 span:nth-child(2)
{

 animation-delay: 1.5s;

}

h1 span:nth-child(3)
{

 animation-delay: 2s;

}

h1 span:nth-child(4)
{

 animation-delay: 2.5s;

}

h1 span:nth-child(5)
{

 animation-delay: 3s;

}

h1 span:nth-child(6)
{

 animation-delay: 3.75s;

}

h1 span:nth-child(7)
{

 animation-delay: 4s;

}

</style>

</body>

<script>
document
  .querySelector('video')
  .addEventListener('ended', function(e) {
    e.target.style.display = 'none';
  });

</script>
</html>""",unsafe_allow_html=True)

</code>```

Expected behavior:

It is expected to behave the same as HTML and CSS

Debug info

Streamlit version: v15.2.0

Python version: v3.8

OS version: Windows 10

Browser version: Chrome 108.0.5359.99

Body:
Summary

While there is a video effect in the HTML and CSS files, this effect does not work when the same code is run in the streamlit.

I’ve had this problem before. Is this a general problem or is there a feature I’m not aware of?

Steps to reproduce

The video file must also be in the folder.

smoke video link: smoke.mp4 - Google Drivesmoke video link: https://drive.google.com/file/d/1ncI67cgjRGoQZHF6I0dEpXwvFwCKxFPK/view

Code snippet:

import streamlit as st

# Page config
st.set_page_config(
        page_title= "Multipage App",
        page_icon="")

# Customization for sidebar
st.markdown('', unsafe_allow_html=True)

# Hiding the Footer
hide_st_style =" "
st.markdown(hide_st_style, unsafe_allow_html=True)

st.markdown("""
  """, unsafe_allow_html=True)

st.markdown("""

<video src="smoke.mp4" autoplay muted></video>

W
E
L
C
O
M
E

""",unsafe_allow_html=True)

Expected behavior:

It is expected to behave the same as HTML and CSS

Debug info

Streamlit version: v15.2.0

Python version: v3.8

OS version: Windows 10

Browser version: Chrome 108.0.5359.99


问:
useSWRMutation post request optimisticData gives me a type error
i have a POST request using SWR:

```<code>  const { trigger, data, error, isMutating } = useSWRMutation(`${baseUrl}radios`, sendRequest);

  const onSubmit: SubmitHandler<FormData> = data => {
    trigger(data, {
      rollbackOnError: true,
      optimisticData: current => ({ ...current, data }),
    });
  };
</code>```

optimistiData gets red underlined on my IDE with the following problem:

(property) optimisticData?: Response | ((currentData?: Response | undefined) => Response) | undefined
Type '(current: Response | undefined) => { data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; ... 10 more ...; text?: (() => Promise<...>) | undefined; }' is not assignable to type 'Response | ((currentData?: Response | undefined) => Response) | undefined'.
Type '(current: Response | undefined) => { data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; ... 10 more ...; text?: (() => Promise<...>) | undefined; }' is not assignable to type '(currentData?: Response | undefined) => Response'.
Call signature return types '{ data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; statusText?: string | undefined; ... 9 more ...; text?: (() => Promise<...>) | undefined; }' and 'Response' are incompatible.
The types of 'headers' are incompatible between these types.
Type 'Headers | undefined' is not assignable to type 'Headers'.
Type 'undefined' is not assignable to type 'Headers'.ts(2322)

i don't understand which headers it's referring to

Body:
i have a POST request using SWR:

  const { trigger, data, error, isMutating } = useSWRMutation(`${baseUrl}radios`, sendRequest);

  const onSubmit: SubmitHandler<FormData> = data => {
    trigger(data, {
      rollbackOnError: true,
      optimisticData: current => ({ ...current, data }),
    });
  };

optimistiData gets red underlined on my IDE with the following problem:

(property) optimisticData?: Response | ((currentData?: Response | undefined) => Response) | undefined
Type '(current: Response | undefined) => { data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; ... 10 more ...; text?: (() => Promise<...>) | undefined; }' is not assignable to type 'Response | ((currentData?: Response | undefined) => Response) | undefined'.
Type '(current: Response | undefined) => { data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; ... 10 more ...; text?: (() => Promise<...>) | undefined; }' is not assignable to type '(currentData?: Response | undefined) => Response'.
Call signature return types '{ data: FormData; headers?: Headers | undefined; ok?: boolean | undefined; redirected?: boolean | undefined; status?: number | undefined; statusText?: string | undefined; ... 9 more ...; text?: (() => Promise<...>) | undefined; }' and 'Response' are incompatible.
The types of 'headers' are incompatible between these types.
Type 'Headers | undefined' is not assignable to type 'Headers'.
Type 'undefined' is not assignable to type 'Headers'.ts(2322)

i don't understand which headers it's referring to


问:
codeMirror in angular with handlebars mode not working
I want to run the example https://stackblitz.com/edit/ngx-codemirror?file=src%2Fapp%2Fapp.component.ts with handlebars mode https://codemirror.net/5/mode/handlebars/ but it does not seems to be working.
Any help would be appritiated.

I tried

```<code>    mode: 'text/x-handlebars-template',

</code>```

but no luck

Body:
I want to run the example https://stackblitz.com/edit/ngx-codemirror?file=src%2Fapp%2Fapp.component.ts with handlebars mode https://codemirror.net/5/mode/handlebars/ but it does not seems to be working.
Any help would be appritiated.

I tried

    mode: 'text/x-handlebars-template',

but no luck


问:
ASP.NET - Deleting IdentityUser throw SqliteException
I am using scaffolded DeletePersonalData, and when trying to delete user, the program throw exception:

```<code>SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.
Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(int rc, sqlite3 db)
</code>```

Code

```<code>public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);
            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "Incorrect password.");
                    return Page();
                }
            }

            var result = await _userManager.DeleteAsync(user); // This throw exception
            var userId = await _userManager.GetUserIdAsync(user);
            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Unexpected error occurred deleting user.");
            }

            await _signInManager.SignOutAsync();

            _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

            return Redirect("~/");
        }
</code>```

Call stack:

```<code>Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList<IUpdateEntry> entriesToSave, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.DeleteAsync(TUser user, CancellationToken cancellationToken)
WebApp.Areas.Identity.Pages.Account.Manage.DeletePersonalDataModel.OnPostAsync() in DeletePersonalData.cshtml.cs
</code>```

This is code created by VisualStudio, and I assume this should work but somehow, it does not. What am I doing wrong?

Body:
I am using scaffolded DeletePersonalData, and when trying to delete user, the program throw exception:

SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.
Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(int rc, sqlite3 db)

Code

public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);
            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "Incorrect password.");
                    return Page();
                }
            }

            var result = await _userManager.DeleteAsync(user); // This throw exception
            var userId = await _userManager.GetUserIdAsync(user);
            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Unexpected error occurred deleting user.");
            }

            await _signInManager.SignOutAsync();

            _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

            return Redirect("~/");
        }

Call stack:

Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable<ModificationCommandBatch> commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList<IUpdateEntry> entriesToSave, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.DeleteAsync(TUser user, CancellationToken cancellationToken)
WebApp.Areas.Identity.Pages.Account.Manage.DeletePersonalDataModel.OnPostAsync() in DeletePersonalData.cshtml.cs

This is code created by VisualStudio, and I assume this should work but somehow, it does not. What am I doing wrong?


问:
Only allow a function to be re-executable after it has already been executed (jquery)
If you go to the JSFiddle, and click "About" and then "Contact" in rapid succession, the drop-down options (which appear to the right of the parents) appear appended to each other although only one parent is selected - this is not desired. I'm trying to only allow a new selection to be made once the appear/disappear animation has been completed, avoiding any appending of the children's content.

```<code>$(function() {

  function animate(e) {
    e.stopPropagation();
    var $detected = $(this).closest('.nav-ul');
    $detected.find('li.detected').removeClass('detected');
    $(this).addClass('detected');

    //figure out which rel to show
    var ulToShow = $(this).attr('rel');

    //hide current rel
    if ($('.substitute .sub-child.active').length > 0) {
    console.log("A");
      $('.substitute .sub-child.active').hide(700, function() {
        $(this).removeClass('active');
        $('#' + ulToShow).fadeIn(528, function() {
          $(this).addClass('active');
          //$('#nav .nav-ul li').on('click', animate)

        });
      });
    } else {
    console.log("B");
      $('#' + ulToShow).fadeIn(528, function() {
        $(this).addClass('active');
        //$('#nav .nav-ul li').on('click', animate)
      });
    }
  }

  $('#nav .nav-ul li').on('click', animate);

  // close menu when clicking anywhere on the page
  $(document).on("click", function() {
    $("#nav li.detected").removeClass("detected");
    $("#nav div.active").hide(700, function() { $(this).removeClass("active"); });
  });
});
</code>```

I tried adding this code after the opening of the function, but it only gave me the alert.

```<code>$('#nav .nav-ul li').click(function(){
    var $this = $(this);
    if(!$this.data('disabled')){
        $this.data('disabled', true);
        alert('next click enable  only in 5 seconds');

        setTimeout(function(){
            $this.data('disabled', false);
        }, 5000);
    }
});
</code>```

Body:
If you go to the JSFiddle, and click "About" and then "Contact" in rapid succession, the drop-down options (which appear to the right of the parents) appear appended to each other although only one parent is selected - this is not desired. I'm trying to only allow a new selection to be made once the appear/disappear animation has been completed, avoiding any appending of the children's content.

$(function() {

  function animate(e) {
    e.stopPropagation();
    var $detected = $(this).closest('.nav-ul');
    $detected.find('li.detected').removeClass('detected');
    $(this).addClass('detected');

    //figure out which rel to show
    var ulToShow = $(this).attr('rel');

    //hide current rel
    if ($('.substitute .sub-child.active').length > 0) {
    console.log("A");
      $('.substitute .sub-child.active').hide(700, function() {
        $(this).removeClass('active');
        $('#' + ulToShow).fadeIn(528, function() {
          $(this).addClass('active');
          //$('#nav .nav-ul li').on('click', animate)

        });
      });
    } else {
    console.log("B");
      $('#' + ulToShow).fadeIn(528, function() {
        $(this).addClass('active');
        //$('#nav .nav-ul li').on('click', animate)
      });
    }
  }

  $('#nav .nav-ul li').on('click', animate);

  // close menu when clicking anywhere on the page
  $(document).on("click", function() {
    $("#nav li.detected").removeClass("detected");
    $("#nav div.active").hide(700, function() { $(this).removeClass("active"); });
  });
});

I tried adding this code after the opening of the function, but it only gave me the alert.

$('#nav .nav-ul li').click(function(){
    var $this = $(this);
    if(!$this.data('disabled')){
        $this.data('disabled', true);
        alert('next click enable  only in 5 seconds');

        setTimeout(function(){
            $this.data('disabled', false);
        }, 5000);
    }
});


问:
How to combine webpack-license-plugin with create-react-app?
For my React-website, I need to document all the packages I am using.
For this, I want to use webpack-license-plugin (https://www.npmjs.com/package/webpack-license-plugin)
However, I recently switched to using "create-react-app" which means there is no config-file I can directly modify.
I tried to follow this answer (create react app Configuration file after build app) which tells me to create a config-file, use the plugin there and load it in my index.html-file.

I would have expected when running the build somehow the inside config-file by me specified output-file would appear inside the build-folder, BUT there is nothing.

I did not find any other guidance, other than this question (Customize webpack plugins using create-react-app). However, I would like to avoid making use of new tools, if possible.
Generally, I just wonder about the simplest way how to achieve what I set out to do. Thanks for any help!

Here is the content of the extra config-file I added to my public folder (beside the index.html):

```<code>const LicensePlugin = require("webpack-license-plugin")

module.exports = {
  plugins: [
    // there might be other plugins here
    new LicensePlugin({ outputFilename: "thirdPartyNotice.json" })
  ]
}
</code>```

And here is the content of my index.html:

```<code><html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>Document</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Cardo&display=swap" rel="stylesheet" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>
    <div id="root"></div>
  </body>
</html>```
```

Body:
For my React-website, I need to document all the packages I am using.
For this, I want to use webpack-license-plugin (https://www.npmjs.com/package/webpack-license-plugin)
However, I recently switched to using "create-react-app" which means there is no config-file I can directly modify.
I tried to follow this answer (create react app Configuration file after build app) which tells me to create a config-file, use the plugin there and load it in my index.html-file.

I would have expected when running the build somehow the inside config-file by me specified output-file would appear inside the build-folder, BUT there is nothing.

I did not find any other guidance, other than this question (Customize webpack plugins using create-react-app). However, I would like to avoid making use of new tools, if possible.
Generally, I just wonder about the simplest way how to achieve what I set out to do. Thanks for any help!

Here is the content of the extra config-file I added to my public folder (beside the index.html):

const LicensePlugin = require("webpack-license-plugin")

module.exports = {
  plugins: [
    // there might be other plugins here
    new LicensePlugin({ outputFilename: "thirdPartyNotice.json" })
  ]
}

And here is the content of my index.html:

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>Document</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Cardo&display=swap" rel="stylesheet" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

    You need to enable JavaScript to run this app.

```


问:
TERRAFORM (0.12) - Nested For-In or other technique to augment an object in a map
I have a map that looks like this:

```<code>stuff = {
  object-1 = {
    id                    = "1"
    main_value            = "blue"
    additional_in_values  = ["red"]
    additional_out_values = ["green"]
    more_values           = "foo"
  },
  object-2 = {
    id                    = "2"
    main_value            = "green"
    additional_in_values  = ["blue"]
    additional_out_values = ["red"]
    more_values           = "fee"
  },
  object-3 = {
    id                    = "3"
    main_value            = "red"
    additional_in_values  = ["green"]
    additional_out_values = ["blue"]
    more_values           = "fie"
  }
}
</code>```

The essence of the challenge is to be able to freely iterate over an object in a map and selectively add, remove and modify attributes of the object without having to explicitly enumerate them.

The specific use case is to augment each object by either inserting the "main_value" into "additional_in_values" and "additional_out_values", or much better, combining the main_value with "additional_in_values" and "additional_out_values" to form two new pairs called "inbound_all" and "outbound_all".  There are additional use cases that involve inserting new key-value pairs in the object or dropping named key-value pairs (for example additional_out could be dropped if we had "outbound_all").

A successful result would look like:

```<code>transformed-stuff = {
  object-1 = {
    id                    = "1"
    main_value            = "blue"
    additional_in_values  = ["red"]
    additional_out_values = ["green"]
    inbound_all           = ["blue", "red"]   # concat main_value and additional_in_values
    outbound_all          = ["blue", "green"] # concat main_value and additional_out_values
    more_values           = "foo"
  },
  object-2 = {
    id                    = "2"
    main_value            = "green"
    additional_in_values  = ["blue"]
    additional_out_values = ["red"]
    inbound_all           = ["green", "blue"]
    outbound_all          = ["green", "red"]
    more_values           = "fee"
  },
  object-3 = {
    id                    = "3"
    main_value            = "red"
    additional_in_values  = ["green"]
    additional_out_values = ["blue"]
    inbound_all           = ["red", "green"]
    outbound_all          = ["red", "blue"]
    more_values           = "fie"
  }
}
</code>```

The key constraint is to do these insert or concatenate operations in a way that preserves the existing object attributes without explicitly naming each attribute.  Naming each attribute would work fine but would be unmaintainable as each of the objects actually has many more attributes than shown, and the attributes come and go, so a solution that explicitly enumerates won't do, per the "unmaintainable" transform in the sample code below.

It seems like it should be possible in the loop to implement logic like:

```<code>(pseudocode)
maintainable = for stuff_key, stuff_details in var.stuff :
 stuff_key => {
    stuff_detail # just insert the existing detail item in the new detail
    inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values) # insert a new element
 }
</code>```

Or even a solution that selectively drops an element of a given value

Any ideas?  I'd think a nested for..in loop should work but my own experiments are failing.  If it were possible the inner for..in would iterate over stuff_details and selectively act on each existing item, as well as inserting the new items after

Code is:

```<code>variable "stuff" {
  type = map(object({
    id                    = string
    main_value            = string
    additional_in_values  = list(string)
    additional_out_values = list(string)
    more_values           = string
  }))
}

locals {
  unmaintainable = {
    for stuff_key, stuff_details in var.stuff :
      stuff_key => {
        id = stuff_details.id
        main_value = stuff_details.main_value
        additional_out_values = stuff_details.additional_out_values
        additional_in_values = stuff_details.additional_in_values
        more_values = stuff_details.more_values
        inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values)
        outbound_all    = concat([stuff_details.main_value], stuff_details.additional_out_values)
      }
   }

  transformed-stuff = {
    for stuff_key, stuff_details in var.stuff :
    stuff_key => {
      inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values)
      outbound_all    = concat([stuff_details.main_value], stuff_details.additional_out_values)
    }
  }
}

output "stuff" {
  value = var.stuff
}

output "unmaintainable" {
    value = local.unmaintainable
}

output "transformed-stuff" {
  value = local.transformed-stuff
}
</code>```

The original value is at the top of the post and can be placed in terraform.tfvars

The not-satisfactory output of the code in its current state is:

```<code>Outputs:

stuff = {
  "object-1" = {
    "additional_in_values" = [
      "red",
    ]
    "additional_out_values" = [
      "green",
    ]
    "id" = "1"
    "main_value" = "blue"
    "more_values" = "foo"
  }
  "object-2" = {
    "additional_in_values" = [
      "blue",
    ]
    "additional_out_values" = [
      "red",
    ]
    "id" = "2"
    "main_value" = "green"
    "more_values" = "foo"
  }
  "object-3" = {
    "additional_in_values" = [
      "green",
    ]
    "additional_out_values" = [
      "blue",
    ]
    "id" = "3"
    "main_value" = "red"
    "more_values" = "foo"
  }
}
transformed-stuff = {
  "object-1" = {
    "inbound_all" = [
      "blue",
      "red",
    ]
    "outbound_all" = [
      "blue",
      "green",
    ]
  }
  "object-2" = {
    "inbound_all" = [
      "green",
      "blue",
    ]
    "outbound_all" = [
      "green",
      "red",
    ]
  }
  "object-3" = {
    "inbound_all" = [
      "red",
      "green",
    ]
    "outbound_all" = [
      "red",
      "blue",
    ]
  }
}
unmaintainable = {
  "object-1" = {
    "additional_in_values" = [
      "red",
    ]
    "additional_out_values" = [
      "green",
    ]
    "id" = "1"
    "inbound_all" = [
      "blue",
      "red",
    ]
    "main_value" = "blue"
    "more_values" = "foo"
    "outbound_all" = [
      "blue",
      "green",
    ]
  }
  "object-2" = {
    "additional_in_values" = [
      "blue",
    ]
    "additional_out_values" = [
      "red",
    ]
    "id" = "2"
    "inbound_all" = [
      "green",
      "blue",
    ]
    "main_value" = "green"
    "more_values" = "foo"
    "outbound_all" = [
      "green",
      "red",
    ]
  }
  "object-3" = {
    "additional_in_values" = [
      "green",
    ]
    "additional_out_values" = [
      "blue",
    ]
    "id" = "3"
    "inbound_all" = [
      "red",
      "green",
    ]
    "main_value" = "red"
    "more_values" = "fee"
    "outbound_all" = [
      "red",
      "blue",
    ]
  }
}
</code>```

Body:
I have a map that looks like this:

stuff = {
  object-1 = {
    id                    = "1"
    main_value            = "blue"
    additional_in_values  = ["red"]
    additional_out_values = ["green"]
    more_values           = "foo"
  },
  object-2 = {
    id                    = "2"
    main_value            = "green"
    additional_in_values  = ["blue"]
    additional_out_values = ["red"]
    more_values           = "fee"
  },
  object-3 = {
    id                    = "3"
    main_value            = "red"
    additional_in_values  = ["green"]
    additional_out_values = ["blue"]
    more_values           = "fie"
  }
}

The essence of the challenge is to be able to freely iterate over an object in a map and selectively add, remove and modify attributes of the object without having to explicitly enumerate them.

The specific use case is to augment each object by either inserting the "main_value" into "additional_in_values" and "additional_out_values", or much better, combining the main_value with "additional_in_values" and "additional_out_values" to form two new pairs called "inbound_all" and "outbound_all".  There are additional use cases that involve inserting new key-value pairs in the object or dropping named key-value pairs (for example additional_out could be dropped if we had "outbound_all").

A successful result would look like:

transformed-stuff = {
  object-1 = {
    id                    = "1"
    main_value            = "blue"
    additional_in_values  = ["red"]
    additional_out_values = ["green"]
    inbound_all           = ["blue", "red"]   # concat main_value and additional_in_values
    outbound_all          = ["blue", "green"] # concat main_value and additional_out_values
    more_values           = "foo"
  },
  object-2 = {
    id                    = "2"
    main_value            = "green"
    additional_in_values  = ["blue"]
    additional_out_values = ["red"]
    inbound_all           = ["green", "blue"]
    outbound_all          = ["green", "red"]
    more_values           = "fee"
  },
  object-3 = {
    id                    = "3"
    main_value            = "red"
    additional_in_values  = ["green"]
    additional_out_values = ["blue"]
    inbound_all           = ["red", "green"]
    outbound_all          = ["red", "blue"]
    more_values           = "fie"
  }
}

The key constraint is to do these insert or concatenate operations in a way that preserves the existing object attributes without explicitly naming each attribute.  Naming each attribute would work fine but would be unmaintainable as each of the objects actually has many more attributes than shown, and the attributes come and go, so a solution that explicitly enumerates won't do, per the "unmaintainable" transform in the sample code below.

It seems like it should be possible in the loop to implement logic like:

(pseudocode)
maintainable = for stuff_key, stuff_details in var.stuff :
 stuff_key => {
    stuff_detail # just insert the existing detail item in the new detail
    inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values) # insert a new element
 }

Or even a solution that selectively drops an element of a given value

Any ideas?  I'd think a nested for..in loop should work but my own experiments are failing.  If it were possible the inner for..in would iterate over stuff_details and selectively act on each existing item, as well as inserting the new items after

Code is:

variable "stuff" {
  type = map(object({
    id                    = string
    main_value            = string
    additional_in_values  = list(string)
    additional_out_values = list(string)
    more_values           = string
  }))
}

locals {
  unmaintainable = {
    for stuff_key, stuff_details in var.stuff :
      stuff_key => {
        id = stuff_details.id
        main_value = stuff_details.main_value
        additional_out_values = stuff_details.additional_out_values
        additional_in_values = stuff_details.additional_in_values
        more_values = stuff_details.more_values
        inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values)
        outbound_all    = concat([stuff_details.main_value], stuff_details.additional_out_values)
      }
   }

  transformed-stuff = {
    for stuff_key, stuff_details in var.stuff :
    stuff_key => {
      inbound_all     = concat([stuff_details.main_value], stuff_details.additional_in_values)
      outbound_all    = concat([stuff_details.main_value], stuff_details.additional_out_values)
    }
  }
}

output "stuff" {
  value = var.stuff
}

output "unmaintainable" {
    value = local.unmaintainable
}

output "transformed-stuff" {
  value = local.transformed-stuff
}

The original value is at the top of the post and can be placed in terraform.tfvars

The not-satisfactory output of the code in its current state is:

Outputs:

stuff = {
  "object-1" = {
    "additional_in_values" = [
      "red",
    ]
    "additional_out_values" = [
      "green",
    ]
    "id" = "1"
    "main_value" = "blue"
    "more_values" = "foo"
  }
  "object-2" = {
    "additional_in_values" = [
      "blue",
    ]
    "additional_out_values" = [
      "red",
    ]
    "id" = "2"
    "main_value" = "green"
    "more_values" = "foo"
  }
  "object-3" = {
    "additional_in_values" = [
      "green",
    ]
    "additional_out_values" = [
      "blue",
    ]
    "id" = "3"
    "main_value" = "red"
    "more_values" = "foo"
  }
}
transformed-stuff = {
  "object-1" = {
    "inbound_all" = [
      "blue",
      "red",
    ]
    "outbound_all" = [
      "blue",
      "green",
    ]
  }
  "object-2" = {
    "inbound_all" = [
      "green",
      "blue",
    ]
    "outbound_all" = [
      "green",
      "red",
    ]
  }
  "object-3" = {
    "inbound_all" = [
      "red",
      "green",
    ]
    "outbound_all" = [
      "red",
      "blue",
    ]
  }
}
unmaintainable = {
  "object-1" = {
    "additional_in_values" = [
      "red",
    ]
    "additional_out_values" = [
      "green",
    ]
    "id" = "1"
    "inbound_all" = [
      "blue",
      "red",
    ]
    "main_value" = "blue"
    "more_values" = "foo"
    "outbound_all" = [
      "blue",
      "green",
    ]
  }
  "object-2" = {
    "additional_in_values" = [
      "blue",
    ]
    "additional_out_values" = [
      "red",
    ]
    "id" = "2"
    "inbound_all" = [
      "green",
      "blue",
    ]
    "main_value" = "green"
    "more_values" = "foo"
    "outbound_all" = [
      "green",
      "red",
    ]
  }
  "object-3" = {
    "additional_in_values" = [
      "green",
    ]
    "additional_out_values" = [
      "blue",
    ]
    "id" = "3"
    "inbound_all" = [
      "red",
      "green",
    ]
    "main_value" = "red"
    "more_values" = "fee"
    "outbound_all" = [
      "red",
      "blue",
    ]
  }
}


问:
Throwing Errors or Returning JSON When Registering User in ExpressJS Node
I am implementing a JSON API in Node ExpressJS and wondering if the best practice is to throw errors or return JSON to the caller indicating that something bad has happened.

This is my current implementation. If the username is already registered, I simply return back a message to the user. Should I be throwing an error instead etc?

```<code>const register = async (req, res) => {

    const { username, password } = req.body

    if (username.length == 0 || password.length == 0) {
        // SHOULD I THROW AN ERROR
        res.json({ success: false, message: 'Username or password is missing.' })
        return
    }

    // check username is already registered
    const existingUser = await models.User.findOne({
        where: {
            username: username
        }
    })

    if (existingUser) {
        // SHOULD I THROW AN ERROR
        res.json({ success: false, message: 'Username already exists.' })
        return
    }
</code>```

Body:
I am implementing a JSON API in Node ExpressJS and wondering if the best practice is to throw errors or return JSON to the caller indicating that something bad has happened.

This is my current implementation. If the username is already registered, I simply return back a message to the user. Should I be throwing an error instead etc?

const register = async (req, res) => {

    const { username, password } = req.body

    if (username.length == 0 || password.length == 0) {
        // SHOULD I THROW AN ERROR
        res.json({ success: false, message: 'Username or password is missing.' })
        return
    }

    // check username is already registered
    const existingUser = await models.User.findOne({
        where: {
            username: username
        }
    })

    if (existingUser) {
        // SHOULD I THROW AN ERROR
        res.json({ success: false, message: 'Username already exists.' })
        return
    }


问:
How to make buttons functionable with music player in Python
I'm making a music player using pygame and tkinter, I'm done with the UI, I just don't know how I would import the songs and make them play/pause/skip based on the buttons I made. I haven't tried anything because I don't know how I would go about it, if anyone knows and can help me out it'd be great! Thanks!

from tkinter import *
import tkinter.font as font
from tkinter import filedialog
from pygame import mixer
## importing required tkinter libraries

def Play():
    print("Play")

root = Tk()
root.title="MP3 Music Player"
mixer.init()

##listbox where your songs will be loaded into
songs_list = Listbox(root,selectmode=SINGLE,bg="black",fg="white",font=('arial',15),height=12,width=47,selectbackground="gray",selectforeground="black")
songs_list.grid(columnspan=9)

#set new default font
default_font = font.Font(family="Helvetica")

##play button
play_button = Button(root,text="Play",width=7,command=Play) ##initialise/create each button with its specified properties
play_button['font'] = default_font ## change font of each button
play_button.grid(row=1,column=0) ## sets position of where button is to be located for each button

##pause button
pause_button = Button(root, text="Pause",width = 7, command=Play)
pause_button['font'] = default_font
pause_button.grid(row=1,column=1)

## stop button
stop_button = Button(root,text="Stop",width=7,command=Play)
stop_button['font'] = default_font
stop_button.grid(row=1,column=2)

## resume button
resume_button = Button(root,text="Resume",width=7,command=Play)
resume_button['font'] = default_font
resume_button.grid(row=1,column=3)

##previous button
previous_button = Button(root,text="Prev",width=7,command=Play)
previous_button['font'] = default_font
previous_button.grid(row=1,column=4)

## next button
next_button = Button(root,text="Next",width=7,command=Play)
next_button['font'] = default_font
next_button.grid(row=1,column=5)

##create menu option
menu = Menu(root)
root.config(menu=menu)
add_song_menu = Menu(menu)
menu.add_cascade(label="Menu",menu=add_song_menu)
add_song_menu.add_command(label="Add songs",command=Play)
add_song_menu.add_command(label="Delete song",command=Play)

```


问:
why wont my robot continue clicking the keys i specify?
currently ive taken up a small project of mine when i was bored but have come into a small problem i am struggling to solve, recently ive started to get back into pokemon and have really enjoyed my time with it. but after catching my first shiny( a rare pokemon with inverted colors) i wanted to catch more, but not sit at my computer endlessly going through encounters so i wanted to create a script to do that for me. as seen below

`

```<code>import java.awt.Color;
import java.awt.Robot;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class App {
    public static void main(String[] args) throws Exception {

         JFrame f = new JFrame();
         String name=JOptionPane.showInputDialog(f,"Enter Name");

    if (name.equals("go")){
        Redo();
    }
    }

   public static void Redo()throws Exception {
        Robot robot = new Robot();

       robot.delay(5000);
             robot.keyPress(10);
           robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);

            check();

    }

   public static void check() throws Exception{
        Robot robot2 = new Robot();
        Color color2 = new Color(255,255,185);
        Color color = robot2.getPixelColor(1080, 446);

        if ( color.equals(color2)==true){
           // System.out.println("shiny found!");
            System.exit(0);
        }
        else{
            robot2.keyPress(123);
           // System.out.println("no shiny ");
            Redo();
        }

   }
}
</code>```

`

what supposed to happen:in the script above a dialogue box pops up where i have to type "go" at that point i manually click into the game window,at which point a robot clicks to go though the different menu's(just the enter key) until it gets to normal play state, then it enters a battle with a pokemon at that point my check() asks another robot to check the screen coordinates for a color( this color is the color of the shiny) if they are both the same color the program ends if not it restarts ( pokemon games reset upon clicking F12) and ive tested this in the normal IDE environment( where i put the color of the shiny in the right screen coordinate) and everything seemed to work

what actually  happened: when i actually try the game itself  the game  only registers the enter button once or maybe my robot only clicks once? im not too sure at with point after 15 or so seconds the robot clicks f12 since it cant find the shiny. and the program repeats, i am using a Jar. not sure if that could be the problem?

so my question is: is there any reason my robot would stop pressing the buttons? or could it be the game not registering them?

Any help is appreciated!

Body:
currently ive taken up a small project of mine when i was bored but have come into a small problem i am struggling to solve, recently ive started to get back into pokemon and have really enjoyed my time with it. but after catching my first shiny( a rare pokemon with inverted colors) i wanted to catch more, but not sit at my computer endlessly going through encounters so i wanted to create a script to do that for me. as seen below

`

import java.awt.Color;
import java.awt.Robot;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class App {
    public static void main(String[] args) throws Exception {

         JFrame f = new JFrame();
         String name=JOptionPane.showInputDialog(f,"Enter Name");

    if (name.equals("go")){
        Redo();
    }
    }

   public static void Redo()throws Exception {
        Robot robot = new Robot();

       robot.delay(5000);
             robot.keyPress(10);
           robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);
            robot.delay(3000);
            robot.keyPress(10);

            check();

    }

   public static void check() throws Exception{
        Robot robot2 = new Robot();
        Color color2 = new Color(255,255,185);
        Color color = robot2.getPixelColor(1080, 446);

        if ( color.equals(color2)==true){
           // System.out.println("shiny found!");
            System.exit(0);
        }
        else{
            robot2.keyPress(123);
           // System.out.println("no shiny ");
            Redo();
        }

   }
}

`

what supposed to happen:in the script above a dialogue box pops up where i have to type "go" at that point i manually click into the game window,at which point a robot clicks to go though the different menu's(just the enter key) until it gets to normal play state, then it enters a battle with a pokemon at that point my check() asks another robot to check the screen coordinates for a color( this color is the color of the shiny) if they are both the same color the program ends if not it restarts ( pokemon games reset upon clicking F12) and ive tested this in the normal IDE environment( where i put the color of the shiny in the right screen coordinate) and everything seemed to work

what actually  happened: when i actually try the game itself  the game  only registers the enter button once or maybe my robot only clicks once? im not too sure at with point after 15 or so seconds the robot clicks f12 since it cant find the shiny. and the program repeats, i am using a Jar. not sure if that could be the problem?

so my question is: is there any reason my robot would stop pressing the buttons? or could it be the game not registering them?

Any help is appreciated!


问:
Two-variable function of an integral
Good evening,

I am trying to compute a matrix in Matlab whose elements are given by:

K(n,m) = int_{-inf}^{+inf} dx int_{-inf}^{+inf} dy f(n,m,x,y),

with f being the elements of an (x,y)-dependent matrix whose form I already know.

I have tried different methods for this:

Computing directly the matrix F with elements f and then two univariate integrals (function integral) with the corresponding 'ArrayValued' options.

Computing directly the matrix F with elements f and then the double integral (function integral2).

Trying to compute the elements of K with two consecutive univariate integrals (again, with integral).

Computing the elements of K with a double integral (again, with integral2).

None of this seems to be working, so I was wondering if anyone could provide a different approach.

Cheers

Title: Two-variable function of an integral


问:
django-storages, on file upload: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden
My bucket policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowUserWrite",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted_userid:user/myuser"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::mybucket-dev",
                "arn:aws:s3:::mybucket-dev/*"
            ]
        }
    ]
}
</code>```

Anyone have any idea why this is not working when I try to upload a file to the bucket?

Body:
My bucket policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowUserWrite",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted_userid:user/myuser"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::mybucket-dev",
                "arn:aws:s3:::mybucket-dev/*"
            ]
        }
    ]
}

Anyone have any idea why this is not working when I try to upload a file to the bucket?


问:
jade view is return nothing on prod but working fine in local
am trying to render simple jade template with 2 inputs and a button to reset user password
in local it is working perfectly fine but in prod it is reading it as if it is get without view and only showing the json response

reset.jade

```<code>doctype html
html
 head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
 body
    form(method='POST')
        legend Reset Password
        .form-group
            label(for='password') New Password
            input.form-control(type='password', name='password', value='', placeholder='New password', autofocus=true)
        .form-group
            label(for='confirm') Confirm Password
            input.form-control(type='password', name='confirmPassword', value='', placeholder='Confirm password')
        .form-group
            button.btn.btn-primary(type='submit') Update Password
</code>```

server.js

```<code>const views = fileURLToPath(import.meta.url)
const __dirname = path.dirname(views)
app.set('views', path.join(__dirname, 'Views'))
app.set('view engine', 'jade')
</code>```

password.js

```<code>export const reset = async (req, res) => {
await User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: { $gt: Date.now() },
})
    .then((user) => {
        if (!user)
            return res.status(401).json({
                message: 'Password reset token is invalid or has expired.',
            })

        var options = { cache: true }
        res.compile('reset', options)

        //Redirect user to form with the email address
        res.renderFile('reset', { user })
    })
    .catch((err) => res.status(500).json({ message: 'a' }))
     }
</code>```

this will send email to user with the jade view and the reset password token

Body:
am trying to render simple jade template with 2 inputs and a button to reset user password
in local it is working perfectly fine but in prod it is reading it as if it is get without view and only showing the json response

reset.jade

doctype html
html
 head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
 body
    form(method='POST')
        legend Reset Password
        .form-group
            label(for='password') New Password
            input.form-control(type='password', name='password', value='', placeholder='New password', autofocus=true)
        .form-group
            label(for='confirm') Confirm Password
            input.form-control(type='password', name='confirmPassword', value='', placeholder='Confirm password')
        .form-group
            button.btn.btn-primary(type='submit') Update Password

server.js

const views = fileURLToPath(import.meta.url)
const __dirname = path.dirname(views)
app.set('views', path.join(__dirname, 'Views'))
app.set('view engine', 'jade')

password.js

export const reset = async (req, res) => {
await User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: { $gt: Date.now() },
})
    .then((user) => {
        if (!user)
            return res.status(401).json({
                message: 'Password reset token is invalid or has expired.',
            })

        var options = { cache: true }
        res.compile('reset', options)

        //Redirect user to form with the email address
        res.renderFile('reset', { user })
    })
    .catch((err) => res.status(500).json({ message: 'a' }))
     }

this will send email to user with the jade view and the reset password token


问:
Firebase remote config returning default value on android
I am using remote config in my react native project as following

```<code>   useEffect(() => {
        remoteConfig()
            .setDefaults({
                activation: 'project',
            })
            .then(() => remoteConfig().fetchAndActivate())
            .catch(error => {
                console.log(error)
            })
            .then(fetchedRemotely => {
                if (fetchedRemotely) {
                   console.log('Configs were retrieved from the backend and activated.');
                } else {
                    console.log('No configs were fetched from the backend, and the local configs were already activated',);
                }
            });
    }, []);

    var activation = remoteConfig().getValue('activation');
</code>```

When I call activation.asString() in a function when a button is clicked, I first get the default value, not the one published. When I press cmd + s in the editor, the project is saved and the the get refreshed, then I start getting the remote value. And this happens only on android. I am implementing this correctly?

Body:
I am using remote config in my react native project as following

   useEffect(() => {
        remoteConfig()
            .setDefaults({
                activation: 'project',
            })
            .then(() => remoteConfig().fetchAndActivate())
            .catch(error => {
                console.log(error)
            })
            .then(fetchedRemotely => {
                if (fetchedRemotely) {
                   console.log('Configs were retrieved from the backend and activated.');
                } else {
                    console.log('No configs were fetched from the backend, and the local configs were already activated',);
                }
            });
    }, []);

    var activation = remoteConfig().getValue('activation');

When I call activation.asString() in a function when a button is clicked, I first get the default value, not the one published. When I press cmd + s in the editor, the project is saved and the the get refreshed, then I start getting the remote value. And this happens only on android. I am implementing this correctly?


问:
Append values to Dataframe in loop and if conditions
Need help please.

I have a dataframe that reads rows from Excel and appends to Dataframe if certain columns exist.
I need to add an additional Dataframe if the columns don't exist in a sheet and append filename and sheetname and write all the file names and sheet names for those sheets to an excel file. Also I want the values to be unique.
I tried adding to dfErrorList but it only showed the last sheetname and filename and repeated itself many times in the output excel file

```<code>from xlsxwriter import Workbook
import pandas as pd
import openpyxl
import glob
import os

path = 'filestoimport/*.xlsx'

list_of_dfs = []
list_of_dferror = []
dfErrorList = pd.DataFrame() #create empty df
for filepath in glob.glob(path):
    xl = pd.ExcelFile(filepath)

    # Define an empty list to store individual DataFrames
    for sheet_name in xl.sheet_names:

        df = pd.read_excel(filepath, sheet_name=sheet_name)
        df['sheetname'] = sheet_name
        file_name = os.path.basename(filepath)
        df['sourcefilename'] = file_name
        if "Project ID" in df.columns and "Status" in df.columns:
          print('')

        *else:

         dfErrorList['sheetname'] = df['sheetname']  # adds `sheet_name` into the column
         dfErrorList['sourcefilename'] = df['sourcefilename']

         continue

        list_of_dferror.append((dfErrorList))

        df['Status'].fillna('', inplace=True)
        df['Added by'].fillna('', inplace=True)

        list_of_dfs.append(df)

    # # Combine all DataFrames into one
    data = pd.concat(list_of_dfs, ignore_index=True)
    dataErrors = pd.concat(list_of_dferror, ignore_index=True)
dataErrors.to_excel(r'error.xlsx', index=False)
# data.to_excel("total_countries.xlsx", index=None)
</code>```

Body:
Need help please.

I have a dataframe that reads rows from Excel and appends to Dataframe if certain columns exist.
I need to add an additional Dataframe if the columns don't exist in a sheet and append filename and sheetname and write all the file names and sheet names for those sheets to an excel file. Also I want the values to be unique.
I tried adding to dfErrorList but it only showed the last sheetname and filename and repeated itself many times in the output excel file

from xlsxwriter import Workbook
import pandas as pd
import openpyxl
import glob
import os

path = 'filestoimport/*.xlsx'

list_of_dfs = []
list_of_dferror = []
dfErrorList = pd.DataFrame() #create empty df
for filepath in glob.glob(path):
    xl = pd.ExcelFile(filepath)

    # Define an empty list to store individual DataFrames
    for sheet_name in xl.sheet_names:

        df = pd.read_excel(filepath, sheet_name=sheet_name)
        df['sheetname'] = sheet_name
        file_name = os.path.basename(filepath)
        df['sourcefilename'] = file_name
        if "Project ID" in df.columns and "Status" in df.columns:
          print('')

        *else:

         dfErrorList['sheetname'] = df['sheetname']  # adds `sheet_name` into the column
         dfErrorList['sourcefilename'] = df['sourcefilename']

         continue

        list_of_dferror.append((dfErrorList))

        df['Status'].fillna('', inplace=True)
        df['Added by'].fillna('', inplace=True)

        list_of_dfs.append(df)

    # # Combine all DataFrames into one
    data = pd.concat(list_of_dfs, ignore_index=True)
    dataErrors = pd.concat(list_of_dferror, ignore_index=True)
dataErrors.to_excel(r'error.xlsx', index=False)
# data.to_excel("total_countries.xlsx", index=None)


问:
Android Studio distorted background
I am setting my background using an image in the drawable folder but when the background is set the image is placed inside every radio group, textview, etc. How can I make it so it so the image is just placed as the layout background? I am using themes and setTheme() here is my themes.xml:</p>
```<code>    <style name="Theme.Christmas" parent="Theme.AppCompat.DayNight.NoActionBar">
    <item name="android:background">@drawable/christmas</item>
    <item name="android:textColor">@color/white</item>
    <item name="colorPrimary">@color/black</item>
    <item name="colorOnPrimary">@color/white</item>
</style>
</code>```

Title: Android Studio distorted background