问:
Iterate over two strings checking to see if it matches with its pair
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

```<code>    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }
</code>```

'''

答:
First you must find out which string is the shortest in length. Also you need to get the length difference when calculating the shortest string. After that, use that length as a terminating condition in your for loop. You can use booleans to check whether the values are present before incrementing the counter with an if statement.

The absolute value of any number can be obtained by calling the static method abs() from the Math class. Last, just add the mismatchCounts to the absolute value of the length difference in order to obtain the result.

Here is my solution.

```<code>public class App {

public static void main(String[] args) throws Exception {
    String seq1 = "TTCGATGGAGCTGTA";
    String seq2 = "TAGCTAGCTCGGCATGA";
    System.out.println(compareStrings(seq1, seq2));
}

public static int compareStrings(String stringOne, String stringTwo) {
    Character A = 'A', T = 'T', G = 'G', C = 'C';
    int mismatchCount = 0;
    int lowestStringLenght = 0;
    int length_one = stringOne.length();
    int length_two = stringTwo.length();
    int lenght_difference = 0;

    if (length_one < length_two) {// string one lenght is greater
        lowestStringLenght = length_one;
        lenght_difference = length_one - length_two;
    } else if (length_one > length_two) {// string two lenght is greater
        lowestStringLenght = length_two;
        lenght_difference = length_two - length_one;
    } else { // lenghts must be equal, use either
        lowestStringLenght = length_one;
        lenght_difference = 0; // there is no difference because they are equal
    }

    for (int i = 0; i < lowestStringLenght; i++) {
        // A matches with T
        // G matches with C
        // evaluate if the values A, T, G, C are present
        boolean A_T_PRESENT = stringOne.charAt(i) == A && stringTwo.charAt(i) == T;
        boolean G_C_PRESENT = stringOne.charAt(i) == G && stringTwo.charAt(i) == C;
        boolean T_A_PRESENT = stringOne.charAt(i) == T && stringTwo.charAt(i) == A;
        boolean C_G_PRESENT = stringOne.charAt(i) == C && stringTwo.charAt(i) == G;
        boolean TWO_EQUAL = stringOne.charAt(i) == stringTwo.charAt(i);

        // characters are equal, increase mismatch counter
        if (TWO_EQUAL) {
            mismatchCount++;
            continue;
        }
        // all booleans evaluated to false, it means that the characters are not proper
        // matches. Increment mismatchCount
        else if (!A_T_PRESENT && !G_C_PRESENT && !T_A_PRESENT && !C_G_PRESENT) {
            mismatchCount++;
            continue;
        } else {
            continue;
        }
    }
    // calculate the sum of the mismatches plus the abs of the lenght difference
    lenght_difference = Math.abs(lenght_difference);
    return mismatchCount + lenght_difference;
}
</code>```

}

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
First you must find out which string is the shortest in length. Also you need to get the length difference when calculating the shortest string. After that, use that length as a terminating condition in your for loop. You can use booleans to check whether the values are present before incrementing the counter with an if statement.

The absolute value of any number can be obtained by calling the static method abs() from the Math class. Last, just add the mismatchCounts to the absolute value of the length difference in order to obtain the result.

Here is my solution.

public class App {

public static void main(String[] args) throws Exception {
    String seq1 = "TTCGATGGAGCTGTA";
    String seq2 = "TAGCTAGCTCGGCATGA";
    System.out.println(compareStrings(seq1, seq2));
}

public static int compareStrings(String stringOne, String stringTwo) {
    Character A = 'A', T = 'T', G = 'G', C = 'C';
    int mismatchCount = 0;
    int lowestStringLenght = 0;
    int length_one = stringOne.length();
    int length_two = stringTwo.length();
    int lenght_difference = 0;

    if (length_one < length_two) {// string one lenght is greater
        lowestStringLenght = length_one;
        lenght_difference = length_one - length_two;
    } else if (length_one > length_two) {// string two lenght is greater
        lowestStringLenght = length_two;
        lenght_difference = length_two - length_one;
    } else { // lenghts must be equal, use either
        lowestStringLenght = length_one;
        lenght_difference = 0; // there is no difference because they are equal
    }

    for (int i = 0; i < lowestStringLenght; i++) {
        // A matches with T
        // G matches with C
        // evaluate if the values A, T, G, C are present
        boolean A_T_PRESENT = stringOne.charAt(i) == A && stringTwo.charAt(i) == T;
        boolean G_C_PRESENT = stringOne.charAt(i) == G && stringTwo.charAt(i) == C;
        boolean T_A_PRESENT = stringOne.charAt(i) == T && stringTwo.charAt(i) == A;
        boolean C_G_PRESENT = stringOne.charAt(i) == C && stringTwo.charAt(i) == G;
        boolean TWO_EQUAL = stringOne.charAt(i) == stringTwo.charAt(i);

        // characters are equal, increase mismatch counter
        if (TWO_EQUAL) {
            mismatchCount++;
            continue;
        }
        // all booleans evaluated to false, it means that the characters are not proper
        // matches. Increment mismatchCount
        else if (!A_T_PRESENT && !G_C_PRESENT && !T_A_PRESENT && !C_G_PRESENT) {
            mismatchCount++;
            continue;
        } else {
            continue;
        }
    }
    // calculate the sum of the mismatches plus the abs of the lenght difference
    lenght_difference = Math.abs(lenght_difference);
    return mismatchCount + lenght_difference;
}

}


来源: stackexchange

问:
How can I simplify this line of code using a common for loop rather than list expansion?
Take a look at the following piece of code:

```<code>def load_data_k(fname: str, yyy_index: int, **selection):
    selection_key_str = list(selection.keys())[0]
    selection_value_int = selection[selection_key_str]
    print(selection_value_int)
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(selection_value_int)]
</code>```

first please tell me why is it using next(file) here:

```<code>lines = [next(file) for _ in range(selection_value_int)]
</code>```

then please tell me how can I simplify this line using a normal for-loop rather than a list expansion.

答:
you could do

```<code>with open(fname) as file:
    lines = file.readlines()[:selection_value_int]
</code>```

though the entire file is read into memory

ContentLicense: CC BY-SA 4.0

Body:
Take a look at the following piece of code:

def load_data_k(fname: str, yyy_index: int, **selection):
    selection_key_str = list(selection.keys())[0]
    selection_value_int = selection[selection_key_str]
    print(selection_value_int)
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(selection_value_int)]

first please tell me why is it using next(file) here:

lines = [next(file) for _ in range(selection_value_int)]

then please tell me how can I simplify this line using a normal for-loop rather than a list expansion.

Body:
you could do

with open(fname) as file:
    lines = file.readlines()[:selection_value_int]

though the entire file is read into memory


问:
Executing SSIS package programmatically using C#
I writing to execute SSIS package using the application. I have written following code but it gives an error. the error is listed below the code.

```<code>        public void RunPackage()
    {
        string pkgLocation;
        Package pkg;
        Application app;
        DTSExecResult pkgResults;

        pkgLocation = @"C:\Users\EMISDb\Desktop\NEOC\EOC data need\NEOC_ETL\NEOC_ETL\obj\Development\99_Dash_WHO.dtsx";
        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);
        pkgResults = pkg.Execute();

    }
</code>```

error:

Retrieving the COM class factory for component with CLSID {4F0FC44B-C99C-4
  41D-B86A-D60D7E22143D} failed due to the following error: 80040154 Class not
  registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
  Description: An unhandled exception occurred during the execution of the
  current web request. Please review the stack trace for more information
  about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Retrieving
  the COM class factory for component with CLSID {4F0FC44B-C99C-441D-B86A-
  D60D7E22143D} failed due to the following error: 80040154 Class not
  registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

The error at the following line.

```<code>Line 27:             app = new Application();
</code>```

答:
I was also experiencing this error and installing SQL Server 2017 x64 Express with Advanced Services resolved the issue.

It installed C:\Program Files\Microsoft SQL Server\140\DTS\Binn\DTS.dll and registered the assembly Microsoft.SqlServer.DTSRuntimeWrap, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91 in
HKEY_CLASSES_ROOT\CLSID\{4F0FC44B-C99C-441D-B86A-D60D7E22143D}.

ContentLicense: CC BY-SA 3.0

Body:
I writing to execute SSIS package using the application. I have written following code but it gives an error. the error is listed below the code.

        public void RunPackage()
    {
        string pkgLocation;
        Package pkg;
        Application app;
        DTSExecResult pkgResults;

        pkgLocation = @"C:\Users\EMISDb\Desktop\NEOC\EOC data need\NEOC_ETL\NEOC_ETL\obj\Development\99_Dash_WHO.dtsx";
        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);
        pkgResults = pkg.Execute();

    }

error:

Retrieving the COM class factory for component with CLSID {4F0FC44B-C99C-4
  41D-B86A-D60D7E22143D} failed due to the following error: 80040154 Class not
  registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
  Description: An unhandled exception occurred during the execution of the
  current web request. Please review the stack trace for more information
  about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Retrieving
  the COM class factory for component with CLSID {4F0FC44B-C99C-441D-B86A-
  D60D7E22143D} failed due to the following error: 80040154 Class not
  registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

The error at the following line.

Line 27:             app = new Application();


问:
numpy: why don't my arrays have the same size after applying a mask intersection?
When I run .compressed() to turn a MaskedArray into a normal ndarray there are two fewer items. Any ideas why this could be?

```<code>mask_intersection = np.ma.mask_or(p_data.astype("float64"), cr_data.astype("float64"))

ipdb> mask_intersection.shape
(178, 163)
ipdb> p_data.shape
(178, 163)
ipdb> cr_data.shape
(178, 163)

ipdb> p_data[mask_intersection].flatten().size
16579
ipdb> cr_data[mask_intersection].compressed().size
16579
ipdb> mask_intersection.sum()
16579
ipdb> p_data[mask_intersection].compressed().size
16577 <-- wtf??

</code>```

no nans

```<code>ipdb> np.argwhere(np.isnan(cr_data[mask_intersection]))
array([], shape=(0, 1), dtype=int64)
ipdb> np.argwhere(np.isnan(p_data[mask_intersection]))
array([], shape=(0, 1), dtype=int64)
</code>```

Here is a copy of p_data https://filebin.net/ua0rn59wl1c2txac

```<code>import pickle
p_data = pickle.load(open("./p_data.obj", 'rb'))
</code>```

hmm this is also strange

```<code>ipdb> p_data[mask_intersection].shape
(16579,)
</code>```

am I applying the mask intersection correctly? I don't mind ending up with a 1d ndarray but the shape-transformation is a little unexpected

ooo interesting... not sure what this means

```<code>ipdb> cr_data[mask_intersection].mask.sum()
0
ipdb> p_data[mask_intersection].mask.sum()
2
</code>```

I wonder if what is happening is that p_data.mask is old so I need to do

```<code>p_data_smaller = p_data[mask_intersection]
p_data_smaller.mask = False
</code>```

or maybe I need to do

```<code>p_data.mask = mask_intersection
</code>```

instead

答:
The solution seems to be to overwrite the ma.mask instead of subsecting the ndarray.

# copy nodata from both rasters and intersect
mask_intersection = np.ma.mask_or(p_data.mask, cr_data.mask)
# flatten into 1d ndarray (not MaskedArray)
p_data.mask = mask_intersection
cr_data.mask = mask_intersection
p_data_c = p_data.compressed()
cr_data_c = cr_data.compressed()
```

Body:
When I run .compressed() to turn a MaskedArray into a normal ndarray there are two fewer items. Any ideas why this could be?

mask_intersection = np.ma.mask_or(p_data.astype("float64"), cr_data.astype("float64"))

ipdb> mask_intersection.shape
(178, 163)
ipdb> p_data.shape
(178, 163)
ipdb> cr_data.shape
(178, 163)

ipdb> p_data[mask_intersection].flatten().size
16579
ipdb> cr_data[mask_intersection].compressed().size
16579
ipdb> mask_intersection.sum()
16579
ipdb> p_data[mask_intersection].compressed().size
16577 <-- wtf??

no nans

ipdb> np.argwhere(np.isnan(cr_data[mask_intersection]))
array([], shape=(0, 1), dtype=int64)
ipdb> np.argwhere(np.isnan(p_data[mask_intersection]))
array([], shape=(0, 1), dtype=int64)

Here is a copy of p_data https://filebin.net/ua0rn59wl1c2txac

import pickle
p_data = pickle.load(open("./p_data.obj", 'rb'))

hmm this is also strange

ipdb> p_data[mask_intersection].shape
(16579,)

am I applying the mask intersection correctly? I don't mind ending up with a 1d ndarray but the shape-transformation is a little unexpected

ooo interesting... not sure what this means

ipdb> cr_data[mask_intersection].mask.sum()
0
ipdb> p_data[mask_intersection].mask.sum()
2

I wonder if what is happening is that p_data.mask is old so I need to do

p_data_smaller = p_data[mask_intersection]
p_data_smaller.mask = False

or maybe I need to do

p_data.mask = mask_intersection

instead


问:
Simplifying a function in R
I have functions like;

```<code>funtosimplify <- function(x){
    return(0.4 * (x[1] * 1 + x[2] * 1.4 - 3.5)^2 + 0.3 * (x[1] *
        1 + x[2] * 1.4 - 3)^2 + 0.2 * (x[1] * 1 + x[2] * 1.3 -
        3.2)^2 + 0.1 * (x[1] * 1 + x[2] * 1.5 - 3.1)^2)
}
</code>```

which should be;

```<code>funsimplified <- function(x){
    1 * x[1]^2 + 2.78 * x[1] * x[2] - 6.5 * x[1] + 1.935 * x[2]^2 - 9.034 * x[2] + 10.609
}
</code>```

I've checked the similar issues and tried mostly recommended package Ryacas but it doesn't work for huge functions, so here it's useless for me. How can we make it possible ?

Thanks in advance.

答:
1) Ryacas0 To use Ryacas0 create the original function which should be a single statement and with no brace brackets around the body nor return keyword.  Convert the body to character, replace x[i] with xi for all i, convert it to yacas using Sym, Simplify it, create a template for the result and convert the simplified expression to character, parse it and inject it into the body of the template.  In the example below f is the input and fs is the simplified output.

```<code>library(Ryacas0)

f <- function(x)
    0.4 * (x[1] * 1 + x[2] * 1.4 - 3.5)^2 + 0.3 * (x[1] *
        1 + x[2] * 1.4 - 3)^2 + 0.2 * (x[1] * 1 + x[2] * 1.3 -
        3.2)^2 + 0.1 * (x[1] * 1 + x[2] * 1.5 - 3.1)^2

txt <- deparse1(body(f))
txt2 <- gsub("x\\[(\\d)\\]", "x\\1", txt)
s <- Sym(txt2)
s2 <- Simplify(s)

fs <- function(x, x1 = x[1], x2 = x[2]) {}
body(fs) <- parse(text = as.character(s2))

fs
## function (x, x1 = x[1], x2 = x[2])
## 1 * x1^2 + (2.78 * (x1 * x2) - 6.5 * x1) + (1.935 * x2^2 - 9.034 *
##     x2 + 10.609)

f(1:2)
## [1] 0.341

fs(1:2)
## [1] 0.341
</code>```

2) Ryacas With Ryacas (as opposed to Ryacas0) it is the same except replace the lines that set s and s2 with

```<code>s <- ysym(txt2)
s2 <- simplify(s)
</code>```

3) mpoly Since f above is a multivariable polynomial we can use mpoly.  txt2 is from (1) above.

```<code>library(mpoly)

p <- mp(txt2, stars = TRUE)
fs2 <- as.function(p, varorder = sort(vars(p)))
fs2
## function(.) {.[1]**2+2.78*.[1]*.[2]-6.5*.[1]+1.935*.[2]**2-9.034*.[2]+10.609}

fs2(1:2)
## [1] 0.341
</code>```

Title: Simplifying a function in R

Body:
I have functions like;

funtosimplify <- function(x){
    return(0.4 * (x[1] * 1 + x[2] * 1.4 - 3.5)^2 + 0.3 * (x[1] *
        1 + x[2] * 1.4 - 3)^2 + 0.2 * (x[1] * 1 + x[2] * 1.3 -
        3.2)^2 + 0.1 * (x[1] * 1 + x[2] * 1.5 - 3.1)^2)
}

which should be;

funsimplified <- function(x){
    1 * x[1]^2 + 2.78 * x[1] * x[2] - 6.5 * x[1] + 1.935 * x[2]^2 - 9.034 * x[2] + 10.609
}

I've checked the similar issues and tried mostly recommended package Ryacas but it doesn't work for huge functions, so here it's useless for me. How can we make it possible ?

Thanks in advance.

Body:
1) Ryacas0 To use Ryacas0 create the original function which should be a single statement and with no brace brackets around the body nor return keyword.  Convert the body to character, replace x[i] with xi for all i, convert it to yacas using Sym, Simplify it, create a template for the result and convert the simplified expression to character, parse it and inject it into the body of the template.  In the example below f is the input and fs is the simplified output.

library(Ryacas0)

f <- function(x)
    0.4 * (x[1] * 1 + x[2] * 1.4 - 3.5)^2 + 0.3 * (x[1] *
        1 + x[2] * 1.4 - 3)^2 + 0.2 * (x[1] * 1 + x[2] * 1.3 -
        3.2)^2 + 0.1 * (x[1] * 1 + x[2] * 1.5 - 3.1)^2

txt <- deparse1(body(f))
txt2 <- gsub("x\\[(\\d)\\]", "x\\1", txt)
s <- Sym(txt2)
s2 <- Simplify(s)

fs <- function(x, x1 = x[1], x2 = x[2]) {}
body(fs) <- parse(text = as.character(s2))

fs
## function (x, x1 = x[1], x2 = x[2])
## 1 * x1^2 + (2.78 * (x1 * x2) - 6.5 * x1) + (1.935 * x2^2 - 9.034 *
##     x2 + 10.609)

f(1:2)
## [1] 0.341

fs(1:2)
## [1] 0.341

2) Ryacas With Ryacas (as opposed to Ryacas0) it is the same except replace the lines that set s and s2 with

s <- ysym(txt2)
s2 <- simplify(s)

3) mpoly Since f above is a multivariable polynomial we can use mpoly.  txt2 is from (1) above.

library(mpoly)

p <- mp(txt2, stars = TRUE)
fs2 <- as.function(p, varorder = sort(vars(p)))
fs2
## function(.) {.[1]**2+2.78*.[1]*.[2]-6.5*.[1]+1.935*.[2]**2-9.034*.[2]+10.609}

fs2(1:2)
## [1] 0.341


问:
How do I join on two columns from multiple csv files in neo4j?
This is my first time using neo4j and I have spent past 3.5 hours in figuring out on how to join two csv files.

sample_user contains

sample_order contains

Now I simply want for each user_id what were my top 2 products by timestamp(recency of timestamp). For that I am joining sample_user to sample_order on user_id to get the other info sample_order contains. Is that the correct approach?

I have tried this till now but nothing seems to work!

```<code>LOAD CSV with headers FROM 'file:///sample_users.csv' AS row with row where row.user_phone_number is not null
merge(n:user_id {Name:row.user_id})
merge(m:user_phone_number{Name:row.user_phone_number})
merge(l:location{Name:row.location})
with *
LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.distance}]->(o)
</code>```

Different sites offering different ways by using SET and define uniqueness. Please help!

UPDATE!!! I could merge on the same table like

```<code>LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row with order_row where  order_row.product is not null
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.order_id}]->(o)
</code>```

I just want to merge this order_row.user_id with other table's user_id too in order to get their first_name, location. Basically merge both the csv files.

答:
I found this somewhere,it may help

1.load all nodes in two commands (one command does not really work; first the people described in the first two columns and then the ones from the second two columns):

```<code>a) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person, number: row.Num_pers1}) b) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person2, number: row.Num_pers2})
</code>```

Connect the nodes:

```<code>a) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person, number: row.Num_pers1}) b) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person2, number: row.Num_pers2})
</code>```

You can then see all the connections from e.g. Marc:
MATCH (a {name: "Marc"})--(b) return a,b

Body:
This is my first time using neo4j and I have spent past 3.5 hours in figuring out on how to join two csv files.

sample_user contains

sample_order contains

Now I simply want for each user_id what were my top 2 products by timestamp(recency of timestamp). For that I am joining sample_user to sample_order on user_id to get the other info sample_order contains. Is that the correct approach?

I have tried this till now but nothing seems to work!

LOAD CSV with headers FROM 'file:///sample_users.csv' AS row with row where row.user_phone_number is not null
merge(n:user_id {Name:row.user_id})
merge(m:user_phone_number{Name:row.user_phone_number})
merge(l:location{Name:row.location})
with *
LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.distance}]->(o)

Different sites offering different ways by using SET and define uniqueness. Please help!

UPDATE!!! I could merge on the same table like

LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row with order_row where  order_row.product is not null
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.order_id}]->(o)

I just want to merge this order_row.user_id with other table's user_id too in order to get their first_name, location. Basically merge both the csv files.

Body:
I found this somewhere,it may help

1.load all nodes in two commands (one command does not really work; first the people described in the first two columns and then the ones from the second two columns):

a) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person, number: row.Num_pers1}) b) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person2, number: row.Num_pers2})

Connect the nodes:

a) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person, number: row.Num_pers1}) b) LOAD CSV WITH HEADERS FROM 'file:///FileName.csv' as row MERGE (a:Person {name: row.Person2, number: row.Num_pers2})

You can then see all the connections from e.g. Marc:
MATCH (a {name: "Marc"})--(b) return a,b


问:
Unable to access request.body from the endpoint.js in sveltekit skeleton project
After initiating a skeleton project from sveltekit app. my index has a form :

```<code><script>
    let name
    let password

    async function submitit(){
       // console.log("name is :", name)
       // console.log("password is :", password)

     const doit = async () =>{
        let res = await fetch( 'formdata' ,{
        method : "post",
        headers: {
        'Accept': 'application/json',
        'content-type' : 'text/html; charset=UTF-8',
        //'Content-Type': 'multipart/form-data'
        },
        body : JSON.stringify({
            name : "name",
            password : "password"
        })
    })// fetch
    let results =await res.json()
    console.log( "xxxxxxxxxxxxxxxxxxxxx"    , results )
    return results
    }

     doit().then(data =>{
         console.log("data log : " , data)
     })

    } //submitit

</script>

<form on:submit|preventDefault={submitit}>
    <p>
    <label>Name :
        <input type="text"  placeholder="name"   aria-label="name" required bind:value={name}>
    </label>
</p>
<p>
    <label>Password :
        <input type="password" placeholder="password"   aria-label="password" required  bind:value={password}>
    </label>
</p>
    <button type="submit">Submit</button>
</form>
</code>```

my endpoint formdata.js

```<code>export async function post(request) {

    console.log("formdata js log of request : ", request)

    return {

        status : 200,
        headers: {
            'content-type': 'application/json'
        },
        body : {
            message : "login form submitted the login credentials",
        }
    }

}
</code>```

When I click submit, the index.svelte returns the message "login form submitted the login credentials" and it is in the console.log of the browser.  The cmd which is used to run the application using npm run dev, logs the dataform.js request and prints the following :

```<code>formdata js log of request :  {
  request: Request {
    size: 0,
    follow: 20,
    compress: true,
    counter: 0,
    agent: undefined,
    highWaterMark: 16384,
    insecureHTTPParser: false,
    [Symbol(Body internals)]: {
      body: <Buffer 7b 22 6e 61 6d 65 22 3a 22 6e 61 6d 65 22 2c 22 70 61 73 73 77 6f 72 64 22 3a 22 70 61 73 73 77 6f 72 64 22 7d>,
      stream: [Readable],
      boundary: null,
      disturbed: false,
      error: null
    },
    [Symbol(Request internals)]: {
      method: 'POST',
      redirect: 'follow',
      headers: [Object],
      parsedURL: [URL],
      signal: null,
      referrer: undefined,
      referrerPolicy: ''
    }
  },
  url: URL {
    href: 'http://127.0.0.1:3000/formdata',
    origin: 'http://127.0.0.1:3000',
    protocol: 'http:',
    username: '',
    password: '',
    host: '127.0.0.1:3000',
    hostname: '127.0.0.1',
    port: '3000',
    pathname: '/formdata',
    search: '',
    searchParams: URLSearchParams {},
    hash: ''
  },
  params: {},
  locals: {},
  platform: undefined
}
</code>```

Notice the following:
1- there is no username or password fields in my form or the body json.stringify in the index.svelte but it is in the request log under the url section (both are empty despite the dummy text I entered in index.svelte)

2- body stream is readable. I indicated the application to accept/send json.

I also find this pr from Rich and have no idea if what I'm facing is because of this change. Here is the PR

I'm lost with this sveltekit. I had great experience with Sapper and I hope I could figure out sveltekit so I can go on and start developing my application but this is the first step in any application, process form data.

=================================================================

****************** update : Explain needed if possible *****************************
I still would like to understand how you got the event argument from this pr because in Rich's post, the code with + is the updated one. It doesn't mention event:

Updating endpoints
Similarly, handlers receive a RequestEvent. Most GET handlers will be unchanged, but any handler that needs to read the request body will need to update:

```<code>-export async function post({ params, body }) {
+export async function post({ params, request }) {
+ const body = await request.formData(); // or request.json(), etc
  await do_something_with(params, body);
  return { status: 201 };
}
</code>```

there is no mention in event anywhere. How did you get the keyword "event" as an argument for the function?

答:
Your endpoint should now look like this:

```<code>export async function post(event) {
    const data = await event.request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}
</code>```

Before the change linked in the PR you referenced, the argument to post was called request and you could access request.body. Now, the argument is called event and you can access event.request, which is a standard web request object. See the SvelteKit docs.

Your endpoint could also be written like this to automatically destructure the request property (note the additional curly brackets around request):

export async function post({ request }) {
    const data = await request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}
```

Body:
After initiating a skeleton project from sveltekit app. my index has a form :

<form on:submit|preventDefault={submitit}>

    Name :
        <input type="text"  placeholder="name"   aria-label="name" required bind:value={name}>

    Password :
        <input type="password" placeholder="password"   aria-label="password" required  bind:value={password}>

    <button type="submit">Submit</button>
</form>

my endpoint formdata.js

export async function post(request) {

    console.log("formdata js log of request : ", request)

    return {

        status : 200,
        headers: {
            'content-type': 'application/json'
        },
        body : {
            message : "login form submitted the login credentials",
        }
    }

}

When I click submit, the index.svelte returns the message "login form submitted the login credentials" and it is in the console.log of the browser.  The cmd which is used to run the application using npm run dev, logs the dataform.js request and prints the following :

formdata js log of request :  {
  request: Request {
    size: 0,
    follow: 20,
    compress: true,
    counter: 0,
    agent: undefined,
    highWaterMark: 16384,
    insecureHTTPParser: false,
    [Symbol(Body internals)]: {
      body: <Buffer 7b 22 6e 61 6d 65 22 3a 22 6e 61 6d 65 22 2c 22 70 61 73 73 77 6f 72 64 22 3a 22 70 61 73 73 77 6f 72 64 22 7d>,
      stream: [Readable],
      boundary: null,
      disturbed: false,
      error: null
    },
    [Symbol(Request internals)]: {
      method: 'POST',
      redirect: 'follow',
      headers: [Object],
      parsedURL: [URL],
      signal: null,
      referrer: undefined,
      referrerPolicy: ''
    }
  },
  url: URL {
    href: 'http://127.0.0.1:3000/formdata',
    origin: 'http://127.0.0.1:3000',
    protocol: 'http:',
    username: '',
    password: '',
    host: '127.0.0.1:3000',
    hostname: '127.0.0.1',
    port: '3000',
    pathname: '/formdata',
    search: '',
    searchParams: URLSearchParams {},
    hash: ''
  },
  params: {},
  locals: {},
  platform: undefined
}

Notice the following:
1- there is no username or password fields in my form or the body json.stringify in the index.svelte but it is in the request log under the url section (both are empty despite the dummy text I entered in index.svelte)

2- body stream is readable. I indicated the application to accept/send json.

I also find this pr from Rich and have no idea if what I'm facing is because of this change. Here is the PR

I'm lost with this sveltekit. I had great experience with Sapper and I hope I could figure out sveltekit so I can go on and start developing my application but this is the first step in any application, process form data.

=================================================================

****************** update : Explain needed if possible *****************************
I still would like to understand how you got the event argument from this pr because in Rich's post, the code with + is the updated one. It doesn't mention event:

Updating endpoints
Similarly, handlers receive a RequestEvent. Most GET handlers will be unchanged, but any handler that needs to read the request body will need to update:

-export async function post({ params, body }) {
+export async function post({ params, request }) {
+ const body = await request.formData(); // or request.json(), etc
  await do_something_with(params, body);
  return { status: 201 };
}

there is no mention in event anywhere. How did you get the keyword "event" as an argument for the function?

Body:
Your endpoint should now look like this:

export async function post(event) {
    const data = await event.request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}

Before the change linked in the PR you referenced, the argument to post was called request and you could access request.body. Now, the argument is called event and you can access event.request, which is a standard web request object. See the SvelteKit docs.

Your endpoint could also be written like this to automatically destructure the request property (note the additional curly brackets around request):

export async function post({ request }) {
    const data = await request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}


答:
This snippet:

```<code>lines = [next(file) for _ in range(selection_value_int)]
</code>```

expands to:

```<code>lines = []
for _ in range(selection_value_int):
    lines.append(next(file))
</code>```

However this doesn't simplify anything.

next(file) uses File object's generator behaviour
Thus loads some lines without getting whole file

Title: How can I simplify this line of code using a common for loop rather than list expansion?

Body:
This snippet:

lines = [next(file) for _ in range(selection_value_int)]

expands to:

lines = []
for _ in range(selection_value_int):
    lines.append(next(file))

However this doesn't simplify anything.

next(file) uses File object's generator behaviour
Thus loads some lines without getting whole file


问:
C# call method from C++ class
I'm trying to integrate with a windows based api using c-sharp and I've run into this issue.

The api sends me a pointer to a struct that holds a bunch of virtual methods

```<code>struct CApiInterface
{
   virtual int __stdcall Version(void);
   ...
}
</code>```

My question is, how can I call methods off this in C#? I'd like to do something like:

```<code>CApiInterface _api;

public void Start(CApiInterface* api)
{
_api = api;
}

...

public void SomeOtherMethod()
{
_api.version();
}
</code>```

I would like to stay out of CLI/C++ if at all possible, if this is even possible to begin with.

答: Check out this question for an example of someone else who did the same thing. It seems to revolve around using delegates marked with the UmanagedFunctionPointerAttribute.

Title: C# call method from C++ class

Body:
I'm trying to integrate with a windows based api using c-sharp and I've run into this issue.

The api sends me a pointer to a struct that holds a bunch of virtual methods

struct CApiInterface
{
   virtual int __stdcall Version(void);
   ...
}

My question is, how can I call methods off this in C#? I'd like to do something like:

CApiInterface _api;

public void Start(CApiInterface* api)
{
_api = api;
}

...

public void SomeOtherMethod()
{
_api.version();
}

I would like to stay out of CLI/C++ if at all possible, if this is even possible to begin with.


问:
SQL Error when I try to update an item using Dapper and Microsoft SQL Server
Picture with the error

```<code>    public bool UpdateDistrict(string name, int id,int primarySeller, string primarySellerName)
    {
        bool result = false;
        string connStr = @"Data Source=.;Initial Catalog=DataBase;Integrated Security=True";

        string sql = "UPDATE District" + " SET Name = @name, Id = @id, PrimSellerId = @primarySeller , PrimSellerName = @primarySellerName" +
            " WHERE Id = @id";
       var  district=GetDistrict(id);
        if(name==null || name=="")
        {
            name=district.Name;
        }

        using (var conn = new SqlConnection(connStr))
        {
            conn.Query(sql, new
            {
                Name = name,
                Id = id,
                PrimSellerId = primarySeller,
                PrimSellerName = primarySellerName,

            });
            result = true;
        }
        return result;
    }
</code>```

This is what I get as error when I try to update in the database

Microsoft.Data.SqlClient.SqlException: 'Must declare the scalar
variable "@primarySeller".

答:
To expand on the comment, when you write a query in SQL:

```<code>UPDATE District
SET
  Name = @name,
  Id = @id,
  PrimSellerId = @primarySeller ,
  PrimSellerName = @primarySellerName
WHERE Id = @id
</code>```

It is the parameter names (text after @) that should be specified in the anonymous type passed as the parameter arguments:

```<code>        new
        {
            name,
            id,
            primarySeller,
            primarySellerName,
        }
</code>```

In your SQL all your parameter names are the same as the c# variable names you use to make the anonymous type, so you can abbreviate the creation of the AT by just mentioning the variable names; the compiler will use them and the property names for the AT unless you're on an old version of .Net that doesn't support this (you'll find out), in which case you'll have to specify the column name too:

```<code>primarySeller = primarySeller
</code>```

If your names differ you'll need to ensure that the AT property names are matched to the SQL parameter names:

```<code>  conn.Query(
    "UPDATE t SET userAge = @u WHERE id = @i",
    new { u = 19, i = someId }
  );
</code>```

If you're running an update, insert, delete, merge (most things that aren't a select and don't produce rows of values, use Execute; it returns an integer of the number of rows affected, which you may want to utilise to indicate something didn't save:

```<code>int r = conn.Execute(...);
return r == 1;
</code>```

Body:
Picture with the error

    public bool UpdateDistrict(string name, int id,int primarySeller, string primarySellerName)
    {
        bool result = false;
        string connStr = @"Data Source=.;Initial Catalog=DataBase;Integrated Security=True";

        string sql = "UPDATE District" + " SET Name = @name, Id = @id, PrimSellerId = @primarySeller , PrimSellerName = @primarySellerName" +
            " WHERE Id = @id";
       var  district=GetDistrict(id);
        if(name==null || name=="")
        {
            name=district.Name;
        }

        using (var conn = new SqlConnection(connStr))
        {
            conn.Query(sql, new
            {
                Name = name,
                Id = id,
                PrimSellerId = primarySeller,
                PrimSellerName = primarySellerName,

            });
            result = true;
        }
        return result;
    }

This is what I get as error when I try to update in the database

Microsoft.Data.SqlClient.SqlException: 'Must declare the scalar
variable "@primarySeller".

Body:
To expand on the comment, when you write a query in SQL:

UPDATE District
SET
  Name = @name,
  Id = @id,
  PrimSellerId = @primarySeller ,
  PrimSellerName = @primarySellerName
WHERE Id = @id

It is the parameter names (text after @) that should be specified in the anonymous type passed as the parameter arguments:

        new
        {
            name,
            id,
            primarySeller,
            primarySellerName,
        }

In your SQL all your parameter names are the same as the c# variable names you use to make the anonymous type, so you can abbreviate the creation of the AT by just mentioning the variable names; the compiler will use them and the property names for the AT unless you're on an old version of .Net that doesn't support this (you'll find out), in which case you'll have to specify the column name too:

primarySeller = primarySeller

If your names differ you'll need to ensure that the AT property names are matched to the SQL parameter names:

  conn.Query(
    "UPDATE t SET userAge = @u WHERE id = @i",
    new { u = 19, i = someId }
  );

If you're running an update, insert, delete, merge (most things that aren't a select and don't produce rows of values, use Execute; it returns an integer of the number of rows affected, which you may want to utilise to indicate something didn't save:

int r = conn.Execute(...);
return r == 1;


问:
Flutter Circular Avatar background color while loading
I used two circular avatar (the first one with a white background just a little bigger to create a white border).
Also the second one have the background property set to white.
However before the image is loaded I see a blue background. As you can see form the code there are no one blu widget on the back...
I wold like to have a black or white background while the widget is loading the picture.</p>
```<code>return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        padding: const EdgeInsets.only(top: 30),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: appColor,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  width: 0,
                  height: 20,
                ),
                const Center(
                  child: Text(
                    'WhyBye ',
                    style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Savor',
                      fontSize: 40,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 0,
                  height: 10,
                ),
                Stack(
                  //& Stack contenente l'immagine del profilo.
                  children: [
                    _image != null
                        ? CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: MemoryImage(_image!),
                            ))
                        : CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: Variables.userPicUrl.isNotEmpty
                                  ? NetworkImage(Variables.userPicUrl)
                                  : null,
                            )),
                    Positioned(
                      //& All'interno del precedente Stack, posizionamento dei pulsanti immagine dalla galleria/fotocamera.
                      bottom: -10,
                      left: 15,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.gallery);
                        },
                        icon: const Icon(Icons.photo_library_rounded),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
                    Positioned(
                      bottom: -10,
                      left: 135,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.camera);
                        },
                        icon: const Icon(Icons.add_a_photo),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
</code>```

答:
Following the documentation of CircleAvatar:

If a backgroundColor is not specified, the theme's ThemeData.primaryColorLight is used with dark foreground colors, and ThemeData.primaryColorDark with light foreground colors.

I think you're using the default theme (which uses blue as primary color). Try to explicitly define s transparent color to the inner circle so while it's loading you only see the color of the outer circle

Body:
I used two circular avatar (the first one with a white background just a little bigger to create a white border).
Also the second one have the background property set to white.
However before the image is loaded I see a blue background. As you can see form the code there are no one blu widget on the back...
I wold like to have a black or white background while the widget is loading the picture.

return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        padding: const EdgeInsets.only(top: 30),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: appColor,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  width: 0,
                  height: 20,
                ),
                const Center(
                  child: Text(
                    'WhyBye ',
                    style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Savor',
                      fontSize: 40,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 0,
                  height: 10,
                ),
                Stack(
                  //& Stack contenente l'immagine del profilo.
                  children: [
                    _image != null
                        ? CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: MemoryImage(_image!),
                            ))
                        : CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: Variables.userPicUrl.isNotEmpty
                                  ? NetworkImage(Variables.userPicUrl)
                                  : null,
                            )),
                    Positioned(
                      //& All'interno del precedente Stack, posizionamento dei pulsanti immagine dalla galleria/fotocamera.
                      bottom: -10,
                      left: 15,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.gallery);
                        },
                        icon: const Icon(Icons.photo_library_rounded),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
                    Positioned(
                      bottom: -10,
                      left: 135,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.camera);
                        },
                        icon: const Icon(Icons.add_a_photo),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),


问:
DbFunctions, is a type which is not valid in the given context
I tried to use the SqlServerDbFunctionsExtensions.DateDiffDay but DbFunctions _ says

CS0119: DbFunctions is a type which is not valid in the given context

```<code>SqlServerDbFunctionsExtensions.DateDiffDay(this Microsoft.EntityFrameworkCore.DbFunctions _, DateTime.Now, i.Invoicedate) + i.ProductNav.GracePeriod.GetValueOrDefault()
</code>```

I also tried the following but i get the same error

```<code>SqlServerDbFunctionsExtensions.DateDiffDay(DbFunctions _, DateTime.Now, i.Invoicedate) + i.ProductNav.GracePeriod.GetValueOrDefault()
</code>```

答:
Take a look at these docs

Provides CLR methods that get translated to database functions when
used in LINQ to Entities queries. Calling these methods in other
contexts (e.g. LINQ to Objects) will throw a NotSupportedException.

You can only access it in linq to entity queries, you can't do what you're trying to do.

it's an extension method you can't pass it in.

```<code>public static int DateDiffDay (this Microsoft.EntityFrameworkCore.DbFunctions _, DateTime startDate, DateTime endDate);
</code>```

on DateDiffDay

you use it like this         DateDiffDay(starDate, EndDate) in the query

```<code>var allDaysDifferences = myEntities.Sum(r => EF.Functions.DateDiffDay(r.FromDate, r.ToDate));
</code>```

Body:
I tried to use the SqlServerDbFunctionsExtensions.DateDiffDay but DbFunctions _ says

CS0119: DbFunctions is a type which is not valid in the given context

SqlServerDbFunctionsExtensions.DateDiffDay(this Microsoft.EntityFrameworkCore.DbFunctions _, DateTime.Now, i.Invoicedate) + i.ProductNav.GracePeriod.GetValueOrDefault()

I also tried the following but i get the same error

SqlServerDbFunctionsExtensions.DateDiffDay(DbFunctions _, DateTime.Now, i.Invoicedate) + i.ProductNav.GracePeriod.GetValueOrDefault()

Body:
Take a look at these docs

Provides CLR methods that get translated to database functions when
used in LINQ to Entities queries. Calling these methods in other
contexts (e.g. LINQ to Objects) will throw a NotSupportedException.

You can only access it in linq to entity queries, you can't do what you're trying to do.

it's an extension method you can't pass it in.

public static int DateDiffDay (this Microsoft.EntityFrameworkCore.DbFunctions _, DateTime startDate, DateTime endDate);

on DateDiffDay

you use it like this         DateDiffDay(starDate, EndDate) in the query

var allDaysDifferences = myEntities.Sum(r => EF.Functions.DateDiffDay(r.FromDate, r.ToDate));


问:
Fyne testing: how do I test dialogs?
I want to make GUI testing, but investigation of test package and sources of fyne disappoints a lot.

Could somebody please tell, is there a way to fill text fields of a created dialog and click 'ok' and 'cancel' buttons to check results?

All docs I saw only suggest to move creating of form fields out to a func and check them out then individually, and, yes, that's an option, but is there a possibility to check it out as a complete dialog?

答:
Ok, I implemented an approach which does everything what I need.

@andy.xyz mb it would be useful to implement this out of the box.

Instead of calling dialog.NewForm directly I do this:

var newForm = dialog.NewForm
```
<p>and afterwards I call <code>newForm</code> with the same arguments, as follows:</p>
<pre class="lang-golang prettyprint-override"><code>    name := widget.NewEntry()
    eName := widget.NewFormItem("Name", name)
    active := widget.NewCheck()
    eActive := widget.NewFormItem("Active", active)
    d := newForm("A dialog", "OK", "Cancel", []*widget.FormItem{eName, eActive}, func(b bool) {}, w)
</code>```

A test looks like this:

    newForm = testNewForm

    assert.Equal(t, "A dialog", lastTestDialog.getTitle())
    assert.Equal(t, "OK", lastTestDialog.getConfirm())
    assert.Equal(t, "Cancel", lastTestDialog.getDismiss())

    lastTestDialog.setText(t, "Name", "some name")
    lastTestDialog.setCheck(t, "Active", true)
    lastTestDialog.tapOk()
    assert.Equal(t, false, lastTestDialog.isValid())
    // other checks
```
<p>And here's the code of the implementation:</p>
<pre class="lang-golang prettyprint-override"><code>package main

import (
    "fmt"
    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/dialog"
    "fyne.io/fyne/v2/widget"
    "testing"
)

type testDialog struct {
    title    string
    confirm  string
    dismiss  string
    widgets  map[string]fyne.CanvasObject
    callback func(bool)
    invalid  bool
}

func (d *testDialog) Show() {}

func (d *testDialog) Hide() {}

func (d *testDialog) SetDismissText(string) {}

func (d *testDialog) SetOnClosed(func()) {}

func (d *testDialog) Refresh() {}

func (d *testDialog) Resize(fyne.Size) {}

func (d *testDialog) MinSize() fyne.Size {
    return fyne.Size{}
}

func (d *testDialog) getTitle() string {
    return d.title
}

func (d *testDialog) getConfirm() string {
    return d.confirm
}

func (d *testDialog) getDismiss() string {
    return d.dismiss
}

func (d *testDialog) isValid() bool {
    return !d.invalid
}

func (d *testDialog) tapOk() {
    d.invalid = false
    for _, wi := range d.widgets {
        if w, ok := wi.(fyne.Validatable); ok {
            if e := w.Validate(); e != nil {
                d.invalid = true
                break
            }
        }
    }
    if !d.invalid {
        d.callback(true)
    }
}

func (d *testDialog) tapCancel() {
    d.callback(false)
}

func (d *testDialog) setText(t *testing.T, name string, text string) {
    wi, ok := d.widgets[name]
    if !ok {
        t.Fail()
        return
    }
    e, ok := wi.(*widget.Entry)
    if !ok {
        t.Fail()
        return
    }
    e.SetText(text)
}

func (d *testDialog) setCheck(t *testing.T, name string, check bool) {
    wi, ok := d.widgets[name]
    if !ok {
        t.Fail()
        return
    }
    c, ok := wi.(*widget.Check)
    if !ok {
        t.Fail()
        return
    }
    c.Checked = check
}

func (d *testDialog) tapButton(t *testing.T, name string) {
    t.Helper()
    wi, ok := d.widgets[name]
    if !ok {
        t.Errorf("there's no widget with name %s", name)
        return
    }
    b, ok := wi.(*widget.Button)
    if !ok {
        t.Errorf("widget '%s' isn't a button", name)
        return
    }
    b.OnTapped()
}

var lastTestDialog *testDialog = nil

func testNewForm(title, confirm, dismiss string, items []*widget.FormItem, callback func(bool), _ fyne.Window) dialog.Dialog {
    widgets := make(map[string]fyne.CanvasObject)
    for _, i := range items {
        widgetsForItem := digWidgets(i.Widget)
        l := len(widgetsForItem)
        if l < 1 {
            continue
        }
        if l == 1 {
            widgets[i.Text] = widgetsForItem[0]
            continue
        }
        for x, wi := range widgetsForItem {
            widgets[fmt.Sprintf("%s-%d", i.Text, x)] = wi
        }
    }
    lastTestDialog = &testDialog{title: title, confirm: confirm, dismiss: dismiss, widgets: widgets, callback: callback}
    return lastTestDialog
}

func digWidgets(root fyne.CanvasObject) []fyne.CanvasObject {
    if cnt, ok := root.(*fyne.Container); ok {
        var widgets []fyne.CanvasObject
        for _, o := range cnt.Objects {
            widgets = append(widgets, digWidgets(o)...)
        }
        return widgets
    }
    return []fyne.CanvasObject{root}
}
</code>```

Title: Fyne testing: how do I test dialogs?

Body:
Ok, I implemented an approach which does everything what I need.

@andy.xyz mb it would be useful to implement this out of the box.

Instead of calling dialog.NewForm directly I do this:

var newForm = dialog.NewForm

and afterwards I call newForm with the same arguments, as follows:

    name := widget.NewEntry()
    eName := widget.NewFormItem("Name", name)
    active := widget.NewCheck()
    eActive := widget.NewFormItem("Active", active)
    d := newForm("A dialog", "OK", "Cancel", []*widget.FormItem{eName, eActive}, func(b bool) {}, w)

A test looks like this:

    newForm = testNewForm

    assert.Equal(t, "A dialog", lastTestDialog.getTitle())
    assert.Equal(t, "OK", lastTestDialog.getConfirm())
    assert.Equal(t, "Cancel", lastTestDialog.getDismiss())

    lastTestDialog.setText(t, "Name", "some name")
    lastTestDialog.setCheck(t, "Active", true)
    lastTestDialog.tapOk()
    assert.Equal(t, false, lastTestDialog.isValid())
    // other checks

And here's the code of the implementation:

package main

import (
    "fmt"
    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/dialog"
    "fyne.io/fyne/v2/widget"
    "testing"
)

type testDialog struct {
    title    string
    confirm  string
    dismiss  string
    widgets  map[string]fyne.CanvasObject
    callback func(bool)
    invalid  bool
}

func (d *testDialog) Show() {}

func (d *testDialog) Hide() {}

func (d *testDialog) SetDismissText(string) {}

func (d *testDialog) SetOnClosed(func()) {}

func (d *testDialog) Refresh() {}

func (d *testDialog) Resize(fyne.Size) {}

func (d *testDialog) MinSize() fyne.Size {
    return fyne.Size{}
}

func (d *testDialog) getTitle() string {
    return d.title
}

func (d *testDialog) getConfirm() string {
    return d.confirm
}

func (d *testDialog) getDismiss() string {
    return d.dismiss
}

func (d *testDialog) isValid() bool {
    return !d.invalid
}

func (d *testDialog) tapOk() {
    d.invalid = false
    for _, wi := range d.widgets {
        if w, ok := wi.(fyne.Validatable); ok {
            if e := w.Validate(); e != nil {
                d.invalid = true
                break
            }
        }
    }
    if !d.invalid {
        d.callback(true)
    }
}

func (d *testDialog) tapCancel() {
    d.callback(false)
}

func (d *testDialog) setText(t *testing.T, name string, text string) {
    wi, ok := d.widgets[name]
    if !ok {
        t.Fail()
        return
    }
    e, ok := wi.(*widget.Entry)
    if !ok {
        t.Fail()
        return
    }
    e.SetText(text)
}

func (d *testDialog) setCheck(t *testing.T, name string, check bool) {
    wi, ok := d.widgets[name]
    if !ok {
        t.Fail()
        return
    }
    c, ok := wi.(*widget.Check)
    if !ok {
        t.Fail()
        return
    }
    c.Checked = check
}

func (d *testDialog) tapButton(t *testing.T, name string) {
    t.Helper()
    wi, ok := d.widgets[name]
    if !ok {
        t.Errorf("there's no widget with name %s", name)
        return
    }
    b, ok := wi.(*widget.Button)
    if !ok {
        t.Errorf("widget '%s' isn't a button", name)
        return
    }
    b.OnTapped()
}

var lastTestDialog *testDialog = nil

func testNewForm(title, confirm, dismiss string, items []*widget.FormItem, callback func(bool), _ fyne.Window) dialog.Dialog {
    widgets := make(map[string]fyne.CanvasObject)
    for _, i := range items {
        widgetsForItem := digWidgets(i.Widget)
        l := len(widgetsForItem)
        if l < 1 {
            continue
        }
        if l == 1 {
            widgets[i.Text] = widgetsForItem[0]
            continue
        }
        for x, wi := range widgetsForItem {
            widgets[fmt.Sprintf("%s-%d", i.Text, x)] = wi
        }
    }
    lastTestDialog = &testDialog{title: title, confirm: confirm, dismiss: dismiss, widgets: widgets, callback: callback}
    return lastTestDialog
}

func digWidgets(root fyne.CanvasObject) []fyne.CanvasObject {
    if cnt, ok := root.(*fyne.Container); ok {
        var widgets []fyne.CanvasObject
        for _, o := range cnt.Objects {
            widgets = append(widgets, digWidgets(o)...)
        }
        return widgets
    }
    return []fyne.CanvasObject{root}
}


问:
More Float Right Questions
Here's the link: http://www.whiterootmedia.com/homepage_layout_test/

Here's the code:

```<code><div class="site" style="background:yellow;min-width: 577px; ">

<div class="banner" style="background:blue; height:100px; width:417px; float:left;">Banner   Banner   Banner   Banner   Banner   </div>
<div class="ads" style="background:green; height:800px; width:160px; float:right;">Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  </div>
<div class="tree" style="background:orange; white-space:nowrap; height:400px; width:auto; min-width:417px; clear:left;">Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   </div>

</div>
</code>```

I would like the Orange div content not to go behind or on top of the green div when you shrink the window and  I would like the orange div text to push the green div off the screen.

Dusty

答:
Are you by any chance trying to do this?

http://jsfiddle.net/d7seY/

Note: I changed some measurements so it was a bit more comfortable to lay out in jsfiddle.

Title: More Float Right Questions

Body:
Here's the link: http://www.whiterootmedia.com/homepage_layout_test/

Here's the code:

Banner   Banner   Banner   Banner   Banner

Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads

Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree

I would like the Orange div content not to go behind or on top of the green div when you shrink the window and  I would like the orange div text to push the green div off the screen.

Dusty


问:
I am trying to render an array inside an object in React. I have a departments.json file that I have imported into my app.jsx as Data
I am in React. I have a departments.json file that I am pulling my data from:
import Data from "./departments.json"

My information is an array of objects and within each object, I have a key with an array of multiple values. It is these values that I am trying to render as separate divs.

I have used .map to render, but it displays all of the values in one div for each object grouped together. I am really needing these values in their own div. So multiple divs are grouped per object. This is the output:

Component:

```<code>import Data from "./departments.json";
import Info from "./students.json";

function App() {

  console.log(Info)
  console.log(Data)

  return (
    <div className="App">
      <ul className="filtered-student">
        {Info.map(function(student, index){
          return (
            <li key={student.id}>
              <span className="name">{[`${student.familyName}, ${student.givenName}`]}</span>
              <span className="dob">DOB: <span className="value">{student.dob}</span></span>
              <span className="admit-date">Admitted: <span className="value">{student.admitDate}</span></span>
              <span className="grad-date">Anticipated Graduation: <span className="value">{student.anticipatedGraduationDate}</span></span>
              <span className="mentor">Mentor: <span className="value">{[student.mentor.familyName, student.mentor.givenName]}</span></span>
            </li>
          )
        })}
      </ul>
      <div className="filtered-department">
        {Data.map(function(department, index){
          return (
            <div key={index} className="dept-name">{department.subjects}</div>
          )
        })}
      </div>
    </div>
  );
}

export default App;
</code>```

The JSON file:

```<code>[{
        "name": "Architecture and History of Art",
        "subjects": [
            "Painting",
            "Sculpture",
            "Architecture",
            "Drawing, printing, photography, collage and film",
            "The art and architecture of antiquity",
            "Art, religion and society",
            "Art, society and politics"
        ]
    },
    {
        "name": "Physical Education",
        "subjects": [
            "Anatomy and physiology",
            "Social, cultural and ethical influences",
            "Skill acquisition and psychology",
            "Health, fitness and training"
        ]
    },
    {
        "name": "Physics",
        "subjects": [
            "Physical quantities and units",
            "Measurement techniques",
            "Dynamics",
            "Forces, density and pressure",
            "Work, energy and power",
            "Deformation of solids",
            "Waves",
            "Superposition",
            "Electric fields",
            "Current of electricity",
            "D.C. circuits",
            "Particle and nuclear physics"
        ]
    },
    {
        "name": "Εlectrical & Electronics Engineering",
        "subjects": [
            "Circuit Theory & Networks",
            "Electrical & Electronic Measurement",
            "Data Structure & Algorithms",
            "Materials Science",
            "Mathematics",
            "Numerical Methods & Programming",
            "Computer Organization & Architecture",
            "Technical Report writing"
        ]
    },
    {
        "name": "Computer Science",
        "subjects": [
            "Information representation",
            "Communication and Internet technologies",
            "Hardware",
            "Processor fundamentals",
            "System software",
            "Security, privacy and data integrity",
            "Ethics and ownership",
            "Database and data modelling",
            "Algorithm design and problem-solving",
            "Data representation",
            "Programming",
            "Software development",
            "Monitoring and control systems"
        ]
    }
]

</code>```

答:
Maybe I didn't understand correctly what you need, but try this:</p>
```<code><div className="App">
  <ul className="filtered-student">
    {Info.map((student) => (
        <li key={student.id}>
          <span className="name">
            {[`${student.familyName}, ${student.givenName}`]}
          </span>
          <span className="dob">
            DOB: <span className="value">{student.dob}</span>
          </span>
          <span className="admit-date">
            Admitted: <span className="value">{student.admitDate}</span>
          </span>
          <span className="grad-date">
            Anticipated Graduation:{' '}
            <span className="value">
              {student.anticipatedGraduationDate}
            </span>
          </span>
          <span className="mentor">
            Mentor:{' '}
            <span className="value">
              {[student.mentor.familyName, student.mentor.givenName]}
            </span>
          </span>
        </li>
    ))}
  </ul>

  <div className="filtered-department">
    {Data.map((department) => (
        <div key={department.name} className="dept-name">
          {department.subjects.map((subject) => <div>{subject}</div>)}
        </div>
    ))}
  </div>
</div>
</code>```

Body:
I am in React. I have a departments.json file that I am pulling my data from:
import Data from "./departments.json"

My information is an array of objects and within each object, I have a key with an array of multiple values. It is these values that I am trying to render as separate divs.

I have used .map to render, but it displays all of the values in one div for each object grouped together. I am really needing these values in their own div. So multiple divs are grouped per object. This is the output:

Component:

import Data from "./departments.json";
import Info from "./students.json";

function App() {

  console.log(Info)
  console.log(Data)

  return (

        {Info.map(function(student, index){
          return (

              {[`${student.familyName}, ${student.givenName}`]}
              DOB: {student.dob}
              Admitted: {student.admitDate}
              Anticipated Graduation: {student.anticipatedGraduationDate}
              Mentor: {[student.mentor.familyName, student.mentor.givenName]}

          )
        })}

        {Data.map(function(department, index){
          return (

{department.subjects}

          )
        })}

  );
}

export default App;

The JSON file:

[{
        "name": "Architecture and History of Art",
        "subjects": [
            "Painting",
            "Sculpture",
            "Architecture",
            "Drawing, printing, photography, collage and film",
            "The art and architecture of antiquity",
            "Art, religion and society",
            "Art, society and politics"
        ]
    },
    {
        "name": "Physical Education",
        "subjects": [
            "Anatomy and physiology",
            "Social, cultural and ethical influences",
            "Skill acquisition and psychology",
            "Health, fitness and training"
        ]
    },
    {
        "name": "Physics",
        "subjects": [
            "Physical quantities and units",
            "Measurement techniques",
            "Dynamics",
            "Forces, density and pressure",
            "Work, energy and power",
            "Deformation of solids",
            "Waves",
            "Superposition",
            "Electric fields",
            "Current of electricity",
            "D.C. circuits",
            "Particle and nuclear physics"
        ]
    },
    {
        "name": "Εlectrical & Electronics Engineering",
        "subjects": [
            "Circuit Theory & Networks",
            "Electrical & Electronic Measurement",
            "Data Structure & Algorithms",
            "Materials Science",
            "Mathematics",
            "Numerical Methods & Programming",
            "Computer Organization & Architecture",
            "Technical Report writing"
        ]
    },
    {
        "name": "Computer Science",
        "subjects": [
            "Information representation",
            "Communication and Internet technologies",
            "Hardware",
            "Processor fundamentals",
            "System software",
            "Security, privacy and data integrity",
            "Ethics and ownership",
            "Database and data modelling",
            "Algorithm design and problem-solving",
            "Data representation",
            "Programming",
            "Software development",
            "Monitoring and control systems"
        ]
    }
]

Body:
Maybe I didn't understand correctly what you need, but try this:

<div className="App">
  <ul className="filtered-student">
    {Info.map((student) => (
        <li key={student.id}>
          <span className="name">
            {[`${student.familyName}, ${student.givenName}`]}
          </span>
          <span className="dob">
            DOB: <span className="value">{student.dob}</span>
          </span>
          <span className="admit-date">
            Admitted: <span className="value">{student.admitDate}</span>
          </span>
          <span className="grad-date">
            Anticipated Graduation:{' '}
            <span className="value">
              {student.anticipatedGraduationDate}
            </span>
          </span>
          <span className="mentor">
            Mentor:{' '}
            <span className="value">
              {[student.mentor.familyName, student.mentor.givenName]}
            </span>
          </span>
        </li>
    ))}
  </ul>

  <div className="filtered-department">
    {Data.map((department) => (
        <div key={department.name} className="dept-name">
          {department.subjects.map((subject) => <div>{subject}</div>)}
        </div>
    ))}
  </div>
</div>


问:
how to remove eventhandler from bootstrap carousel indicator items
I am using bootstrap5 carousel, and I want to fire a custom event when the previous or next indicators are clicked.
I want to prevent the default bootstrap event from firing.   I have tried a bunch of different techniques, but with no success.

Does anyone know how to do this?

Mtia

答:
Check the official documentation. It has some listeners you can add to your JavaScript.

You need to make sure you add the Bootstrap CDN or the npm module with the JavaScript for it to work, though.

Bootstrap Documentation

Example

const myCarousel = document.querySelector("#myCarousel");
const carousel = new bootstrap.Carousel(myCarousel, { interval: 2500 });

myCarousel.addEventListener("slide.bs.carousel", () => { /* Do something... */ });
```


问:
Is there a simpler version of renaming columns with alternating patterns? Or tidyverse methods?

My Data

So I have a data frame that I am working with below:

```<code>structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")
</code>```

It looks like this:

```<code> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1
</code>```

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

```<code>new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1
</code>```

Which gives me this data frame:

```<code>  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1
</code>```

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
</code>```

For example:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1
</code>```

This is time-consuming if you spell it out manually:

```<code>names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1
</code>```

Which does get you what you want, yet slowly:

```<code>  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1
</code>```

And something like outer doesnt seem to fit here:

```<code>outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")
</code>```

So if there is a better way of naming chunks of variables like this, that would be great to know.

Body:
My Data

So I have a data frame that I am working with below:

structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")

It looks like this:

 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1

Which gives me this data frame:

  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")

For example:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1

This is time-consuming if you spell it out manually:

names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1

Which does get you what you want, yet slowly:

  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1

And something like outer doesnt seem to fit here:

outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")

So if there is a better way of naming chunks of variables like this, that would be great to know.

Body:
You may use rename_with in dplyr -

library(dplyr)

df %>% rename_with(~paste0('cope_', seq_along(.)))

#  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
#1      3      1      2      2      3      3      2      3      3       2
#2      3      1      2      2      3      3      2      3      3       2
#3      3      1      2      3      4      4      1      4      3       1
#4      2      1      1      1      1      3      1      4      2       1
#5      4      1      3      1      3      3      3      3      3       1
#6      1      1      2      1      3      3      3      3      3       1


问:
Kernel module that iterates over the tree of children of a task using depth first search
So I know how to create a kernel and to iterate over the processes linearly by simply including linux/sched.h and using the following code:

struct task_struct *task;

for_each_process(task)
{
   printk("Name: %s PID: [%d]\n", task->comm, task->pid);
}
```
<p>How can I print these tasks using a depth first search? I want my output to be similar to the one of <code>ps -eLf</code>.</p>
<p>The following patch of code has been given for reference:</p>
<pre class="lang-c prettyprint-override"><code>struct task_struct *task;
struct list_head *list;
list_for_each(list, &init_task->children) {
    task = list_entry(list, struct task_struct, sibling);
    /* task points to the next child in the list */
}
</code>```

and I know that task->comm returns the name and task->pid returns the PID for that task.

What fields are used to for the state and parent PID?

答:
I see the accepted answer is using recursion. Even if the code is simpler, it is still a very bad idea to write recursive functions in kernel code. The kernel has a limited stack size available and a recursive functions can easily overflow that and crash everything. You should implement DFS/BFS iteratively instead: the Wikipedia pages (DFS, BFS) have explanations and examples of code.

Here's a simple DFS and BFS implementation using a support struct as a queue (tested on kernel 5.10). Since the only difference between iterative DFS and BFS is pushing new elements on the head or the tail of the queue respectively, I just implemented both and you can switch to BFS by simply adding #define BFS.

// Uncomment to use BFS instead of DFS
// #define BFS

static void dump_children_tree(struct task_struct *task) {
    char comm[TASK_COMM_LEN];
    struct task_struct *child;
    struct list_head *list;
    struct queue *q, *tmp;
#ifdef BFS
    struct queue **tail;
#endif
    pid_t ppid;

    q = kmalloc(sizeof *q, GFP_KERNEL);
    if (!q)
        goto out_nomem;

    q->task = task;
    q->next = NULL;
#ifdef BFS
    tail = &q->next;
#endif

    while (q) {
        task = q->task;
#ifndef BFS
        tmp = q;
        q = q->next;
        kfree(tmp);
#endif

        rcu_read_lock();
        ppid = rcu_dereference(task->real_parent)->pid;
        rcu_read_unlock();

        pr_info("Name: %-20s State: %ld\tPID: %d\tPPID: %d\n",
            get_task_comm(comm, task),
            task->state,
            task->pid,
            ppid
        );

        list_for_each(list, &task->children) {
            child = list_entry(list, struct task_struct, sibling);
            get_task_struct(child);

            tmp = kmalloc(sizeof *tmp, GFP_KERNEL);
            if (!tmp)
                goto out_nomem;

            tmp->task = child;
#ifdef BFS
            tmp->next = NULL;
            *tail = tmp;
            tail = &tmp->next;
#else // DFS
            tmp->next = q;
            q = tmp;
#endif
        }

        put_task_struct(task);
#ifdef BFS
        tmp = q;
        q = q->next;
        kfree(tmp);
#endif
    }

    return;

out_nomem:
    while (q) {
        tmp = q;
        q = q->next;
        kfree(tmp);
    }
}
```

NOTE: the above function assumes that get_task_struct() was already called on the passed task, and automatically calls put_task_struct() for you on it before returning.

Body:
So I know how to create a kernel and to iterate over the processes linearly by simply including linux/sched.h and using the following code:

struct task_struct *task;

for_each_process(task)
{
   printk("Name: %s PID: [%d]\n", task->comm, task->pid);
}

How can I print these tasks using a depth first search? I want my output to be similar to the one of ps -eLf.

The following patch of code has been given for reference:

struct task_struct *task;
struct list_head *list;
list_for_each(list, &init_task->children) {
    task = list_entry(list, struct task_struct, sibling);
    /* task points to the next child in the list */
}

and I know that task->comm returns the name and task->pid returns the PID for that task.

What fields are used to for the state and parent PID?

Body:
I see the accepted answer is using recursion. Even if the code is simpler, it is still a very bad idea to write recursive functions in kernel code. The kernel has a limited stack size available and a recursive functions can easily overflow that and crash everything. You should implement DFS/BFS iteratively instead: the Wikipedia pages (DFS, BFS) have explanations and examples of code.

Here's a simple DFS and BFS implementation using a support struct as a queue (tested on kernel 5.10). Since the only difference between iterative DFS and BFS is pushing new elements on the head or the tail of the queue respectively, I just implemented both and you can switch to BFS by simply adding #define BFS.

// Uncomment to use BFS instead of DFS
// #define BFS

static void dump_children_tree(struct task_struct *task) {
    char comm[TASK_COMM_LEN];
    struct task_struct *child;
    struct list_head *list;
    struct queue *q, *tmp;
#ifdef BFS
    struct queue **tail;
#endif
    pid_t ppid;

    q = kmalloc(sizeof *q, GFP_KERNEL);
    if (!q)
        goto out_nomem;

    q->task = task;
    q->next = NULL;
#ifdef BFS
    tail = &q->next;
#endif

    while (q) {
        task = q->task;
#ifndef BFS
        tmp = q;
        q = q->next;
        kfree(tmp);
#endif

        rcu_read_lock();
        ppid = rcu_dereference(task->real_parent)->pid;
        rcu_read_unlock();

        pr_info("Name: %-20s State: %ld\tPID: %d\tPPID: %d\n",
            get_task_comm(comm, task),
            task->state,
            task->pid,
            ppid
        );

        list_for_each(list, &task->children) {
            child = list_entry(list, struct task_struct, sibling);
            get_task_struct(child);

            tmp = kmalloc(sizeof *tmp, GFP_KERNEL);
            if (!tmp)
                goto out_nomem;

            tmp->task = child;
#ifdef BFS
            tmp->next = NULL;
            *tail = tmp;
            tail = &tmp->next;
#else // DFS
            tmp->next = q;
            q = tmp;
#endif
        }

        put_task_struct(task);
#ifdef BFS
        tmp = q;
        q = q->next;
        kfree(tmp);
#endif
    }

    return;

out_nomem:
    while (q) {
        tmp = q;
        q = q->next;
        kfree(tmp);
    }
}

NOTE: the above function assumes that get_task_struct() was already called on the passed task, and automatically calls put_task_struct() for you on it before returning.


问:
Convert array to iterator
How do I convert an array to an iterator, such that I can call both next and done to iterate the array's values?

I've seen exhaustively that

an array is an iterable

but it doesn't have either property (const a = [1,2,3]; a.done; // returns undefined).

I've tried directly accessing the Symbol.iterator (const iter = a[Symbol.iterator];), but it simply returns function values() for the array.

答: Use the .values() method, it returns an iterator over array elements.</p>

Title: Convert array to iterator


问:
Python code to randomly guess user input number
I just just finished (jk I was looking at old code and found this so) but for real this is the final code
final update: Everything now good
thanks to this odd number formula.
The sum of n odd numbers is n^2
How did we arrive to this formula

First 1 odd number = 1 Sum = 1 = 1^2

First 2 odd numbers =1,3 Sum = 4 =    2^2

First 3 odd numbers = 1,3,5 Sum = 9 = 3^2

First 4 odd numbers =1,3,5,7 Sum = 16 4^2

First 5 odd numbers = 1,3,5,7,9 Sum = 25 =5^2

Therefore sum of n odd numbers = n^2

import random,os
userI =True
os.system("cls")
def randomOddNumber(a,b):
  a = a // 2
  b = b // 2 - 1
  number = random.randint(a,b)
  number = (number * 2) + 1
  return number
while userI==True:
    userInput = int(input("Please input a 4 digit number: "))
    compNumber = random.randint(1000, 9999)

    count = 0
    while userInput != compNumber:

        if (userInput % 2) == 0:

                compNumber= random.randrange(0, 10000, 2)
                count=count+1
        else:
              compNumber = randomOddNumber(0,9999)
              count =count+1
    print("Match was created on the", count, "attempt.")
    ex = False
    while ex == False:
        userAwnser = input("Would you like to play again?: ")
        if userAwnser == "no"or userAwnser=="No":
            userI = False
            ex = True
        elif userAwnser == "yes"or userAwnser=="Yes":
            userI = True
            ex = True
            os.system("cls")
        else:
            print("Error Not a valid awnser")
            ex = False

```

答:
```<code>while True:
    master = int(input("enter a 4 digit number: "))
    if 1000 <= master <= 9999:
        break
    print("That's not a 4-digit number.")

guess = 5500
delta = guess // 2
tries = 0
while guess != master and tries < 10:
    tries = tries+1
    nxt = input(f"My guess is {guess}.  Is your number higher or lower? ")
    if nxt[0] == 'h':
        guess += delta
    elif nxt[0] == 'l':
        guess -= delta
    else:
        print("Come on, type 'higher' or 'lower'.")
        continue
    delta //= 2

if master == guess:
    print(f"My guess is {guess}.  I got it right in {tries} tries")
else:
    print("I didn't get it in 10 tries.")
</code>```


问:
How to store the same inner structure inside a DynamoDbTable
I have a class called Customer, inside I have two fields with the same object.

```<code>@Value
@Builder
@DynamoDbImmutable(builder = Customer.CustomerBuilder.class)
public class Customer {
@Getter(onMethod_ = @DynamoDbPartitionKey)
String id;

@Getter(onMethod_ = {@DynamoDbFlatten,
@DynamoDbAttribute("phone")})
Phone phone;

@Getter(onMethod_ = {@DynamoDbFlatten,
@DynamoDbAttribute("HomePhone")})
Phone homePhone;
</code>```

The phone structure

```<code>@Value
@Builder
@DynamoDbImmutable(builder = Phone.PhoneBuilder.class)
public class Phone {
String number;
....
</code>```

When I put the item into DynamoDB table it says

```<code>Caused by: java.lang.IllegalArgumentException: Attempt to add an attribute to a mapper that already has one with the same name. [Attribute name: number]
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.lambda$null$2(StaticImmutableTableSchema.java:184)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at java.base/java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1085)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.lambda$new$3(StaticImmutableTableSchema.java:181)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.<init>(StaticImmutableTableSchema.java:179)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.<init>(StaticImmutableTableSchema.java:77)
</code>```

How should I store it, tried to give different name for fields, like through DynamoDbAttribute, but didn't help much

答:
You are currently flattening both phone and homePhone via @DynamoDbFlatten and that moves their constituent attributes (both have number) to become top-level attributes. You end up with two top-level attributes named number, causing the conflict.

Remove @DynamoDbFlatten from both and store phone and homePhone so they become hierarchical. Or find some other way to make these attribute names unique (e.g. renaming them at the attribute level).

Body:
I have a class called Customer, inside I have two fields with the same object.

@Value
@Builder
@DynamoDbImmutable(builder = Customer.CustomerBuilder.class)
public class Customer {
@Getter(onMethod_ = @DynamoDbPartitionKey)
String id;

@Getter(onMethod_ = {@DynamoDbFlatten,
@DynamoDbAttribute("phone")})
Phone phone;

@Getter(onMethod_ = {@DynamoDbFlatten,
@DynamoDbAttribute("HomePhone")})
Phone homePhone;

The phone structure

@Value
@Builder
@DynamoDbImmutable(builder = Phone.PhoneBuilder.class)
public class Phone {
String number;
....

When I put the item into DynamoDB table it says

Caused by: java.lang.IllegalArgumentException: Attempt to add an attribute to a mapper that already has one with the same name. [Attribute name: number]
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.lambda$null$2(StaticImmutableTableSchema.java:184)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at java.base/java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1085)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.lambda$new$3(StaticImmutableTableSchema.java:181)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.<init>(StaticImmutableTableSchema.java:179)
at software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema.<init>(StaticImmutableTableSchema.java:77)

How should I store it, tried to give different name for fields, like through DynamoDbAttribute, but didn't help much


答:
DateDiffDay is an extension method. You call it with object instance and then pass the parameters without that object as a first parameter. In your case:

```<code>EF.Functions.DateDiffDay(DateTime.Now, i.InvoiceDate) + i.ProductNav.GracePeriod.GetValueOrDefault();
</code>```

You may need to add the using directive:

```<code>using Microsoft.EntityFrameworkCore;
</code>```

and the needed nuget package

Title: DbFunctions, is a type which is not valid in the given context

Body:
DateDiffDay is an extension method. You call it with object instance and then pass the parameters without that object as a first parameter. In your case:

EF.Functions.DateDiffDay(DateTime.Now, i.InvoiceDate) + i.ProductNav.GracePeriod.GetValueOrDefault();

You may need to add the using directive:

using Microsoft.EntityFrameworkCore;

and the needed nuget package