问:
Case_when in mutate for weighted averages - creating unexpected NAs for some cases that meet a condition but working for all others
This is my first post! I have a dataset in long form where i have a column called "indicator" with 51 levels and then a column with numeric values and then a series of columns with identifying and weighting variables. I am using a long sequence of case_when conditions inside mutate to weight different levels of indicator by different other columns. The code is mostly working, but there are a few conditions where it is creating NAs for some of the levels of indicator that meet the condition, but not others. So this means it's not a problem in the line of the code, but something in the underlying data and I can't figure it out. I have tried separating out the distinct conditions into separate mutate functions but that didn't help. All help would be so much appreciated!

```<code>    # Weighted means # Grouping by indicator only - this is where I get errors
      df4 <- df3 %>%
      group_by(indicator) %>%
      mutate(globalmean = case_when(
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, beef", indicator)) ~ weighted.mean(value, prod_beef, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, cereals (excl rice)", indicator)) ~ weighted.mean(value, prod_cerealsnorice, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, chicken", indicator)) ~ weighted.mean(value, prod_chickenmeat, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, eggs", indicator)) ~ weighted.mean(value, prod_eggs, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, milk", indicator)) ~ weighted.mean(value, prod_cowmilk, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, pork", indicator)) ~ weighted.mean(value, prod_pork, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, rice", indicator)) ~ weighted.mean(value, prod_rice, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, cereals", indicator)) ~ weighted.mean(value, areaharvested_cereals, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, citrus", indicator)) ~ weighted.mean(value, areaharvested_citrus, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, fruit", indicator)) ~ weighted.mean(value, areaharvested_fruit, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, pulses", indicator)) ~ weighted.mean(value, areaharvested_pulses, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, roots and tubers", indicator)) ~ weighted.mean(value, areaharvested_roottuber, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, treenuts", indicator)) ~ weighted.mean(value, areaharvested_treenuts, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, vegetables", indicator)) ~ weighted.mean(value, areaharvested_vegetables, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, beef", indicator)) ~ weighted.mean(value, producinganimals_beef, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, chicken", indicator)) ~ weighted.mean(value, producinganimals_chickenmeat, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, milk", indicator)) ~ weighted.mean(value, producinganimals_cowmilk, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, eggs", indicator)) ~ weighted.mean(value, producinganimals_eggs, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, pork", indicator)) ~ weighted.mean(value, producinganimals_pork, na.rm = TRUE)),
        (grepl("pop_u", mean_weighting)  ~ weighted.mean(value, pop_u, na.rm = TRUE)),
        (grepl("GDP", mean_weighting)  ~ weighted.mean(value, GDP, na.rm = TRUE)), # one of two indicator levels meeting this condition works, the other results in NA
        (grepl("unweighted", mean_weighting) ~ mean(value, na.rm = TRUE)),
        (grepl("cropland", mean_weighting)  ~ weighted.mean(value, croplandcov, na.rm = TRUE)),
        (grepl("totalpop", mean_weighting) ~ weighted.mean(value, totalpop, na.rm = TRUE)), # Almost all of the indicator levels meeting this condition work, 3 result in NA
        (grepl("landarea", mean_weighting) ~ weighted.mean(value, landarea, na.rm = TRUE)),
        TRUE ~ mean(value)
        )
        ) %>%
## Tried this manual overwriting the NA indicator levels as a workaround but it doesn't fix the problem:
        mutate(globalmean = case_when(
          indicator == "safeh20" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "govteffect" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "healthtax" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "aginGDP" ~ weighted.mean(value, GDP, na.rm = TRUE),
          indicator == "functionalintegrity" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          indicator == "pesticides" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          indicator == "sustNO2mgmt" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          TRUE ~ globalmean)) %>%
          ungroup()
      df4 <- df4 %>% group_by(indicator) %>%
      mutate(globalmedian = median(value, na.rm = TRUE),
             globalmin = min(value, na.rm = TRUE),
             globalmax = max(value, na.rm = TRUE),
             globalp25 = quantile(value, c(.25)),
             globalp75 = quantile(value, c(.75))) %>%
      ungroup() %>% as.data.frame()

**# Weighted means grouping by region and indicator - otherwise all the same code and it works perfectly.**
    df5 <- df4 %>% group_by(fsci_regions, indicator) %>%
      mutate(regionmean = case_when(
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, beef", indicator)) ~ weighted.mean(value, prod_beef, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, cereals (excl rice)", indicator)) ~ weighted.mean(value, prod_cerealsnorice, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, chicken", indicator)) ~ weighted.mean(value, prod_chickenmeat, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, eggs", indicator)) ~ weighted.mean(value, prod_eggs, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, milk", indicator)) ~ weighted.mean(value, prod_cowmilk, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, pork", indicator)) ~ weighted.mean(value, prod_pork, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, rice", indicator)) ~ weighted.mean(value, prod_rice, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, cereals", indicator)) ~ weighted.mean(value, areaharvested_cereals, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, citrus", indicator)) ~ weighted.mean(value, areaharvested_citrus, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, fruit", indicator)) ~ weighted.mean(value, areaharvested_fruit, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, pulses", indicator)) ~ weighted.mean(value, areaharvested_pulses, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, roots and tubers", indicator)) ~ weighted.mean(value, areaharvested_roottuber, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, treenuts", indicator)) ~ weighted.mean(value, areaharvested_treenuts, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, vegetables", indicator)) ~ weighted.mean(value, areaharvested_vegetables, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, beef", indicator)) ~ weighted.mean(value, producinganimals_beef, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, chicken", indicator)) ~ weighted.mean(value, producinganimals_chickenmeat, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, milk", indicator)) ~ weighted.mean(value, producinganimals_cowmilk, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, eggs", indicator)) ~ weighted.mean(value, producinganimals_eggs, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, pork", indicator)) ~ weighted.mean(value, producinganimals_pork, na.rm = TRUE)),
        ((grepl("unweighted", mean_weighting))  ~ mean(value, na.rm = TRUE)),
        (grepl("totalpop", mean_weighting) ~ weighted.mean(value, totalpop, na.rm = TRUE)),
        (grepl("landarea", mean_weighting) ~ weighted.mean(value, landarea, na.rm = TRUE)),
        (grepl("cropland", mean_weighting)  ~ weighted.mean(value, croplandcov, na.rm = TRUE)),
        (grepl("pop_u", mean_weighting)  ~ weighted.mean(value, pop_u, na.rm = TRUE)),
        (TRUE ~ mean(value, na.rm = TRUE)))) %>% ungroup() %>%
      group_by(fsci_regions, short_label, globalmean, globalmedian, globalmin, globalmax, globalp25,
               globalp75, theme, direction) %>%
      summarise(regionmean = first(regionmean))
</code>```

I moved things around in the case_when ordering going from most specific to most general, before that even more lines had errors but now it's down to the 6 described above. I also tried coding more specifically the 6 that aren't working after the main chunk of code but that also didn't work (see annotation in code).

All insights would be so helpful!

Many thanks,
Kate

Body:
This is my first post! I have a dataset in long form where i have a column called "indicator" with 51 levels and then a column with numeric values and then a series of columns with identifying and weighting variables. I am using a long sequence of case_when conditions inside mutate to weight different levels of indicator by different other columns. The code is mostly working, but there are a few conditions where it is creating NAs for some of the levels of indicator that meet the condition, but not others. So this means it's not a problem in the line of the code, but something in the underlying data and I can't figure it out. I have tried separating out the distinct conditions into separate mutate functions but that didn't help. All help would be so much appreciated!

    # Weighted means # Grouping by indicator only - this is where I get errors
      df4 <- df3 %>%
      group_by(indicator) %>%
      mutate(globalmean = case_when(
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, beef", indicator)) ~ weighted.mean(value, prod_beef, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, cereals (excl rice)", indicator)) ~ weighted.mean(value, prod_cerealsnorice, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, chicken", indicator)) ~ weighted.mean(value, prod_chickenmeat, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, eggs", indicator)) ~ weighted.mean(value, prod_eggs, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, milk", indicator)) ~ weighted.mean(value, prod_cowmilk, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, pork", indicator)) ~ weighted.mean(value, prod_pork, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, rice", indicator)) ~ weighted.mean(value, prod_rice, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, cereals", indicator)) ~ weighted.mean(value, areaharvested_cereals, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, citrus", indicator)) ~ weighted.mean(value, areaharvested_citrus, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, fruit", indicator)) ~ weighted.mean(value, areaharvested_fruit, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, pulses", indicator)) ~ weighted.mean(value, areaharvested_pulses, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, roots and tubers", indicator)) ~ weighted.mean(value, areaharvested_roottuber, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, treenuts", indicator)) ~ weighted.mean(value, areaharvested_treenuts, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, vegetables", indicator)) ~ weighted.mean(value, areaharvested_vegetables, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, beef", indicator)) ~ weighted.mean(value, producinganimals_beef, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, chicken", indicator)) ~ weighted.mean(value, producinganimals_chickenmeat, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, milk", indicator)) ~ weighted.mean(value, producinganimals_cowmilk, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, eggs", indicator)) ~ weighted.mean(value, producinganimals_eggs, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, pork", indicator)) ~ weighted.mean(value, producinganimals_pork, na.rm = TRUE)),
        (grepl("pop_u", mean_weighting)  ~ weighted.mean(value, pop_u, na.rm = TRUE)),
        (grepl("GDP", mean_weighting)  ~ weighted.mean(value, GDP, na.rm = TRUE)), # one of two indicator levels meeting this condition works, the other results in NA
        (grepl("unweighted", mean_weighting) ~ mean(value, na.rm = TRUE)),
        (grepl("cropland", mean_weighting)  ~ weighted.mean(value, croplandcov, na.rm = TRUE)),
        (grepl("totalpop", mean_weighting) ~ weighted.mean(value, totalpop, na.rm = TRUE)), # Almost all of the indicator levels meeting this condition work, 3 result in NA
        (grepl("landarea", mean_weighting) ~ weighted.mean(value, landarea, na.rm = TRUE)),
        TRUE ~ mean(value)
        )
        ) %>%
## Tried this manual overwriting the NA indicator levels as a workaround but it doesn't fix the problem:
        mutate(globalmean = case_when(
          indicator == "safeh20" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "govteffect" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "healthtax" ~ weighted.mean(value, totalpop, na.rm = TRUE),
          indicator == "aginGDP" ~ weighted.mean(value, GDP, na.rm = TRUE),
          indicator == "functionalintegrity" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          indicator == "pesticides" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          indicator == "sustNO2mgmt" ~ weighted.mean(value, croplandcov, na.rm = TRUE),
          TRUE ~ globalmean)) %>%
          ungroup()
      df4 <- df4 %>% group_by(indicator) %>%
      mutate(globalmedian = median(value, na.rm = TRUE),
             globalmin = min(value, na.rm = TRUE),
             globalmax = max(value, na.rm = TRUE),
             globalp25 = quantile(value, c(.25)),
             globalp75 = quantile(value, c(.75))) %>%
      ungroup() %>% as.data.frame()

**# Weighted means grouping by region and indicator - otherwise all the same code and it works perfectly.**
    df5 <- df4 %>% group_by(fsci_regions, indicator) %>%
      mutate(regionmean = case_when(
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, beef", indicator)) ~ weighted.mean(value, prod_beef, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, cereals (excl rice)", indicator)) ~ weighted.mean(value, prod_cerealsnorice, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, chicken", indicator)) ~ weighted.mean(value, prod_chickenmeat, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, eggs", indicator)) ~ weighted.mean(value, prod_eggs, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, milk", indicator)) ~ weighted.mean(value, prod_cowmilk, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, pork", indicator)) ~ weighted.mean(value, prod_pork, na.rm = TRUE)),
        ((grepl("production", mean_weighting) & grepl("Emissions intensity, rice", indicator)) ~ weighted.mean(value, prod_rice, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, cereals", indicator)) ~ weighted.mean(value, areaharvested_cereals, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, citrus", indicator)) ~ weighted.mean(value, areaharvested_citrus, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, fruit", indicator)) ~ weighted.mean(value, areaharvested_fruit, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, pulses", indicator)) ~ weighted.mean(value, areaharvested_pulses, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, roots and tubers", indicator)) ~ weighted.mean(value, areaharvested_roottuber, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, treenuts", indicator)) ~ weighted.mean(value, areaharvested_treenuts, na.rm = TRUE)),
        ((grepl("areaharvested", mean_weighting) & grepl("Yield, vegetables", indicator)) ~ weighted.mean(value, areaharvested_vegetables, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, beef", indicator)) ~ weighted.mean(value, producinganimals_beef, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, chicken", indicator)) ~ weighted.mean(value, producinganimals_chickenmeat, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, milk", indicator)) ~ weighted.mean(value, producinganimals_cowmilk, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, eggs", indicator)) ~ weighted.mean(value, producinganimals_eggs, na.rm = TRUE)),
        ((grepl("producinganimals", mean_weighting) & grepl("Yield, pork", indicator)) ~ weighted.mean(value, producinganimals_pork, na.rm = TRUE)),
        ((grepl("unweighted", mean_weighting))  ~ mean(value, na.rm = TRUE)),
        (grepl("totalpop", mean_weighting) ~ weighted.mean(value, totalpop, na.rm = TRUE)),
        (grepl("landarea", mean_weighting) ~ weighted.mean(value, landarea, na.rm = TRUE)),
        (grepl("cropland", mean_weighting)  ~ weighted.mean(value, croplandcov, na.rm = TRUE)),
        (grepl("pop_u", mean_weighting)  ~ weighted.mean(value, pop_u, na.rm = TRUE)),
        (TRUE ~ mean(value, na.rm = TRUE)))) %>% ungroup() %>%
      group_by(fsci_regions, short_label, globalmean, globalmedian, globalmin, globalmax, globalp25,
               globalp75, theme, direction) %>%
      summarise(regionmean = first(regionmean))

I moved things around in the case_when ordering going from most specific to most general, before that even more lines had errors but now it's down to the 6 described above. I also tried coding more specifically the 6 that aren't working after the main chunk of code but that also didn't work (see annotation in code).

All insights would be so helpful!

Many thanks,
Kate


来源: stackexchange

问:
How to handle the unloaded event of a webbrowser in order to do some stuff when it is closed
I am opening a PDF file using below code:

```<code>System.Windows.Controls.Frame frame = new System.Windows.Controls.Frame();
System.Windows.Controls.WebBrowser browser = new System.Windows.Controls.WebBrowser();
browser.Unloaded += Browser_Unloaded;
Uri myUri = new Uri("C:\Users\MyUser\Downloads\myPDFFile.pdf", UriKind.RelativeOrAbsolute);
browser.Navigate(myUri);
frame.Content = browser;
</code>```

And below the event handler for when Browser is unloaded:

```<code>private void Browser_Unloaded(object sender, System.Windows.RoutedEventArgs e)
{
    browser = frame.Content as System.Windows.Controls.WebBrowser;
    browser.Dispose();
    frame.Content = null;
}
</code>```

What I am trying to do is to handle when browser is closed but above event handler is not being fired.

ContentLicense: CC BY-SA 4.0

Body:
I am opening a PDF file using below code:

System.Windows.Controls.Frame frame = new System.Windows.Controls.Frame();
System.Windows.Controls.WebBrowser browser = new System.Windows.Controls.WebBrowser();
browser.Unloaded += Browser_Unloaded;
Uri myUri = new Uri("C:\Users\MyUser\Downloads\myPDFFile.pdf", UriKind.RelativeOrAbsolute);
browser.Navigate(myUri);
frame.Content = browser;

And below the event handler for when Browser is unloaded:

private void Browser_Unloaded(object sender, System.Windows.RoutedEventArgs e)
{
    browser = frame.Content as System.Windows.Controls.WebBrowser;
    browser.Dispose();
    frame.Content = null;
}

What I am trying to do is to handle when browser is closed but above event handler is not being fired.


问:
Prevent extra middle space on the last row of a flex container with justify content: space-between
When my flex container has a different number of elements in the last row than the previous rows, the space-between property makes it so that there is too much space between the elements in the last row. I would like the last element to be in the second column.

I have tried adding the following code but it just makes the gaps in the second smaller.

```<code>.grid::after {
    content: "";
    flex: auto;
}
</code>```

Before adding the above code: (https://i.stack.imgur.com/bJVJS.jpg)

After adding the code:
(https://i.stack.imgur.com/BuF9L.jpg)
(https://i.stack.imgur.com/Qdt70.jpg)

Body:
When my flex container has a different number of elements in the last row than the previous rows, the space-between property makes it so that there is too much space between the elements in the last row. I would like the last element to be in the second column.

I have tried adding the following code but it just makes the gaps in the second smaller.

.grid::after {
    content: "";
    flex: auto;
}

Before adding the above code: (https://i.stack.imgur.com/bJVJS.jpg)

After adding the code:
(https://i.stack.imgur.com/BuF9L.jpg)
(https://i.stack.imgur.com/Qdt70.jpg)


问:
Comparing directories with cksum to include spaces in file names
I recently used rsync to transfer a large directory with a lot of subdirectories; several GB size in total. There are several thousand files to compare. Trying to see if everything went well and that every file is where it should be, ie. I have a clone of the original directory.

I want to feed this script (compare_directories) the two directories to compare: compare_directories dir1 dir2

```<code>#!/bin/bash

if [[ -z $2 ]];
then
    # simple help text with no error checking
    echo "compare_directories dir1 dir2"
    echo "   dir1  directory with files copied from"
    echo "   dir2  directory with files copied to"
else
    export FROM=$1
    export TO=$2
    cnt=0
    for fname in *
    do
        from=$(cksum $FROM/$fname)
        from=${from%% *}
        to=$(cksum $TO/${fname})
        to=${to%% *}
        cnt=$(($cnt + 1))
        [ $(($cnt % 5)) -eq 0 ] && echo "$cnt files processed"
        [ "$from" = "$to" ] && continue
        echo "failure on file $fname"
    done
fi
</code>```

The line with the "x files processed" is just there to indicate that the comparison is still running by printing a counter after every 5 processed files.

I used this script to compare the checksums of each file, but it doesn't like spaces in file names, and I'm not entirely sure if it's running efficiently.

Body:
I recently used rsync to transfer a large directory with a lot of subdirectories; several GB size in total. There are several thousand files to compare. Trying to see if everything went well and that every file is where it should be, ie. I have a clone of the original directory.

I want to feed this script (compare_directories) the two directories to compare: compare_directories dir1 dir2

#!/bin/bash

if [[ -z $2 ]];
then
    # simple help text with no error checking
    echo "compare_directories dir1 dir2"
    echo "   dir1  directory with files copied from"
    echo "   dir2  directory with files copied to"
else
    export FROM=$1
    export TO=$2
    cnt=0
    for fname in *
    do
        from=$(cksum $FROM/$fname)
        from=${from%% *}
        to=$(cksum $TO/${fname})
        to=${to%% *}
        cnt=$(($cnt + 1))
        [ $(($cnt % 5)) -eq 0 ] && echo "$cnt files processed"
        [ "$from" = "$to" ] && continue
        echo "failure on file $fname"
    done
fi

The line with the "x files processed" is just there to indicate that the comparison is still running by printing a counter after every 5 processed files.

I used this script to compare the checksums of each file, but it doesn't like spaces in file names, and I'm not entirely sure if it's running efficiently.


问:
Run a single test function in R's testthat
R's testthat package has a number of functions for running tests: https://testthat.r-lib.org/reference/index.html#run-tests. However, the most coarse level you can filter tests seems to be at a file level, since there is a test_file() function that doesn't have any filtering arguments, and test_dir() has a filter argument but it is only used to filter by filename.

However I frequently want to only run a single test, because it's new, or because I know it's relevant to a change I just made.

Is there a way, in the R console or in RStudio to run a single testthat test? If not, is there some other recommended solution to this problem such as putting each test in it's own file (this seems pretty painful though)?


问:
Debugging C++ code in R (g++: error: UDEBUG: No such file or directory)
I am trying to debug C++ code in an R package by following the steps from https://mpadge.github.io/blog/blog012.html.

The argument PKG_CPPFLAGS=-UDEBUG -g in Makevars doesn't work.

I can compile the code correctly, but then I get

```<code>fixest2 (main) $ R -d gdb -e 'source("vscode-test.r")'
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Reading symbols from /usr/lib/R/bin/exec/R...
(No debugging symbols found in /usr/lib/R/bin/exec/R)
(gdb)
</code>```

Any ideas? I'm on Ubuntu 20.04

Body:
I am trying to debug C++ code in an R package by following the steps from https://mpadge.github.io/blog/blog012.html.

The argument PKG_CPPFLAGS=-UDEBUG -g in Makevars doesn't work.

I can compile the code correctly, but then I get

fixest2 (main) $ R -d gdb -e 'source("vscode-test.r")'
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Reading symbols from /usr/lib/R/bin/exec/R...
(No debugging symbols found in /usr/lib/R/bin/exec/R)
(gdb)

Any ideas? I'm on Ubuntu 20.04


问:
Insert data into a table from a view before delete using trigger DBeaver
I have a main table named employee and I need to log my data into employee_exit table when any employee is removed from employee table and I need to fetch data from a view named EmployeeRecord and insert into employee_exit table using a trigger.

```<code>CREATE TRIGGER LogEmployeeExit
BEFORE DELETE ON Employee
FOR EACH ROW
BEGIN
    INSERT INTO Employee_Exit
      (EmployeeID, ExitDate, TotalMasterCard, TotalDonationAmt)
    SELECT EmployeeID,NOW(),TotalMasterCard,TotalDonation FROM EmployeeRecord WHERE EmployeeID = NEW.ID;
END
</code>```

I tried using trigger which didn't work for me.

Body:
I have a main table named employee and I need to log my data into employee_exit table when any employee is removed from employee table and I need to fetch data from a view named EmployeeRecord and insert into employee_exit table using a trigger.

CREATE TRIGGER LogEmployeeExit
BEFORE DELETE ON Employee
FOR EACH ROW
BEGIN
    INSERT INTO Employee_Exit
      (EmployeeID, ExitDate, TotalMasterCard, TotalDonationAmt)
    SELECT EmployeeID,NOW(),TotalMasterCard,TotalDonation FROM EmployeeRecord WHERE EmployeeID = NEW.ID;
END

I tried using trigger which didn't work for me.


问:
How to resume an activity that is in background when tap on a Notification in Android
In my app i have 3 different Activity. Main Activity, Album Activity and Camera Activity.
when my app is in background with:

Main activity, and user tap on notification, app resume with main activity.

Album activity, and user tap on notification, app resume with main activity.

Camera activity, and user tap on notification, app resume with main activity.

what i want is, if my app is in background with:

Main activity, and user tap on notification, app will resume with main activity.

Album activity, and user tap on notification, app will resume with album activity.

Camera activity, and user tap on notification, app will resume with camera activity.

how i can achieve this?? I am implementing FCM push notification and my project is Android with jetpack compose.

Thanks in advance.

```<code>   override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

   val intent: Intent? = packageManager.getLaunchIntentForPackage(packageName)
            intent?.run {
                startActivity(this)
            }

            // it should be unique when push comes
            val requestCode = System.currentTimeMillis().toInt()

            // Pending intent for activity
            val pendingIntent: PendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE)

     notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_newarrivalicon)
                .setContentTitle(notification.title)
                .setContentText(notification.body)
                .setAutoCancel(true)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setContentIntent(pendingIntent)

            with(NotificationManagerCompat.from(this)) {
                notify(requestCode, notificationBuilder.build())
            }
}
</code>```

My Manifaest is like this

```<code>      <activity
        android:name=".ui.home.MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/Theme.CustomSplashScreenTheme"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:host="cognivision.jp" android:scheme="https" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ui.album.AlbumActivity"
        android:parentActivityName=".ui.home.MainActivity"
        android:directBootAware="true"
        android:exported="true"
        android:launchMode="singleTop"
        android:label="@string/title_activity_album"
        android:theme="@style/Theme.CustomSplashScreenTheme"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
    </activity>
</code>```

so, The onMessageRecived() triggered when the app running on foreground and i passed my package instead of specific activity to the intent. But when the app is on background, system handle the push notification and when i tap on notification my app start from Main activity always. But i don't want any specific activity to open, i want whatever the activity was on display before app going background to open exactly same activity and same screen.

Body:
In my app i have 3 different Activity. Main Activity, Album Activity and Camera Activity.
when my app is in background with:

Main activity, and user tap on notification, app resume with main activity.

Album activity, and user tap on notification, app resume with main activity.

Camera activity, and user tap on notification, app resume with main activity.

what i want is, if my app is in background with:

Main activity, and user tap on notification, app will resume with main activity.

Album activity, and user tap on notification, app will resume with album activity.

Camera activity, and user tap on notification, app will resume with camera activity.

how i can achieve this?? I am implementing FCM push notification and my project is Android with jetpack compose.

Thanks in advance.

   override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

   val intent: Intent? = packageManager.getLaunchIntentForPackage(packageName)
            intent?.run {
                startActivity(this)
            }

            // it should be unique when push comes
            val requestCode = System.currentTimeMillis().toInt()

            // Pending intent for activity
            val pendingIntent: PendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE)

     notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_newarrivalicon)
                .setContentTitle(notification.title)
                .setContentText(notification.body)
                .setAutoCancel(true)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setContentIntent(pendingIntent)

            with(NotificationManagerCompat.from(this)) {
                notify(requestCode, notificationBuilder.build())
            }
}

My Manifaest is like this

      <activity
        android:name=".ui.home.MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/Theme.CustomSplashScreenTheme"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:host="cognivision.jp" android:scheme="https" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ui.album.AlbumActivity"
        android:parentActivityName=".ui.home.MainActivity"
        android:directBootAware="true"
        android:exported="true"
        android:launchMode="singleTop"
        android:label="@string/title_activity_album"
        android:theme="@style/Theme.CustomSplashScreenTheme"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
    </activity>

so, The onMessageRecived() triggered when the app running on foreground and i passed my package instead of specific activity to the intent. But when the app is on background, system handle the push notification and when i tap on notification my app start from Main activity always. But i don't want any specific activity to open, i want whatever the activity was on display before app going background to open exactly same activity and same screen.


问:
Adding margin to move the text in VB .NET
I want to insert the margin to the text so that i can move the text up little bi but the .PadTop is cannot be used. How to solve this problem?</p>
```<code>    txtTitle.Text = StrConv(view, VbStrConv.Uppercase)
    txtTitle.Font.Size = 20
    txtTitle.ForeColor = Drawing.Color.Pink
    txtTitle.Font.Bold = True
    txtTitle.Pad.Top = 20
</code>```

Body:
I want to insert the margin to the text so that i can move the text up little bi but the .PadTop is cannot be used. How to solve this problem?

    txtTitle.Text = StrConv(view, VbStrConv.Uppercase)
    txtTitle.Font.Size = 20
    txtTitle.ForeColor = Drawing.Color.Pink
    txtTitle.Font.Bold = True
    txtTitle.Pad.Top = 20


问:
Running p4 on OVS
I am trying to run P4 on OVS following this github repo https://github.com/Orange-OpenSource/p4rt-ovs. I could setup OvS with DPDK as well p4c to compile p4 to C and then C to ubpf code. However, I am missing the command to load the BPF program into my OvS

```<code>ovs-ofctl load-bpf-prog br0 1 /tmp/tunneling.o
</code>```

However, this option seems to be missing from my OvS. ( Error - unknown option load-bpf-prog). I am using the same version of OvS as the repo. Any suggestions/hints as to what I could do to install this utility (load-bpf-prog)? Thank you for help

Title: Running p4 on OVS

Body:
I am trying to run P4 on OVS following this github repo https://github.com/Orange-OpenSource/p4rt-ovs. I could setup OvS with DPDK as well p4c to compile p4 to C and then C to ubpf code. However, I am missing the command to load the BPF program into my OvS

ovs-ofctl load-bpf-prog br0 1 /tmp/tunneling.o

However, this option seems to be missing from my OvS. ( Error - unknown option load-bpf-prog). I am using the same version of OvS as the repo. Any suggestions/hints as to what I could do to install this utility (load-bpf-prog)? Thank you for help


问:
Fix build react-native ios
Can anyone please tell me what this error is and how to fix it?

Title: Fix build react-native ios


问:
Redirect to the caller endpoint after successful authentication
In my ASP.NET Core web app, I want (a) the authorization middleware to take the unauthenticated user to the login endpoint first and (b) to return to the action after the successful login.

With the following code, (a) works as expected, but not sure how to return the caller action in the callback. I tried the suggested approaches here with no joy.

public class AccountController: ControllerBase
{
    [AllowAnonymous]
    [HttpGet]
    public IActionResult Signin()
    {
        var props = _signInManager.ConfigureExternalAuthenticationProperties(provider: GoogleDefaults.AuthenticationScheme);
        return new ChallengeResult(GoogleDefaults.AuthenticationScheme, props);
    }

    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> Callback()
    {
        var info = await _signInManager.GetExternalLoginInfoAsync();
        var user = new User
        {
            Email = info.Principal.FindFirstValue(ClaimTypes.Email),
            UserName = info.Principal.FindFirstValue(ClaimTypes.Email)
        };

        await _userManager.CreateAsync(user);
        await _signInManager.SignInAsync(user, isPersistent: true, authenticationMethod: null);
        return Ok();
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetUserProfile()
    {
        var user = User;
        return GetUserProfile(user);
    }
}
```
<p>In other words, I want a call to <code>GetUserProfile</code> endpoint from an unauthenticated user to redirect to <code>Sigin</code>, then to Google login, then to <code>Callback</code>, then to <code>GetUserProfile</code> with the authenticated user information. I am not sure how to return to <code>GetUserProfile</code> (or any caller in general) from <code>Callback</code>.</p>
<p>I configure the authNZ services as the following if needed.</p>
<pre class="lang-cs prettyprint-override"><code>services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/api/v1/account/signin";
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
    options.ClientId = GetGoogleClientId();
    options.ClientSecret = GetGoogleSecret();
});
</code>```

Body:
In my ASP.NET Core web app, I want (a) the authorization middleware to take the unauthenticated user to the login endpoint first and (b) to return to the action after the successful login.

With the following code, (a) works as expected, but not sure how to return the caller action in the callback. I tried the suggested approaches here with no joy.

public class AccountController: ControllerBase
{
    [AllowAnonymous]
    [HttpGet]
    public IActionResult Signin()
    {
        var props = _signInManager.ConfigureExternalAuthenticationProperties(provider: GoogleDefaults.AuthenticationScheme);
        return new ChallengeResult(GoogleDefaults.AuthenticationScheme, props);
    }

    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> Callback()
    {
        var info = await _signInManager.GetExternalLoginInfoAsync();
        var user = new User
        {
            Email = info.Principal.FindFirstValue(ClaimTypes.Email),
            UserName = info.Principal.FindFirstValue(ClaimTypes.Email)
        };

        await _userManager.CreateAsync(user);
        await _signInManager.SignInAsync(user, isPersistent: true, authenticationMethod: null);
        return Ok();
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetUserProfile()
    {
        var user = User;
        return GetUserProfile(user);
    }
}

In other words, I want a call to GetUserProfile endpoint from an unauthenticated user to redirect to Sigin, then to Google login, then to Callback, then to GetUserProfile with the authenticated user information. I am not sure how to return to GetUserProfile (or any caller in general) from Callback.

I configure the authNZ services as the following if needed.

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/api/v1/account/signin";
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
    options.ClientId = GetGoogleClientId();
    options.ClientSecret = GetGoogleSecret();
});


问:
Python gRPC request missing occasionally
I'm using gRPC in python with django and django-grpc-framework.

And when I run the unittest, there is a piece of code in my models.py which producing weird problem: I request three gRPC requests, but only one reaches the server side.

Problem details

To simplified the problem, the following code explains the situation:

```<code>class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(
                app_label='...',
                object_type='...',
                object_id='...',
                exchange_id='...',
                remark='...',
                date_record='...',
            ))
</code>```

Here, the some_method is triggering under a django.test.TestCase unittest function, while the gRPC was connecting to a external running server instance.

And the relating .proto files is as below:

```<code>// base.proto
// ...
message CreditRecord {
    int64 id = 1;
    string username = 2;
    string app_label = 3;
    string flag = 4;
    string object_type = 5;
    int64 object_id = 6;
    int64 amount = 7;
    int64 balance = 8;
    string remark = 9;
    string date_record = 10;
    string exchange_id = 11;
    int64 retract_ref = 12;
}

message RetractObjectRequest {
    string app_label = 1;
    string object_type = 2;
    int64 object_id = 3;
    string exchange_id = 4;
    string remark = 5;
    string date_record = 6;
}
// ...
</code>```
```<code>// stub1 - stub3 has the similar structure below
syntax = "proto3";

package mjtest.growth;

import "mjtest/growth/base.proto";

service CreditController {
    // ...
    rpc RetractObject (RetractObjectRequest) returns (stream CreditRecord) {}
}

</code>```

And the Server-Side code is something like (using django-grpc-framework):

```<code># services.py
class GenericCreditService(mixins.RetrieveModelMixin,
                           mixins.ListModelMixin,
                           GenericService):
    def RetractObject(self, request: base_pb2.RetractObjectRequest, context):
        print('Request reached!', request)
        # ...
        records = model_class.retract_object(...)
        # Here, records has aready return a list, not a iterator.
        for rec in records:
            yield self.serializer_class(rec).message
</code>```

So, when I trigger the unittest, the client-side calls THREE times to request a RetractObject gRPC method.

But only ONE time when Request reached! was printed.

Attempt #1: adding a sleep(0.5)

I guess that there's some issue inside the client side, and I add sleep(0.5) after every request.

```<code>class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(...))
            sleep(0.5)
</code>```

Then all three requests reaches!

Attempt #2: traverses the response explicitly.

I guess that the stream response with no consumed may cause the problem, so I transfer the response to a list explicitly.

```<code>class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(...))
            list(resp)
</code>```

Then all three requests reaches!

So the problem is so weird, and neither of the ways I request throws an error.

Can anyone help?

Body:
I'm using gRPC in python with django and django-grpc-framework.

And when I run the unittest, there is a piece of code in my models.py which producing weird problem: I request three gRPC requests, but only one reaches the server side.

Problem details

To simplified the problem, the following code explains the situation:

class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(
                app_label='...',
                object_type='...',
                object_id='...',
                exchange_id='...',
                remark='...',
                date_record='...',
            ))

Here, the some_method is triggering under a django.test.TestCase unittest function, while the gRPC was connecting to a external running server instance.

And the relating .proto files is as below:

// base.proto
// ...
message CreditRecord {
    int64 id = 1;
    string username = 2;
    string app_label = 3;
    string flag = 4;
    string object_type = 5;
    int64 object_id = 6;
    int64 amount = 7;
    int64 balance = 8;
    string remark = 9;
    string date_record = 10;
    string exchange_id = 11;
    int64 retract_ref = 12;
}

message RetractObjectRequest {
    string app_label = 1;
    string object_type = 2;
    int64 object_id = 3;
    string exchange_id = 4;
    string remark = 5;
    string date_record = 6;
}
// ...

// stub1 - stub3 has the similar structure below
syntax = "proto3";

package mjtest.growth;

import "mjtest/growth/base.proto";

service CreditController {
    // ...
    rpc RetractObject (RetractObjectRequest) returns (stream CreditRecord) {}
}

And the Server-Side code is something like (using django-grpc-framework):

# services.py
class GenericCreditService(mixins.RetrieveModelMixin,
                           mixins.ListModelMixin,
                           GenericService):
    def RetractObject(self, request: base_pb2.RetractObjectRequest, context):
        print('Request reached!', request)
        # ...
        records = model_class.retract_object(...)
        # Here, records has aready return a list, not a iterator.
        for rec in records:
            yield self.serializer_class(rec).message

So, when I trigger the unittest, the client-side calls THREE times to request a RetractObject gRPC method.

But only ONE time when Request reached! was printed.

Attempt #1: adding a sleep(0.5)

I guess that there's some issue inside the client side, and I add sleep(0.5) after every request.

class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(...))
            sleep(0.5)

Then all three requests reaches!

Attempt #2: traverses the response explicitly.

I guess that the stream response with no consumed may cause the problem, so I transfer the response to a list explicitly.

class MyModel(models.Model):
    def some_method(self):
        for stub in [stub1, stub2, stub3]:
            resp = stub.RetractObject(base_pb2.RetractObjectRequest(...))
            list(resp)

Then all three requests reaches!

So the problem is so weird, and neither of the ways I request throws an error.

Can anyone help?


问:
Ignoring an Admin with specific command
I have created a anti-abuse command where I want to ignore Administrators of the server and I have used this like
const permission = [PermissionFlagsBits.Administrator];
if (message.member.permissions.has(permission)) return;
And it gives this error.

```<code>TypeError: Cannot read properties of null ( reading "permissions)
</code>```

It would be great if someone helps me!

I was expecting that it would ignore Administrators and take action though the members..

Title: Ignoring an Admin with specific command

Body:
I have created a anti-abuse command where I want to ignore Administrators of the server and I have used this like
const permission = [PermissionFlagsBits.Administrator];
if (message.member.permissions.has(permission)) return;
And it gives this error.

TypeError: Cannot read properties of null ( reading "permissions)

It would be great if someone helps me!

I was expecting that it would ignore Administrators and take action though the members..


问:
psutil 0.6.1 version of cpu_times,cpu_percent, memory_info,memory_percent
We have a code like below

```<code>    for p in psutil.process_iter():
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                               'cpu_times', 'name', 'status'])
</code>```

but on a centos6.10 with python 2.6.6, psutil version 0.6.1
Process install does not have "cpu_times,cpu_percent, memory_info,memory_percent" at all and generate error like AttributeError: 'Process' object has no attribute 'memory_percent'
so does anyone how I can get similar info in 0.6.1 for each process

```<code>[root@centos610 xxx]# python
Python 2.6.6 (r266:84292, Jun 20 2019, 14:14:55)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> psutil.version_info
(0, 6, 1)

</code>```

Thanks

Body:
We have a code like below

    for p in psutil.process_iter():
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                               'cpu_times', 'name', 'status'])

but on a centos6.10 with python 2.6.6, psutil version 0.6.1
Process install does not have "cpu_times,cpu_percent, memory_info,memory_percent" at all and generate error like AttributeError: 'Process' object has no attribute 'memory_percent'
so does anyone how I can get similar info in 0.6.1 for each process

[root@centos610 xxx]# python
Python 2.6.6 (r266:84292, Jun 20 2019, 14:14:55)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> psutil.version_info
(0, 6, 1)

Thanks


问:
Button to save data from a result to a data table; user token required error
I'm trying to add a button that takes data from a search results page and adds it to a data table. For example the first search result displays properly and I want the Favorites Button to save the data for the logged in user.

I keep getting the "message": "Token is Missing!" from the helper.py.
Fairly new to all this so I know I'm not using the best methods but at this point would just like to get this to work somewhat.
I'm guessing this is due to the @token_required. But I'm not sure how to fix this.

This is the route.

```<code>@api.route('/movies', methods = ['POST'])
@token_required
def save_movie(current_user_token):
    title = request.json['title']
    tmdb_id = request.json['tmdb_id']
    user_token = current_user_token.token

    print(f"User Token: {current_user_token.token}")

    movie = SaveMovie(title, tmdb_id, user_token=user_token)

    db.session.add(movie)
    db.session.commit()

    response = movie_schema.dump(movie)

    return jsonify(response)
</code>```

and this is the form I'm using

```<code>            <form action="/api/movies" method="POST">
                <input type="hidden" name="title" value="{{ results.0.title }}"/>
                <input type="hidden" name="tmdb_id" value="{{ results.0.id }}"/>
                <input type="hidden" name="x-access-token" value="Bearer {{ current_user.token }}"/>
                <button name ="submit" class="btn btn-primary" type="submit">Favorite</button>
            </form>
</code>```

This is the Model

```<code>class Movie:
    """
    Movie class to define Movie Objects
    """

    def __init__(self,id,title,overview,poster):
        self.id = id
        self.title = title
        self.overview = overview
        self.poster = f"https://image.tmdb.org/t/p/w500/{poster}"
</code>```

And these are the functions

```<code>def search_movie(query):
    data = requests.get(f"{BASEURL}/search/movie?api_key={API_KEY}&language=en-US&query={query}&page=1&include_adult=false").json()
    if data['results']:
        search_data = process_results(data['results'])
    return search_data

def process_results(movie_list):
    movie_results = []
    for movie_item in movie_list:
        id = movie_item.get('id')
        title = movie_item.get('original_title')
        overview = movie_item.get('overview')
        poster = movie_item.get('poster_path')

        if poster:
            movie_object = Movie(id, title, overview, poster)
            movie_results.append(movie_object)

    return movie_results
</code>```

I've attempted to add the token in the form to see if that would help but that didn't work and I'm not sure if maybe I need a @login-required for the search results but that would not be ideal. Would creating another function as a go between fix this?

Body:
I'm trying to add a button that takes data from a search results page and adds it to a data table. For example the first search result displays properly and I want the Favorites Button to save the data for the logged in user.

I keep getting the "message": "Token is Missing!" from the helper.py.
Fairly new to all this so I know I'm not using the best methods but at this point would just like to get this to work somewhat.
I'm guessing this is due to the @token_required. But I'm not sure how to fix this.

This is the route.

@api.route('/movies', methods = ['POST'])
@token_required
def save_movie(current_user_token):
    title = request.json['title']
    tmdb_id = request.json['tmdb_id']
    user_token = current_user_token.token

    print(f"User Token: {current_user_token.token}")

    movie = SaveMovie(title, tmdb_id, user_token=user_token)

    db.session.add(movie)
    db.session.commit()

    response = movie_schema.dump(movie)

    return jsonify(response)

and this is the form I'm using

            <form action="/api/movies" method="POST">
                <input type="hidden" name="title" value="{{ results.0.title }}"/>
                <input type="hidden" name="tmdb_id" value="{{ results.0.id }}"/>
                <input type="hidden" name="x-access-token" value="Bearer {{ current_user.token }}"/>
                <button name ="submit" class="btn btn-primary" type="submit">Favorite</button>
            </form>

This is the Model

class Movie:
    """
    Movie class to define Movie Objects
    """

    def __init__(self,id,title,overview,poster):
        self.id = id
        self.title = title
        self.overview = overview
        self.poster = f"https://image.tmdb.org/t/p/w500/{poster}"

And these are the functions

def search_movie(query):
    data = requests.get(f"{BASEURL}/search/movie?api_key={API_KEY}&language=en-US&query={query}&page=1&include_adult=false").json()
    if data['results']:
        search_data = process_results(data['results'])
    return search_data

def process_results(movie_list):
    movie_results = []
    for movie_item in movie_list:
        id = movie_item.get('id')
        title = movie_item.get('original_title')
        overview = movie_item.get('overview')
        poster = movie_item.get('poster_path')

        if poster:
            movie_object = Movie(id, title, overview, poster)
            movie_results.append(movie_object)

    return movie_results

I've attempted to add the token in the form to see if that would help but that didn't work and I'm not sure if maybe I need a @login-required for the search results but that would not be ideal. Would creating another function as a go between fix this?


问:
Coroutine issue in script for Unity3D
I have a script WebSourceConfig to read the JSON config file, and use WebSourceLink script to render buttons into Unity app. WebSourceLink always need to run after WebSourceConfig finished, otherwise, there will no any data to parse in the app.

I'm using coroutine, and IEnumerator method to ask running in this sequence.

```<code>public class WebSourceLink : MonoBehaviour
{
    public WebSourceConfig configSource;

    //Buttons references
    public Button buttonPrefab;
    public GameObject Buttons;

    //Browser windows references
    public GameObject browserWindow;
    public GameObject Windows;

    private Vector2 _nextWindowPosition = new(-900f, 0f);

    void Start()
    {
        // Start coroutne to wait for read config file
        StartCoroutine(WaitForConfigRead());
    }

    IEnumerator WaitForConfigRead()
    {
        // Continually check if the config file has been read
        while (configSource.webConfig == null)
        {
            // Use the yield return statement to pause the coroutine
            // until the next frame
            Debug.Log("Null data parsed");
            yield return null;
        }

        Debug.Log(configSource.webConfig);

        // Once the file is read by WebSourceConfig, read the config data
        ReadData();

        InvokeRepeating("ReadData", 300, 5 * 60);
    }

......

}
</code>```

But the configSource == null or configSource.webConfig == null always be false, configSource's value is Main Camera (WebSourceConfig), configSource.webConfig's value is WebConfiguration no matter the config file be downloaded or not.

What's wrong with my script? How to can I fix it?

Here is my WebSourceConfig script to read downloaded file. I also use coroutine, it works to read config file only if the file is downloaded.

```<code>public class WebSourceConfig : MonoBehaviour
{
    public WebConfiguration webConfig;

    // Store the last time the config file was read
    private DateTime lastReadTime = DateTime.MinValue;

    void Start()
    {
        // Start the coroutine to wait for the file to be downloaded
        StartCoroutine(WaitForConfigFile());
    }

    IEnumerator WaitForConfigFile()
    {
        // Continually check if the config file has been downloaded yet
        while (!File.Exists(Path.Combine(Application.streamingAssetsPath, "config.json")))
        {
            // Use the yield return statement to pause the coroutine
            // until the next frame
            yield return null;
        }

        // Once the file is downloaded, read the config file
        ReadConfigFile();

        // Call the CheckConfigFile method every 5 minutes
        InvokeRepeating("CheckConfigFile", 300, 5 * 60);
    }

    void CheckConfigFile()
    {
        // Check for changes to the config file
        // If the file has changed, read it again
        if (HasConfigFileChanged())
        {
            ReadConfigFile();
        }
    }

    void ReadConfigFile()
    {
        try
        {
            // Use the Path.Combine method to create the full path to the JSON file
            string jsonPath = Path.Combine(Application.streamingAssetsPath, "config.json");

            // Read the JSON file into a string
            string json = File.ReadAllText(jsonPath);

            // Convert the JSON string into a strongly-typed object
            webConfig = JsonUtility.FromJson<WebConfiguration>(json);
        }
        catch (System.Exception ex)
        {
            // Print the error message to the console
            Debug.LogError(ex.Message);
        }
    }

    bool HasConfigFileChanged()
    {
        // Get the last modified time of the file
        string jsonPath = Path.Combine(Application.streamingAssetsPath, "config.json");
        var lastModifiedTime = File.GetLastWriteTime(jsonPath);

        // Check if the last modified time is different from the time when we last read the file
        if (lastModifiedTime != lastReadTime)
        {
            // Update the lastReadTime to the current time
            lastReadTime = lastModifiedTime;

            // Return true to indicate that the file has changed
            return true;
        }

        // Return false if the file has not changed
        return false;
    }
}
</code>```

Title: Coroutine issue in script for Unity3D

Body:
I have a script WebSourceConfig to read the JSON config file, and use WebSourceLink script to render buttons into Unity app. WebSourceLink always need to run after WebSourceConfig finished, otherwise, there will no any data to parse in the app.

I'm using coroutine, and IEnumerator method to ask running in this sequence.

public class WebSourceLink : MonoBehaviour
{
    public WebSourceConfig configSource;

    //Buttons references
    public Button buttonPrefab;
    public GameObject Buttons;

    //Browser windows references
    public GameObject browserWindow;
    public GameObject Windows;

    private Vector2 _nextWindowPosition = new(-900f, 0f);

    void Start()
    {
        // Start coroutne to wait for read config file
        StartCoroutine(WaitForConfigRead());
    }

    IEnumerator WaitForConfigRead()
    {
        // Continually check if the config file has been read
        while (configSource.webConfig == null)
        {
            // Use the yield return statement to pause the coroutine
            // until the next frame
            Debug.Log("Null data parsed");
            yield return null;
        }

        Debug.Log(configSource.webConfig);

        // Once the file is read by WebSourceConfig, read the config data
        ReadData();

        InvokeRepeating("ReadData", 300, 5 * 60);
    }

......

}

But the configSource == null or configSource.webConfig == null always be false, configSource's value is Main Camera (WebSourceConfig), configSource.webConfig's value is WebConfiguration no matter the config file be downloaded or not.

What's wrong with my script? How to can I fix it?

Here is my WebSourceConfig script to read downloaded file. I also use coroutine, it works to read config file only if the file is downloaded.

public class WebSourceConfig : MonoBehaviour
{
    public WebConfiguration webConfig;

    // Store the last time the config file was read
    private DateTime lastReadTime = DateTime.MinValue;

    void Start()
    {
        // Start the coroutine to wait for the file to be downloaded
        StartCoroutine(WaitForConfigFile());
    }

    IEnumerator WaitForConfigFile()
    {
        // Continually check if the config file has been downloaded yet
        while (!File.Exists(Path.Combine(Application.streamingAssetsPath, "config.json")))
        {
            // Use the yield return statement to pause the coroutine
            // until the next frame
            yield return null;
        }

        // Once the file is downloaded, read the config file
        ReadConfigFile();

        // Call the CheckConfigFile method every 5 minutes
        InvokeRepeating("CheckConfigFile", 300, 5 * 60);
    }

    void CheckConfigFile()
    {
        // Check for changes to the config file
        // If the file has changed, read it again
        if (HasConfigFileChanged())
        {
            ReadConfigFile();
        }
    }

    void ReadConfigFile()
    {
        try
        {
            // Use the Path.Combine method to create the full path to the JSON file
            string jsonPath = Path.Combine(Application.streamingAssetsPath, "config.json");

            // Read the JSON file into a string
            string json = File.ReadAllText(jsonPath);

            // Convert the JSON string into a strongly-typed object
            webConfig = JsonUtility.FromJson<WebConfiguration>(json);
        }
        catch (System.Exception ex)
        {
            // Print the error message to the console
            Debug.LogError(ex.Message);
        }
    }

    bool HasConfigFileChanged()
    {
        // Get the last modified time of the file
        string jsonPath = Path.Combine(Application.streamingAssetsPath, "config.json");
        var lastModifiedTime = File.GetLastWriteTime(jsonPath);

        // Check if the last modified time is different from the time when we last read the file
        if (lastModifiedTime != lastReadTime)
        {
            // Update the lastReadTime to the current time
            lastReadTime = lastModifiedTime;

            // Return true to indicate that the file has changed
            return true;
        }

        // Return false if the file has not changed
        return false;
    }
}


问:
*Modern* CollectionView. Waterfall effect? (I.e. Is dynamic cell height / staggering for MULTIPLE columns possible?)

Goal:

UICollectionView with 'waterfall effect', entailing:

Multiple columns of cells (each cell contains only one stackview).

Each stackview contains n items, thus height of cells varies, but width is fixed.

Each cell in each column should butt up against one above it, with fixed padding, let's say CGFloat(50.0).

That produces a 'staggered' look across the columns, but no wasted space or 'empty slots'.

The Problem:

I've tried configuring the collection view using UICollectionViewFlowLayout,  and alternatively, UICollectionViewCompositionalLayout without success
Best I've been able to achieve is cells aligned to top of each row, where each row has a uniform height (approx same height as tallest cell in that row). Meaning, next row starts below the bottom of the tallest cell in the previous row, leaving large gaps between shorter cells and cells placed cells in the next row (which is what I don't want).

Afterthoughts:

I suspect that's just how it is... that collection view (particularly compositional layout) doesn't know how to handle multiple columns with independent vertical layouts wherein all columns scroll vertically as one.

I'm not even sure if a custom layout could solve it, as I've never written one yet. Or if I'm just better off creating a big scroll view and layout the stackviews manually without a collection view, or multiple single-column collection views side by side?  I don't understand enough of the tradeoffs and possibilities and hoping someone can steer me in the right direction.

Note, I did find this cool hack for making the content of cells top align for UICollectionViewFlow layout, and it works for what it is, but doesn't but doesn't give me the waterfall effect I'm looking e.g. doesn't tie multiple rows together for a seamless vertically sized cell height appearance.

UICollection View Flow Layout Vertical Align

```<code>class TopAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        // This method is being requested to return the layout attributes for each cell in the rectangle.'
        // where the attributes are frame, bounds, center, size, transform3D, transform, alpha, zIndix and isHidden

        // It starts by getting a copy attributes the super class has configured each cell:
        //
        let attributes = super.layoutAttributesForElements(in: rect)?.map { $0.copy() } as? [UICollectionViewLayoutAttributes]

        attributes?
            // Then it's using the reduce() function to build a new dictionary of tupples consisting of:
            // [cgfloat : (cgfloat, [attrs])], which is [ cell center.y : (cell origin.y, [all the other cells]) ]
        ///
            .reduce([CGFloat: (CGFloat, [UICollectionViewLayoutAttributes])]()) { // for each cell, $0 = dict to build, $1 = next cell
                guard $1.representedElementCategory == .cell else { return $0 }   // only operate on cells (not decorations or supplemental views)
                return $0.merging([ceil($1.center.y): ($1.frame.origin.y, [$1])]) { // center.y : origin.y, [merged attributes]
                    ($0.0 < $1.0 ? $0.0 : $1.0, $0.1 + $1.1)
                        //
                        // if dict center.y < cell center.y
                        //    (cell ctr.y, [cell/dict merged attributes]
                        // else
                        //    (dict ctr.y, [cell/dict merged attributes]

                }
            } // returns dictionary of merged [cgfloat : (cgfloat, [attrs])]
            .values.forEach { minY, line in // pull each item up to the top via diff btw center and top line
                line.forEach {
                    $0.frame = $0.frame.offsetBy(
                        dx: 0,
                        dy: minY - $0.frame.origin.y
                    )
                    $0.frame = CGRectMake($0.frame.origin.x, $0.frame.origin.y + 200, $0.frame.size.width, 50) //$0.frame.size.height - (minY - $0.frame.origin.y))
                }
            }

        return attributes
    }
}
</code>```

Body:
Goal:

UICollectionView with 'waterfall effect', entailing:

Multiple columns of cells (each cell contains only one stackview).

Each stackview contains n items, thus height of cells varies, but width is fixed.

Each cell in each column should butt up against one above it, with fixed padding, let's say CGFloat(50.0).

That produces a 'staggered' look across the columns, but no wasted space or 'empty slots'.

The Problem:

I've tried configuring the collection view using UICollectionViewFlowLayout,  and alternatively, UICollectionViewCompositionalLayout without success
Best I've been able to achieve is cells aligned to top of each row, where each row has a uniform height (approx same height as tallest cell in that row). Meaning, next row starts below the bottom of the tallest cell in the previous row, leaving large gaps between shorter cells and cells placed cells in the next row (which is what I don't want).

Afterthoughts:

I suspect that's just how it is... that collection view (particularly compositional layout) doesn't know how to handle multiple columns with independent vertical layouts wherein all columns scroll vertically as one.

I'm not even sure if a custom layout could solve it, as I've never written one yet. Or if I'm just better off creating a big scroll view and layout the stackviews manually without a collection view, or multiple single-column collection views side by side?  I don't understand enough of the tradeoffs and possibilities and hoping someone can steer me in the right direction.

Note, I did find this cool hack for making the content of cells top align for UICollectionViewFlow layout, and it works for what it is, but doesn't but doesn't give me the waterfall effect I'm looking e.g. doesn't tie multiple rows together for a seamless vertically sized cell height appearance.

UICollection View Flow Layout Vertical Align

class TopAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        // This method is being requested to return the layout attributes for each cell in the rectangle.'
        // where the attributes are frame, bounds, center, size, transform3D, transform, alpha, zIndix and isHidden

        // It starts by getting a copy attributes the super class has configured each cell:
        //
        let attributes = super.layoutAttributesForElements(in: rect)?.map { $0.copy() } as? [UICollectionViewLayoutAttributes]

        attributes?
            // Then it's using the reduce() function to build a new dictionary of tupples consisting of:
            // [cgfloat : (cgfloat, [attrs])], which is [ cell center.y : (cell origin.y, [all the other cells]) ]
        ///
            .reduce([CGFloat: (CGFloat, [UICollectionViewLayoutAttributes])]()) { // for each cell, $0 = dict to build, $1 = next cell
                guard $1.representedElementCategory == .cell else { return $0 }   // only operate on cells (not decorations or supplemental views)
                return $0.merging([ceil($1.center.y): ($1.frame.origin.y, [$1])]) { // center.y : origin.y, [merged attributes]
                    ($0.0 < $1.0 ? $0.0 : $1.0, $0.1 + $1.1)
                        //
                        // if dict center.y < cell center.y
                        //    (cell ctr.y, [cell/dict merged attributes]
                        // else
                        //    (dict ctr.y, [cell/dict merged attributes]

                }
            } // returns dictionary of merged [cgfloat : (cgfloat, [attrs])]
            .values.forEach { minY, line in // pull each item up to the top via diff btw center and top line
                line.forEach {
                    $0.frame = $0.frame.offsetBy(
                        dx: 0,
                        dy: minY - $0.frame.origin.y
                    )
                    $0.frame = CGRectMake($0.frame.origin.x, $0.frame.origin.y + 200, $0.frame.size.width, 50) //$0.frame.size.height - (minY - $0.frame.origin.y))
                }
            }

        return attributes
    }
}


问:
Issue with Google Font API
I can't get my Google Font API to bring up the font I'm selecting. Got the links straight from Google, CSS seems right, but no joy. Am I doing something wrong?

HTML:

h1 {
  font-family: "Montserrat", sans-serif;
  size: 3rem;
  line-height: 1.5;
  font-weight: 900;
}
title {
  font-family: "Ubuntu", sans-serif;
  size: 1rem;
  font-weight: 300;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="utf-8">
  <title>TinDog</title>

  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

  <!-- Google Font API -->
  <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;700;900&family=Ubuntu:wght@300;400;700&display=swap" rel="stylesheet">
  <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;700;900&family=Ubuntu:wght@300;400;700&display=swap'); </style>

  <!-- CSS Connection -->
  <link rel="stylesheet" href="css/styles.css">

</head>
<body>

<h1>Heading H1</h1>

</body>
</html></code>```

Tried changing the quotations from " to ' and even `. Tried changing the name of the font to Montserrat-black, tried all sorts of solutions around the internet.

Title: Issue with Google Font API

Body:
I can't get my Google Font API to bring up the font I'm selecting. Got the links straight from Google, CSS seems right, but no joy. Am I doing something wrong?

HTML:

h1 {
  font-family: "Montserrat", sans-serif;
  size: 3rem;
  line-height: 1.5;
  font-weight: 900;
}
title {
  font-family: "Ubuntu", sans-serif;
  size: 1rem;
  font-weight: 300;
}

  <meta charset="utf-8">
  <title>TinDog</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

  <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;700;900&family=Ubuntu:wght@300;400;700&display=swap" rel="stylesheet">

  <link rel="stylesheet" href="css/styles.css">

Heading H1

Tried changing the quotations from " to ' and even `. Tried changing the name of the font to Montserrat-black, tried all sorts of solutions around the internet.


问:
CVXPY: Equality Norm Constraints
I am confused with my constraints. I have a matrix variable with size [8,2] and two norm constraints cp.norm(V[:,0])**2==5 and cp.norm(V[:,1])**2==5. But there is a error said that :

DCPError: Problem does not follow DCP rules. Specifically:
The following constraints are not DCP:
Pnorm(var5258[0:8, 0], 2) == 5.0 , because the following subexpressions are not:
|-- Pnorm(var5258[0:8, 0], 2) == 5.0
power(Pnorm(var5258[0:8, 1], 2), 2.0) == 5.0 , because the following subexpressions are not:
|-- power(Pnorm(var5258[0:8, 1], 2), 2.0) == 5.0

I do not know why and could someone helps me?
Thanks a lot!

Pei

I read the DCP rules about equality but do not know where I did not follow the rules.

Title: CVXPY: Equality Norm Constraints


问:
Docker: Error response from daemon: driver failed programming external connectivity
So I am trying to run searxng in a docker container, but it just loads a blank page. Running docker-compose logs -f searxng spits out the following:

```<code>searxng  | Traceback (most recent call last):
searxng  |   File "/usr/local/searxng/searx/search/processors/abstract.py", line 75, in initialize
searxng  |     self.engine.init(get_engine_from_settings(self.engine_name))
searxng  |   File "/usr/local/searxng/searx/engines/zlibrary.py", line 39, in init
searxng  |     resp = http_get('https://z-lib.org', timeout=5.0)
searxng  |   File "/usr/local/searxng/searx/network/__init__.py", line 165, in get
searxng  |     return request('get', url, **kwargs)
searxng  |   File "/usr/local/searxng/searx/network/__init__.py", line 96, in request
searxng  |     return future.result(timeout)
searxng  |   File "/usr/lib/python3.10/concurrent/futures/_base.py", line 446, in result
searxng  |     return self.__get_result()
searxng  |   File "/usr/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result
searxng  |     raise self._exception
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 291, in request
searxng  |     return await self.call_client(False, method, url, **kwargs)
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 287, in call_client
searxng  |     raise e
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 272, in call_client
searxng  |     response = await client.request(method, url, **kwargs)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1513, in request
searxng  |     return await self.send(request, auth=auth, follow_redirects=follow_redirects)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1600, in send
searxng  |     response = await self._send_handling_auth(
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1628, in _send_handling_auth
searxng  |     response = await self._send_handling_redirects(
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1665, in _send_handling_redirects
searxng  |     response = await self._send_single_request(request)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1702, in _send_single_request
searxng  |     response = await transport.handle_async_request(request)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_transports/default.py", line 307, in handle_async_request
searxng  |     with map_httpcore_exceptions():
searxng  |   File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
searxng  |     self.gen.throw(typ, value, traceback)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
searxng  |     raise mapped_exc(message) from exc
searxng  | httpx.ConnectTimeout
</code>```

I'm running this on arch linux, maybe that could have something to do with it. Here is also my neofetch output:

```<code>- OS: Arch Linux x86_64
- Host: 81YM IdeaPad 5 14ARE05
- Kernel: 5.15.82-1-lts
- Packages: 1426 (pacman), 32 (flatpak)
- Shell: bash 5.1.16
- DE: GNOME 43.2
- CPU: AMD Ryzen 5 4600U with Radeon Graphics (12) @ 2.100GHz
- GPU: AMD ATI 04:00.0 Renoir
- Memory: 8790MiB / 15364MiB
</code>```

I followed all the steps for the installation, as well as following the 'How to use it' Link with no errors.

Running the command docker-compose up -d starts the containers without error, but trying to access localhost or 127.0.0.1 or 127.0.0.1:8080:8080 (as it states in the docker-compose.yaml file)

Body:
So I am trying to run searxng in a docker container, but it just loads a blank page. Running docker-compose logs -f searxng spits out the following:

searxng  | Traceback (most recent call last):
searxng  |   File "/usr/local/searxng/searx/search/processors/abstract.py", line 75, in initialize
searxng  |     self.engine.init(get_engine_from_settings(self.engine_name))
searxng  |   File "/usr/local/searxng/searx/engines/zlibrary.py", line 39, in init
searxng  |     resp = http_get('https://z-lib.org', timeout=5.0)
searxng  |   File "/usr/local/searxng/searx/network/__init__.py", line 165, in get
searxng  |     return request('get', url, **kwargs)
searxng  |   File "/usr/local/searxng/searx/network/__init__.py", line 96, in request
searxng  |     return future.result(timeout)
searxng  |   File "/usr/lib/python3.10/concurrent/futures/_base.py", line 446, in result
searxng  |     return self.__get_result()
searxng  |   File "/usr/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result
searxng  |     raise self._exception
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 291, in request
searxng  |     return await self.call_client(False, method, url, **kwargs)
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 287, in call_client
searxng  |     raise e
searxng  |   File "/usr/local/searxng/searx/network/network.py", line 272, in call_client
searxng  |     response = await client.request(method, url, **kwargs)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1513, in request
searxng  |     return await self.send(request, auth=auth, follow_redirects=follow_redirects)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1600, in send
searxng  |     response = await self._send_handling_auth(
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1628, in _send_handling_auth
searxng  |     response = await self._send_handling_redirects(
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1665, in _send_handling_redirects
searxng  |     response = await self._send_single_request(request)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_client.py", line 1702, in _send_single_request
searxng  |     response = await transport.handle_async_request(request)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_transports/default.py", line 307, in handle_async_request
searxng  |     with map_httpcore_exceptions():
searxng  |   File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
searxng  |     self.gen.throw(typ, value, traceback)
searxng  |   File "/usr/lib/python3.10/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
searxng  |     raise mapped_exc(message) from exc
searxng  | httpx.ConnectTimeout

I'm running this on arch linux, maybe that could have something to do with it. Here is also my neofetch output:

- OS: Arch Linux x86_64
- Host: 81YM IdeaPad 5 14ARE05
- Kernel: 5.15.82-1-lts
- Packages: 1426 (pacman), 32 (flatpak)
- Shell: bash 5.1.16
- DE: GNOME 43.2
- CPU: AMD Ryzen 5 4600U with Radeon Graphics (12) @ 2.100GHz
- GPU: AMD ATI 04:00.0 Renoir
- Memory: 8790MiB / 15364MiB

I followed all the steps for the installation, as well as following the 'How to use it' Link with no errors.

Running the command docker-compose up -d starts the containers without error, but trying to access localhost or 127.0.0.1 or 127.0.0.1:8080:8080 (as it states in the docker-compose.yaml file)


问:
How can I output Math.php in PHP?
Warning: include(Math.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\php ModulesAndNamespaces\php modules & namespaces.php on line 13

<?php
// modules-> divide and reuse codes
    //Math.php
    define( 'PI', 3.14);

    function add($a,$b) {
        echo $a+$b;
    }
?>
<?php
    //App.php
    include ('Math.php');
    echo PI;// 3.14
    echo add(1,2);//3
?>
```

Why do I get this error, and how can the problem be fixed?

Title: How can I output Math.php in PHP?

Body:
Warning: include(Math.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\php ModulesAndNamespaces\php modules & namespaces.php on line 13

<?php
// modules-> divide and reuse codes
    //Math.php
    define( 'PI', 3.14);

    function add($a,$b) {
        echo $a+$b;
    }
?>
<?php
    //App.php
    include ('Math.php');
    echo PI;// 3.14
    echo add(1,2);//3
?>

Why do I get this error, and how can the problem be fixed?


问:
How do I inject a file into a Netlify deploy from Github to avoid using git-lfs?
I have a Netlify site that deploys from Github. The problem is that it contains a WebGL Unity game which has a pretty big .data file. The file is bigger than 100MB so it would need to be storged in Github's LFS. I don't want to use Github LFS so is there a way to store this file in an external link like Google Drive or Dropbox or something like that and inject it into the deploy at build time?


问:
gapi.client.getToken() always return null when refresh ReactJS app
So I am making a React app that accesses the user's Google calendar and fetch their events.

It is working fine, but the problem is that when I refresh the app, the user has to consent again, which I would like to avoid.

Is there a way for me to skip the consent, after the first time the user consent already?

On user click to log in

```<code>function handleAuthClick() {
    tokenClient.callback = async (resp) => {
      if (resp.error !== undefined) {
        throw (resp);
      }
    };

  if (gapi.client.getToken() === null) {
    // Prompt the user to select a Google Account and ask for consent to share their data
    // when establishing a new session.
    tokenClient.requestAccessToken({prompt: 'consent', access_type:"offline"});
  } else {
    // Skip display of account chooser and consent dialog for an existing session.
    tokenClient.requestAccessToken({prompt: ''});
  }
}

</code>```

Some other function that is used to log in that I copy from google's documentation

```<code>function gapiLoaded() {
    try{
      gapi.load('client', intializeGapiClient);
    } catch {
      console.log("Not Logged in");
    }
}

/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function intializeGapiClient() {
  var API_KEY = "x";

  fetch("http://localhost:5050/id").then(resp => {
  // fetch("https://calendar-342103.uc.r.appspot.com/id").then(resp => {
    return resp.json();
  }).then((data) => {
    API_KEY = data.val2;
  }).then(async () => {
    try{
      await gapi.client.init({
      apiKey: API_KEY,
      discoveryDocs: [DISCOVERY_DOC],
      });
      gapiInited = true;
      maybeEnableButtons();
    } catch {
      console.log("User not logged in")
    }
  })
}

/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
  var CLIENT_ID = "x";

  fetch("http://localhost:5050/id").then(resp => {
  // fetch("https://calendar-342103.uc.r.appspot.com/id").then(resp => {
    return resp.json();
  }).then((data) => {
    CLIENT_ID = data.val1;
  }).then(() => {
    try {
      tokenClient = google.accounts.oauth2.initTokenClient({
      client_id: CLIENT_ID,
      scope: SCOPES,
      callback: '', // defined later
      });
      gisInited = true;
      maybeEnableButtons();
    } catch {

    }
  })
}
</code>```

Body:
So I am making a React app that accesses the user's Google calendar and fetch their events.

It is working fine, but the problem is that when I refresh the app, the user has to consent again, which I would like to avoid.

Is there a way for me to skip the consent, after the first time the user consent already?

On user click to log in

function handleAuthClick() {
    tokenClient.callback = async (resp) => {
      if (resp.error !== undefined) {
        throw (resp);
      }
    };

  if (gapi.client.getToken() === null) {
    // Prompt the user to select a Google Account and ask for consent to share their data
    // when establishing a new session.
    tokenClient.requestAccessToken({prompt: 'consent', access_type:"offline"});
  } else {
    // Skip display of account chooser and consent dialog for an existing session.
    tokenClient.requestAccessToken({prompt: ''});
  }
}

Some other function that is used to log in that I copy from google's documentation

function gapiLoaded() {
    try{
      gapi.load('client', intializeGapiClient);
    } catch {
      console.log("Not Logged in");
    }
}

/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function intializeGapiClient() {
  var API_KEY = "x";

  fetch("http://localhost:5050/id").then(resp => {
  // fetch("https://calendar-342103.uc.r.appspot.com/id").then(resp => {
    return resp.json();
  }).then((data) => {
    API_KEY = data.val2;
  }).then(async () => {
    try{
      await gapi.client.init({
      apiKey: API_KEY,
      discoveryDocs: [DISCOVERY_DOC],
      });
      gapiInited = true;
      maybeEnableButtons();
    } catch {
      console.log("User not logged in")
    }
  })
}

/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
  var CLIENT_ID = "x";

  fetch("http://localhost:5050/id").then(resp => {
  // fetch("https://calendar-342103.uc.r.appspot.com/id").then(resp => {
    return resp.json();
  }).then((data) => {
    CLIENT_ID = data.val1;
  }).then(() => {
    try {
      tokenClient = google.accounts.oauth2.initTokenClient({
      client_id: CLIENT_ID,
      scope: SCOPES,
      callback: '', // defined later
      });
      gisInited = true;
      maybeEnableButtons();
    } catch {

    }
  })
}


问:
Is there a way in CMake to tell Visual Studio to compile parallel runtime decencies that are not directly compile dependent?
I want to set up a Visual Studio solution configuration through cmake where Application A and Application B depends on C, D, and E shared libraries that are loaded at runtime.

These must all be compiled before either A or B can run, but none of these are compile dependent on each other in any way.  They may share common dependencies further down (like a shared interface that came from yet another library "Z") but this should not have an impact about what I am describing.

All of A through E should be allowed to be compiled in parallel for the best build time result.  The libraries only requirement is that they have been compiled and be up to date with code changes when A or B is built and launched for debugging.

Is this type of relationship possible though cmake?

I've tried add_dependency, but this seems to stop A or B from compiling until after all of C D and E are finished, which wastes time.


问:
I keep getting an error whenever I have tried to start up lavalink
I downloaded lavalink in the same folder that I have my project and I have the application.yml code all correct. I still keep getting the error of

```<code>java : The term 'java' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ java -jar Lavalink.jar
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (java:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

</code>```

If you guys need to see any other pieces of code I would happily show you.

I tried downloading the latest version of Java from Oracle. I have put the two files in the same project folder. I have matched the ports in both my main project folder and the application folder.

Body:
I downloaded lavalink in the same folder that I have my project and I have the application.yml code all correct. I still keep getting the error of

java : The term 'java' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ java -jar Lavalink.jar
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (java:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

If you guys need to see any other pieces of code I would happily show you.

I tried downloading the latest version of Java from Oracle. I have put the two files in the same project folder. I have matched the ports in both my main project folder and the application folder.


问:
Why can't field be added to ModelForm in __init__() in Django 1.3
I have a ModelForm with a dynamically added field.  It stopped working when I switched from Django 1.2 to Django 1.3.  The following code is a minimal version which recreates the issue.

```<code>class MyModel(models.Model):
    rank = models.IntegerField()

    def __unicode__(self):
        return "{}".format(self.rank)

class MyModelAdminForm(forms.ModelForm):
    #dummy = forms.NullBooleanField()

    def __init__(self, *args, **kwargs):
        super(MyModelAdminForm, self).__init__(*args, **kwargs)
        self.fields['dummy'] = forms.BooleanField()
        self.fields['dummy'].required = False
        self.Meta.fields.append('dummy')

    class Meta:
        fields = ['rank']
</code>```

The 'dummy' declaration which is commented out isn't needed when running under Django 1.2, everything can be done dynamically in init().  In Django 1.3 the same code gives an error:

```<code>FieldError: Unknown field(s) (dummy) specified for MyModel
</code>```

Which can be fixed by adding the commented-out declaration.

I couldn't find anything in the docs that suggest a backwards-incompatible change that would cause this.  Anyone know what's going on here?

ContentLicense: CC BY-SA 3.0

Body:
I have a ModelForm with a dynamically added field.  It stopped working when I switched from Django 1.2 to Django 1.3.  The following code is a minimal version which recreates the issue.

class MyModel(models.Model):
    rank = models.IntegerField()

    def __unicode__(self):
        return "{}".format(self.rank)

class MyModelAdminForm(forms.ModelForm):
    #dummy = forms.NullBooleanField()

    def __init__(self, *args, **kwargs):
        super(MyModelAdminForm, self).__init__(*args, **kwargs)
        self.fields['dummy'] = forms.BooleanField()
        self.fields['dummy'].required = False
        self.Meta.fields.append('dummy')

    class Meta:
        fields = ['rank']

The 'dummy' declaration which is commented out isn't needed when running under Django 1.2, everything can be done dynamically in init().  In Django 1.3 the same code gives an error:

FieldError: Unknown field(s) (dummy) specified for MyModel

Which can be fixed by adding the commented-out declaration.

I couldn't find anything in the docs that suggest a backwards-incompatible change that would cause this.  Anyone know what's going on here?


问:
watchOS: How to respond to app being opened via an intent?
I've successfully added a StartWorkoutIntent to my watch app for when the action button is pressed, however I need to be notified when the app was opened via the intent.    Apple's docs say to implement this handle function below which I have in my Extension Delegate, however when you press the action button it is never called?

```<code>  func handle(startWorkout intent: INStartWorkoutIntent,
           completion: @escaping (INStartWorkoutIntentResponse) -> Void) {
        print("WE are called!")
        // Let the app start the workout.
        let response = INStartWorkoutIntentResponse(code: .continueInApp,
                 userActivity: nil)
        completion(response)
    }
</code>```

This never gets called either:

```<code> func handle(_ userActivity: NSUserActivity) {

         if userActivity.activityType == "Start Workout" {
             print("Handle Start Workout called")
         }
    }
</code>```

Body:
I've successfully added a StartWorkoutIntent to my watch app for when the action button is pressed, however I need to be notified when the app was opened via the intent.    Apple's docs say to implement this handle function below which I have in my Extension Delegate, however when you press the action button it is never called?

  func handle(startWorkout intent: INStartWorkoutIntent,
           completion: @escaping (INStartWorkoutIntentResponse) -> Void) {
        print("WE are called!")
        // Let the app start the workout.
        let response = INStartWorkoutIntentResponse(code: .continueInApp,
                 userActivity: nil)
        completion(response)
    }

This never gets called either:

 func handle(_ userActivity: NSUserActivity) {

         if userActivity.activityType == "Start Workout" {
             print("Handle Start Workout called")
         }
    }