问:
My scanner only gives me my x when I want both my x and y
I am really new to Java, as well as programming. And I have been going at this problem for a while. It seems like a quick fix but I just couldn't find something similar online:

```<code>import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.Scanner;

import javax.swing.plaf.synth.SynthScrollBarUI;

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

        int x;
        int y;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your first number: ");

        x = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }
        System.out.println("Your first number is " + x);

        System.out.println("Enter your second number: ");
        y = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }

        System.out.println("Your numbers are " + x + " and " + y);

    }
}
</code>```

I am trying to tell the code to ask the user to enter x and y using the same scanner, but when I try to run my code, my output tells me to enter the x twice instead of asking for the y right after my first x input. Even when I go through with the code, when It states the x and y, it only shows the first two numbers added and not my y.

I'm thinking it may be because I have entered my scanner into the loops wrong, since I told the code to only accept integers from the user.

Any help would be great, sorry if it wasn't the best explanation I am still new.

答:
Your current code is logically incorrect, first you get an int then you check if there is an int to get. You need something like

```<code>while (!scan.hasNextInt()) {
    System.out.println("Thats not a number, please try again.");
    scan.nextLine();
}
x = scan.nextInt();
System.out.println("Your first number is " + x);

System.out.println("Enter your second number: ");
while (!scan.hasNextInt()) {
    System.out.println("Thats not a number, please try again.");
    scan.nextLine();
}
y = scan.nextInt();
System.out.println("Your numbers are " + x + " and " + y);
</code>```

Body:
I am really new to Java, as well as programming. And I have been going at this problem for a while. It seems like a quick fix but I just couldn't find something similar online:

import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.Scanner;

import javax.swing.plaf.synth.SynthScrollBarUI;

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

        int x;
        int y;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your first number: ");

        x = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }
        System.out.println("Your first number is " + x);

        System.out.println("Enter your second number: ");
        y = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }

        System.out.println("Your numbers are " + x + " and " + y);

    }
}

I am trying to tell the code to ask the user to enter x and y using the same scanner, but when I try to run my code, my output tells me to enter the x twice instead of asking for the y right after my first x input. Even when I go through with the code, when It states the x and y, it only shows the first two numbers added and not my y.

I'm thinking it may be because I have entered my scanner into the loops wrong, since I told the code to only accept integers from the user.

Any help would be great, sorry if it wasn't the best explanation I am still new.

Body:
Your current code is logically incorrect, first you get an int then you check if there is an int to get. You need something like

while (!scan.hasNextInt()) {
    System.out.println("Thats not a number, please try again.");
    scan.nextLine();
}
x = scan.nextInt();
System.out.println("Your first number is " + x);

System.out.println("Enter your second number: ");
while (!scan.hasNextInt()) {
    System.out.println("Thats not a number, please try again.");
    scan.nextLine();
}
y = scan.nextInt();
System.out.println("Your numbers are " + x + " and " + y);


来源: stackexchange

问:
How To Install WSL without Windows Store?
i have windown 10 enterprise,and i figured it out that this version dont have windows store
how can i install linux subsystem (WSL) with ubuntu ? </p>

答:
I know this is an old post. But I found another way.

You can just run this on PowerShell or Command Prompt as Administrator:

```<code>wsl --install
</code>```

If you want to see another distros:

```<code>wsl --list --online
</code>```

And for install it, you can run (e.g. install Debian on WSL):

```<code>wsl --install -d Debian
</code>```

For more information you can read this post.

ContentLicense: CC BY-SA 4.0

Body:
I know this is an old post. But I found another way.

You can just run this on PowerShell or Command Prompt as Administrator:

wsl --install

If you want to see another distros:

wsl --list --online

And for install it, you can run (e.g. install Debian on WSL):

wsl --install -d Debian

For more information you can read this post.


问:
¿how to execute an angularfire query with 2 "where" clauses in angular fire?
I'm trying to execute a query with two "where" clauses in the same field, using AngularFire. The query works when I set only one "where", but retrieves no results when using two clauses. The same query works normally when using firebase (not angular fire)</p>
```<code>  query2(callback){
    this.resultingArray = [];

    let query =this.angularFirestore.firestore.collection("myCollection")

    //Doesn't work with two clauses:
    .where("date",">=",this.startDate).where("date","<=",this.endDate)

    //works with only one clause:
    //.where("date",">=",this.startDateISO)

    query.get().then((querySnapshot)=>{
      querySnapshot.forEach((docs) => {
        this.resultingArray.push(docs)
      })
     })
    .then(()=>{
          callback()
        }).catch((err)=>{
          console.log(err)
        })
     }
</code>```

答:
Try this.</p>
```<code>let query =this.angularFirestore.firestore.collection("myCollection", ref => {
  return ref.where("date",">=",this.startDate).where("date","<=",this.endDate);
});
</code>```

Body:
I'm trying to execute a query with two "where" clauses in the same field, using AngularFire. The query works when I set only one "where", but retrieves no results when using two clauses. The same query works normally when using firebase (not angular fire)

  query2(callback){
    this.resultingArray = [];

    let query =this.angularFirestore.firestore.collection("myCollection")

    //Doesn't work with two clauses:
    .where("date",">=",this.startDate).where("date","<=",this.endDate)

    //works with only one clause:
    //.where("date",">=",this.startDateISO)

    query.get().then((querySnapshot)=>{
      querySnapshot.forEach((docs) => {
        this.resultingArray.push(docs)
      })
     })
    .then(()=>{
          callback()
        }).catch((err)=>{
          console.log(err)
        })
     }

Body:
Try this.

let query =this.angularFirestore.firestore.collection("myCollection", ref => {
  return ref.where("date",">=",this.startDate).where("date","<=",this.endDate);
});


问:
Basic use of approx() for lookup table with linear interpolation
I have a vector, my_points and a dataframe that describes the almost linear relationship between points and values.

How do I obtain the vector, my_values, from the relationship described in the dataframe and my_points using linear interpolation?

Assume the relationship beyond the last point in the data frame remains linear.

```<code>my_points <- c(4400, 8800, 13200, 37600, 42000, 46400, 50800, 55200, 59600,
       64000, 68400, 72800, 77200, 81600, 86000, 90400, 94800, 99200,
       103600, 108000, 112400, 116800, 121200, 125600)

df <- structure(list(points = c(3000, 4500, 7500, 11000, 14500, 21500,
                                43000, 71500), values = c(20, 30, 50, 75, 100, 150, 300, 500),
                     points_per_value = c(150, 150, 150, 146.666666666667, 145,
                                          143.333333333333, 143.333333333333, 143)), row.names = c(NA,
                                                                                -8L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Body:
I have a vector, my_points and a dataframe that describes the almost linear relationship between points and values.

How do I obtain the vector, my_values, from the relationship described in the dataframe and my_points using linear interpolation?

Assume the relationship beyond the last point in the data frame remains linear.

my_points <- c(4400, 8800, 13200, 37600, 42000, 46400, 50800, 55200, 59600,
       64000, 68400, 72800, 77200, 81600, 86000, 90400, 94800, 99200,
       103600, 108000, 112400, 116800, 121200, 125600)

df <- structure(list(points = c(3000, 4500, 7500, 11000, 14500, 21500,
                                43000, 71500), values = c(20, 30, 50, 75, 100, 150, 300, 500),
                     points_per_value = c(150, 150, 150, 146.666666666667, 145,
                                          143.333333333333, 143.333333333333, 143)), row.names = c(NA,
                                                                                -8L), class = c("tbl_df", "tbl", "data.frame"))

Body:
You said "interpolation", in which case you can get:

cbind(
  data.frame(my_points),
  lapply(df[-1], function(z) approx(df$points, z, xout = my_points)$y)
)
#    my_points    values points_per_value
# 1       4400  29.33333         150.0000
# 2       8800  59.28571         148.7619
# 3      13200  90.71429         145.6190
# 4      37600 262.32558         143.3333
# 5      42000 293.02326         143.3333
# 6      46400 323.85965         143.2936
# 7      50800 354.73684         143.2421
# 8      55200 385.61404         143.1906
# 9      59600 416.49123         143.1392
# 10     64000 447.36842         143.0877
# 11     68400 478.24561         143.0363
# 12     72800        NA               NA
# 13     77200        NA               NA
# 14     81600        NA               NA
# 15     86000        NA               NA
# 16     90400        NA               NA
# 17     94800        NA               NA
# 18     99200        NA               NA
# 19    103600        NA               NA
# 20    108000        NA               NA
# 21    112400        NA               NA
# 22    116800        NA               NA
# 23    121200        NA               NA
# 24    125600        NA               NA

But you also said "beyond the last point", suggesting you want "extrapolation":

cbind(
  data.frame(my_points), lapply(df[-1], function(z)
  Hmisc::approxExtrap(df$points, z, xout = my_points)$y)
)
#    my_points    values points_per_value
# 1       4400  29.33333         150.0000
# 2       8800  59.28571         148.7619
# 3      13200  90.71429         145.6190
# 4      37600 262.32558         143.3333
# 5      42000 293.02326         143.3333
# 6      46400 323.85965         143.2936
# 7      50800 354.73684         143.2421
# 8      55200 385.61404         143.1906
# 9      59600 416.49123         143.1392
# 10     64000 447.36842         143.0877
# 11     68400 478.24561         143.0363
# 12     72800 509.12281         142.9848
# 13     77200 540.00000         142.9333
# 14     81600 570.87719         142.8819
# 15     86000 601.75439         142.8304
# 16     90400 632.63158         142.7789
# 17     94800 663.50877         142.7275
# 18     99200 694.38596         142.6760
# 19    103600 725.26316         142.6246
# 20    108000 756.14035         142.5731
# 21    112400 787.01754         142.5216
# 22    116800 817.89474         142.4702
# 23    121200 848.77193         142.4187
# 24    125600 879.64912         142.3673

If all you need is the vector of one of these columns, then

Hmisc::approxExtrap(df$points, df$my_values, xout = my_points)$y


问:
Module parameter array in Linux module not showing up in sysfs
I'm writing a char device driver for Linux within a module.

I need to use a module parameter array to display some state information about open devices, but this is not working properly. I'm also using an int parameter (not array) and they are initialized like this:

static int open_permissions[3] = {1,2,3};
static int count;
module_param_array(open_permissions, int, &count, 0660);

static int allow_live_bait = 1;             /* default to on */
module_param(allow_live_bait, int, 0660);  /* a int type */
```
<p>Now these parameters are listed in the VFS <code>/sys/module/mymodule/parameters</code> as they should be. If I open the <code>allow_live_bait</code>  parameter with a text editor, it shows me the number <code>1</code> correctly, but if I open the <code>open_permissions</code> parameter (always using a text editor) it does not show anything.</p>
<p>Also, this is not a problem of an incorrect initialization because I tried to print the values of the array in the init_module function like this and they are correctly initialized:</p>
<pre class="lang-c prettyprint-override"><code>   for(j = 0;j<3;j++){
      printk("%s : open permission %d : %d",MODNAME,j,open_permissions[j]);
   }
</code>```

What I would like to know is if this is a normal behavior when using array parameters or if I'm doing something wrong.

答:
This is because module_param_array() allows one of two options in regards to the third argument (nump i.e. the count of supplied values):

Pass NULL if you want a parameter array of fixed size. In this way, no matter what the user passes when inserting the module (or modifying the parameter through sysfs), the parameter under sysfs will always report all the values of the array. The user can override from zero up to all of the values. If the user does not pass the parameter, the default values will stay unchanged and you will see sysfs report 1,2,3. You can see this as the module always considering the entire parameter array "meaningful".

Pass a pointer to an integer for a "dynamically" sized parameter array. The underlying array will still be statically sized, of course, but the semantics are different. The user is now expected to pass up to N (size of the array) parameters, and the number of passed parameters on module insertion (or upon modification through sysfs) is reflected on the count pointer passed to module_param_array(). The module should only consider indexes from 0 up to count meaningful, and the count defaults to 0 if the user does not pass the parameter at all.

It seems to me like you coded your module parameter following option #2, and then inserted the module without passing the parameter, meaning that count=0. What you probably wanted to do was to just go with option #1 instead.

Body:
I'm writing a char device driver for Linux within a module.

I need to use a module parameter array to display some state information about open devices, but this is not working properly. I'm also using an int parameter (not array) and they are initialized like this:

static int open_permissions[3] = {1,2,3};
static int count;
module_param_array(open_permissions, int, &count, 0660);

static int allow_live_bait = 1;             /* default to on */
module_param(allow_live_bait, int, 0660);  /* a int type */

Now these parameters are listed in the VFS /sys/module/mymodule/parameters as they should be. If I open the allow_live_bait  parameter with a text editor, it shows me the number 1 correctly, but if I open the open_permissions parameter (always using a text editor) it does not show anything.

Also, this is not a problem of an incorrect initialization because I tried to print the values of the array in the init_module function like this and they are correctly initialized:

   for(j = 0;j<3;j++){
      printk("%s : open permission %d : %d",MODNAME,j,open_permissions[j]);
   }

What I would like to know is if this is a normal behavior when using array parameters or if I'm doing something wrong.


问:
Image does not respect parent flex size
I have been scratching my head for quite some time now trying to make this image respect its parent flex size.

The scenario is, I want to build a component that would have a height of 150px. This component will have a column flex display of two sections: an image and its description. I wanted each child to have 1/2 (flex: 1) of their parent's height. However, the image doesn't respect its flex size! It pushes its sibling down.

I've noticed that if I apply the flex: 1 to the image itself this doesn't happen, but I'd like to understand why this image is not respecting its parent flex: 1 (which should be around 67.5px)

Thank you!

* {
  box-sizing: border-box;
}

.carousel {
  width: 150px;
  height: 150px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  gap: 1rem;
  outline: 1px solid black;
}

.carousel__image-container {
  outline: 1px solid red;
  flex: 1;
}

.carousel__image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.carousel__description {
  flex: 1;
  display: flex;
  gap: .5rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel">
    <div class="carousel__image-container">
        <img class="carousel__image"
             src="https://images.unsplash.com/photo-1614006160288-14eba44816d6?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=400&q=80"
             alt="Little Cato"
        />
    </div>
    <div class="carousel__description">
      Lorem ipsum dolor sit amet, consectetur.
    </div>
</div></code>```

答:
Flex is not actually the problem. Your image has an aspect-ratio of 3:2, which means that it's impossible to have 150x67.5 with no distortions or changes in it shape, that's why it is push it's sibling down.

If you really want to set your image as 50% of it's parent height, you should set height: 50% to your

You can also try:

```<code>.carousel__image-container {
   outline: 1px solid red;
   height: 50%;
   width: 100%;
}

.carousel__image {
   width: 100%;
   height: 100%;
}
</code>```

Title: Image does not respect parent flex size

Body:
I have been scratching my head for quite some time now trying to make this image respect its parent flex size.

The scenario is, I want to build a component that would have a height of 150px. This component will have a column flex display of two sections: an image and its description. I wanted each child to have 1/2 (flex: 1) of their parent's height. However, the image doesn't respect its flex size! It pushes its sibling down.

I've noticed that if I apply the flex: 1 to the image itself this doesn't happen, but I'd like to understand why this image is not respecting its parent flex: 1 (which should be around 67.5px)

Thank you!

* {
  box-sizing: border-box;
}

.carousel {
  width: 150px;
  height: 150px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  gap: 1rem;
  outline: 1px solid black;
}

.carousel__image-container {
  outline: 1px solid red;
  flex: 1;
}

.carousel__image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.carousel__description {
  flex: 1;
  display: flex;
  gap: .5rem;
}

      Lorem ipsum dolor sit amet, consectetur.

Body:
Flex is not actually the problem. Your image has an aspect-ratio of 3:2, which means that it's impossible to have 150x67.5 with no distortions or changes in it shape, that's why it is push it's sibling down.

If you really want to set your image as 50% of it's parent height, you should set height: 50% to your <div class="carousel__image-container">

You can also try:

.carousel__image-container {
   outline: 1px solid red;
   height: 50%;
   width: 100%;
}

.carousel__image {
   width: 100%;
   height: 100%;
}


问:
Pyspark: Conditionally overwrite an old record with a new value
I'm trying to update my dataframe based on the condition 'backfill'. If a record has a reason 'backfill', I want to update the 'data' column with the new 'data' but keep the old 'timestamp' value.

Ex:

```<code>id,reason,created_at,updated_at,app_data
2,registration,2020-05-09 15:57:19,2020-05-09 15:57:19,bat
2,disqualified ,2020-05-09 15:57:26,2020-05-09 15:57:26,cat
2,backfill,2021-04-29 17:47:09,2021-04-29 17:47:09,rat
</code>```

should become

```<code>id,reason,created_at,updated_at,app_data
2,registration,2020-05-09 15:57:19,2020-05-09 15:57:19,bat
2,disqualified ,2020-05-09 15:57:26,2020-05-09 15:57:26,rat
</code>```

Any suggestions would be appreciated

答:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First, we'll tackle this problem in Pandas then port the code over to Spark. Here I create a DataFrame from your sample:

import pandas as pd

df = pd.DataFrame({"id": [2,2,2], "reason": ["registration", "disqualified", "backfill"],
                    "created_at": ["2020-05-09 15:57:19", "2020-05-09 15:57:26", "2021-04-29 17:47:09"],
                    "updated_at": ["2020-05-09 15:57:19", "2020-05-09 15:57:26", "2021-04-29 17:47:09"],
                    "app_data": ["bat", "cat", "rat"]})
```
<p>Next, I create a function that does it for me in Pandas. I think this is right but if it's not, I think it should be easy to edit the logic.</p>
<pre class="lang-py prettyprint-override"><code>def backfill(df: pd.DataFrame) -> pd.DataFrame:
    cols = df.columns
    df['next_reason'] = df['reason'].shift(-1)
    df['new_data'] = df['app_data'].shift(-1)
    df.loc[df['next_reason'] == "backfill", "app_data"] = df.loc[df['next_reason'] == "backfill"]["new_data"]
    df = df.dropna()
    return df[cols]
</code>```

Now we can test this using the Fugue transform function:

from fugue import transform
transform(df, backfill, schema="*", partition={"by":"id", "presort": "created_at asc"})
```
<p>Notice the partition keyword argument. This handles grouping by id and sorting by the timestamp so that the diff is accurate. Spark does not guarantee order when you move data around so you need to specify this.</p>
<p>And we can confirm the output is right. Now, we just need to bring it to Spark by specifying the engine:</p>
<pre class="lang-py prettyprint-override"><code>import fugue_spark
sdf = transform(df, backfill, schema="*", engine="spark", partition={"by":"id", "presort": "created_at asc"})
sdf.show()
</code>```

and this outputs:

```<code>+---+------------+-------------------+-------------------+--------+
| id|      reason|         created_at|         updated_at|app_data|
+---+------------+-------------------+-------------------+--------+
|  2|registration|2020-05-09 15:57:19|2020-05-09 15:57:19|     bat|
|  2|disqualified|2020-05-09 15:57:26|2020-05-09 15:57:26|     rat|
+---+------------+-------------------+-------------------+--------+
</code>```

Note .show() is needed because Spark evaluates lazily. The transform function can take in both Pandas and Spark dataframes and will output a Spark dataframe if you are using the Spark engine.

The code is likely more maintainable and easier than the PySpark equivalent.

Body:
I'm trying to update my dataframe based on the condition 'backfill'. If a record has a reason 'backfill', I want to update the 'data' column with the new 'data' but keep the old 'timestamp' value.

Ex:

id,reason,created_at,updated_at,app_data
2,registration,2020-05-09 15:57:19,2020-05-09 15:57:19,bat
2,disqualified ,2020-05-09 15:57:26,2020-05-09 15:57:26,cat
2,backfill,2021-04-29 17:47:09,2021-04-29 17:47:09,rat

should become

id,reason,created_at,updated_at,app_data
2,registration,2020-05-09 15:57:19,2020-05-09 15:57:19,bat
2,disqualified ,2020-05-09 15:57:26,2020-05-09 15:57:26,rat

Any suggestions would be appreciated

Body:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First, we'll tackle this problem in Pandas then port the code over to Spark. Here I create a DataFrame from your sample:

import pandas as pd

df = pd.DataFrame({"id": [2,2,2], "reason": ["registration", "disqualified", "backfill"],
                    "created_at": ["2020-05-09 15:57:19", "2020-05-09 15:57:26", "2021-04-29 17:47:09"],
                    "updated_at": ["2020-05-09 15:57:19", "2020-05-09 15:57:26", "2021-04-29 17:47:09"],
                    "app_data": ["bat", "cat", "rat"]})

Next, I create a function that does it for me in Pandas. I think this is right but if it's not, I think it should be easy to edit the logic.

def backfill(df: pd.DataFrame) -> pd.DataFrame:
    cols = df.columns
    df['next_reason'] = df['reason'].shift(-1)
    df['new_data'] = df['app_data'].shift(-1)
    df.loc[df['next_reason'] == "backfill", "app_data"] = df.loc[df['next_reason'] == "backfill"]["new_data"]
    df = df.dropna()
    return df[cols]

Now we can test this using the Fugue transform function:

from fugue import transform
transform(df, backfill, schema="*", partition={"by":"id", "presort": "created_at asc"})

Notice the partition keyword argument. This handles grouping by id and sorting by the timestamp so that the diff is accurate. Spark does not guarantee order when you move data around so you need to specify this.

And we can confirm the output is right. Now, we just need to bring it to Spark by specifying the engine:

import fugue_spark
sdf = transform(df, backfill, schema="*", engine="spark", partition={"by":"id", "presort": "created_at asc"})
sdf.show()

and this outputs:

+---+------------+-------------------+-------------------+--------+
| id|      reason|         created_at|         updated_at|app_data|
+---+------------+-------------------+-------------------+--------+
|  2|registration|2020-05-09 15:57:19|2020-05-09 15:57:19|     bat|
|  2|disqualified|2020-05-09 15:57:26|2020-05-09 15:57:26|     rat|
+---+------------+-------------------+-------------------+--------+

Note .show() is needed because Spark evaluates lazily. The transform function can take in both Pandas and Spark dataframes and will output a Spark dataframe if you are using the Spark engine.

The code is likely more maintainable and easier than the PySpark equivalent.


问:
Is it bad to add jQuery multiple times on a page?
I am in a situation where I have multiple ASCX files that are being added to an aspx page.  Some of these files include the jQuery library.  Depending on which ones are added the jQuery library may be included more than once.

I cannot add jQuery at the masterpage or some other level, it must be from the ASCX.  The reasons for this are beyond the scope of this question, but if someone really wants an explanation I can provide one.

Is it bad to have jQuery added multiple times in an ASPX page?  Is there a way to conditionally add a script to an ASCX page?

答:
in your ascxs you can do

```<code>if (typeof jQuery == 'undefined') {
   // load jquery
   var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "path/to/jQuery";
    document.getElementsByTagName('head')[0].appendChild(script);
} else {
  //already loaded
}
</code>```

ref: check if jquery has been loaded, then load it if false

ContentLicense: CC BY-SA 3.0

Body:
in your ascxs you can do

if (typeof jQuery == 'undefined') {
   // load jquery
   var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "path/to/jQuery";
    document.getElementsByTagName('head')[0].appendChild(script);
} else {
  //already loaded
}

ref: check if jquery has been loaded, then load it if false


问:
making a greetings bot for discord
so, I'm trying to do a bot that greets people when they join getting a greeting from a list and then randomizing it and mentioning them, but I can't get it to mention a user while also choosing a random greeting, what could I do?</p>
```<code>import discord
import os
import random

client = discord.Client()

invites = ["has been invited by"]

username = client.get_user(id)

starter_greetings = [

  "hola como estas"
]

@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  msg = message.content

  channel = client.get_channel(940394154972823593)

  if any(word in msg for word in invites):
    await channel.send(username + random.choice(starter_greetings))

client.run(os.getenv('TOKEN'))
</code>```

答:
First of all, instead of checking for a message's content, you can check if a user joins the server via the on_member_join event, which runs whenever a user joins the server. You can send a message to a specific channel, and have your bot mention the user by using discord.Member.mention. Do have a look at the example below.

starter_greetings = [
  "hola como estas",
  "welcome to the server",
  "enjoy your stay"
]

@client.event
async def on_member_join(member):
    join_channel = member.guild.get_channel(YOUR_CHANNEL_ID) # get the channel of your choice
    await join_channel.send(f"{member.mention} {random.choice(starter_greetings)}")
    # send the member and a random option from starter_greetings list
```

Title: making a greetings bot for discord

Body:
so, I'm trying to do a bot that greets people when they join getting a greeting from a list and then randomizing it and mentioning them, but I can't get it to mention a user while also choosing a random greeting, what could I do?

import discord
import os
import random

client = discord.Client()

invites = ["has been invited by"]

username = client.get_user(id)

starter_greetings = [

  "hola como estas"
]

@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  msg = message.content

  channel = client.get_channel(940394154972823593)

  if any(word in msg for word in invites):
    await channel.send(username + random.choice(starter_greetings))

client.run(os.getenv('TOKEN'))


问:
How to Update value for multiple Field in Oracle SQL
I have to update field: Number, Tgl, product in Table Detail_product from table Details
with condition:

```<code>If, id on Table Detail Product an Detail is same then
update Detail_product.Tgl using Details.tgl where Details.tgl is null,
update Detail_product.number using Details.number  where Details.number
update Detail_product.product using Details.product  where Details.product
</code>```

I have query merge to update field, but i can't create one query to update multiple field

```<code>MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.tgl = y.tgl WHERE Y.tgl IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.number = y.number WHERE Y.number IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.product = y.product WHERE Y.product IS NOT NULL;
</code>```

What should i do, so the query is sort and the runtime doesn't take long.

答:
you should do the merge only once to improve the performance. first join both the tables and get the right value in a sub query and then update the final table. This will make sure both the tables are read once and marked for updated once. The not null check condition in the sub query can be removed most of the records from details tables are not null.</p>
```<code>    MERGE INTO Detail_product x
    USING
    (select nvl(y.tgl, x.tgl) as tgl, nvl(y.number, x.number) as number, nvl(y.product,x.product) as product
    from Detail_product x inner join Details y on x.id = y.id
    where (y.tgl is not null or y.number is not null or y.product is not null)
    ) y
    ON (x.id = y.id)
    WHEN MATCHED THEN
    UPDATE SET x.tgl = y.tgl, x.number = y.number, x.product = y.product;
</code>```

Body:
I have to update field: Number, Tgl, product in Table Detail_product from table Details
with condition:

If, id on Table Detail Product an Detail is same then
update Detail_product.Tgl using Details.tgl where Details.tgl is null,
update Detail_product.number using Details.number  where Details.number
update Detail_product.product using Details.product  where Details.product

I have query merge to update field, but i can't create one query to update multiple field

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.tgl = y.tgl WHERE Y.tgl IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.number = y.number WHERE Y.number IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.product = y.product WHERE Y.product IS NOT NULL;

What should i do, so the query is sort and the runtime doesn't take long.

Body:
you should do the merge only once to improve the performance. first join both the tables and get the right value in a sub query and then update the final table. This will make sure both the tables are read once and marked for updated once. The not null check condition in the sub query can be removed most of the records from details tables are not null.

    MERGE INTO Detail_product x
    USING
    (select nvl(y.tgl, x.tgl) as tgl, nvl(y.number, x.number) as number, nvl(y.product,x.product) as product
    from Detail_product x inner join Details y on x.id = y.id
    where (y.tgl is not null or y.number is not null or y.product is not null)
    ) y
    ON (x.id = y.id)
    WHEN MATCHED THEN
    UPDATE SET x.tgl = y.tgl, x.number = y.number, x.product = y.product;


问:
react - function inside useEffect
I've seen some of the example like

```<code>  useEffect(() => {
    const getData = () : void => {
      console.log("getData")
    }
    getData()
  }, []);
</code>```

But I can put the function outside useEffect with the same outcome.

```<code>  const getData = () : void => {
      console.log("getData")
  }
  useEffect(() => {
    getData()
  }, []);
</code>```

What is the difference between these 2?

答:
One difference is that, if you declare the function outside the effect hook, every time the component re-renders, the function object will be created anew. In contrast, declaring the function inside means that that function only gets created when the hook runs. (The anonymous inline function passed to useEffect still gets created every render, though...) It's really not worth worrying about, but it's a difference.

The main reason some might prefer to declare the function inside the effect hook is to constrain the scope as much as possible - if you do

```<code>const fn = () => ...

useEffect(fn, [])

// lots more code
</code>```

Then, some readers of the code may (very reasonably) worry that // lots more code contains a reference to fn, which can't be determined without reading through all of // lots more code. Constraining your getData to only inside the effect hook makes the intent of the function easier to understand at a glance, especially in a big component.

Title: react - function inside useEffect

Body:
I've seen some of the example like

  useEffect(() => {
    const getData = () : void => {
      console.log("getData")
    }
    getData()
  }, []);

But I can put the function outside useEffect with the same outcome.

  const getData = () : void => {
      console.log("getData")
  }
  useEffect(() => {
    getData()
  }, []);

What is the difference between these 2?

Body:
One difference is that, if you declare the function outside the effect hook, every time the component re-renders, the function object will be created anew. In contrast, declaring the function inside means that that function only gets created when the hook runs. (The anonymous inline function passed to useEffect still gets created every render, though...) It's really not worth worrying about, but it's a difference.

The main reason some might prefer to declare the function inside the effect hook is to constrain the scope as much as possible - if you do

const fn = () => ...

useEffect(fn, [])

// lots more code

Then, some readers of the code may (very reasonably) worry that // lots more code contains a reference to fn, which can't be determined without reading through all of // lots more code. Constraining your getData to only inside the effect hook makes the intent of the function easier to understand at a glance, especially in a big component.


问:
What are the support patterns in laravel 4 request beside the wildcard?
Based on the documentation:

Determining If The Request Path Matches A Pattern

```<code>if (Request::is('admin/*'))
// What are the support patterns in laravel 4 request beside the wildcard?
{
  //
}
</code>```

I can't seems find a docs that provide more examples than just wildcard.

答:
```<code><a href="#" {{ (Request::is('url*')) ? 'class=active' : '' }}>Link</ a>
</code>```

Try this:

```<code>Request::is('url*')
Request::is('url/*')
</code>```

Example:

```<code><a href="#" {{ (Request::is('products*')) ? 'class=active' : '' }}>Link</ a>
</code>```

or

```<code><a href="#" {{ (Request::is('products')) ? 'class=active' : '' }}>Link</ a>

<a href="#" {{ (Request::is('products/*')) ? 'class=active' : '' }}>Link< /a>
</code>```

Body:
Based on the documentation:

Determining If The Request Path Matches A Pattern

if (Request::is('admin/*'))
// What are the support patterns in laravel 4 request beside the wildcard?
{
  //
}

I can't seems find a docs that provide more examples than just wildcard.

Body:
<a href="#" {{ (Request::is('url*')) ? 'class=active' : '' }}>Link</ a>

Try this:

Request::is('url*')
Request::is('url/*')

Example:

<a href="#" {{ (Request::is('products*')) ? 'class=active' : '' }}>Link</ a>

or

<a href="#" {{ (Request::is('products')) ? 'class=active' : '' }}>Link</ a>

<a href="#" {{ (Request::is('products/*')) ? 'class=active' : '' }}>Link< /a>


问:
Regex, php : how to negate a capturing parentheses
I want to analyse a mysql request with a php regex,
that is, extract the select_expr and the table_references from a mysql statement.
For example, here are two mysql queries that I would like my regex to match :

```<code>select id, name from table

select id, name
</code>```

From that query I would like to extract 2 parts : the "id, name" information and the "table" information too.

The first part can actually contain a string like CONCAT('id','.','nom') AS alias,

and the second part can look like : table t INNER JOIN table2 t2 ON t.id=t2.user_id.

So I tried this "I know it's not working but will get me on the road" regex :

```<code>'!select (.*)( from (.*))?!i'
</code>```

And of course, the first capturing parentheses get all until the end, which is not what I want.

In the

```<code>select id, name from table
</code>```

string, it matches "id, nom from table" as the first part, which is not what I want.
(I want "id, nom" as the first part and "table" as the second in this case).

What I would like to do from this point is to tell the regex that the first capturing parentheses
should not match the " from " sequence if founded.
I know there is the negated character class feature, [^a-z],
but that just negate one character and not a whole string (as a sequence of letters in the right order).

Do you have any lights on this ?
Can we negate the content of parentheses for example with regex ?

答:
The last bit if your question makes it sound like the 'from' part of your query is optional, is that right?

If so, then try this:

```<code>!^select (.*?)(?: from (.*))?$!i
</code>```

This will match everything between "select" and "from", if "from" is found, otherwise it will just match everything after "select".

By adding the ? in ".*?" it tells the '*' to not be greedy, so when it hits a place where the rest of the expression matches, it won't keep taking more characters.
I also added the '?:', which makes the second group a non-capturing group, since there is no useful info to read from it. Finally wrap the expression in ^ and $ to mark line start and end.

If 'from' is NOT optional though, then it is a lot easier and you can just use this:

```<code>!^select (.*) from (.*)$!i
</code>```

Body:
I want to analyse a mysql request with a php regex,
that is, extract the select_expr and the table_references from a mysql statement.
For example, here are two mysql queries that I would like my regex to match :

select id, name from table

select id, name

From that query I would like to extract 2 parts : the "id, name" information and the "table" information too.

The first part can actually contain a string like CONCAT('id','.','nom') AS alias,

and the second part can look like : table t INNER JOIN table2 t2 ON t.id=t2.user_id.

So I tried this "I know it's not working but will get me on the road" regex :

'!select (.*)( from (.*))?!i'

And of course, the first capturing parentheses get all until the end, which is not what I want.

In the

select id, name from table

string, it matches "id, nom from table" as the first part, which is not what I want.
(I want "id, nom" as the first part and "table" as the second in this case).

What I would like to do from this point is to tell the regex that the first capturing parentheses
should not match the " from " sequence if founded.
I know there is the negated character class feature, [^a-z],
but that just negate one character and not a whole string (as a sequence of letters in the right order).

Do you have any lights on this ?
Can we negate the content of parentheses for example with regex ?

Body:
The last bit if your question makes it sound like the 'from' part of your query is optional, is that right?

If so, then try this:

!^select (.*?)(?: from (.*))?$!i

This will match everything between "select" and "from", if "from" is found, otherwise it will just match everything after "select".

By adding the ? in ".*?" it tells the '*' to not be greedy, so when it hits a place where the rest of the expression matches, it won't keep taking more characters.
I also added the '?:', which makes the second group a non-capturing group, since there is no useful info to read from it. Finally wrap the expression in ^ and $ to mark line start and end.

If 'from' is NOT optional though, then it is a lot easier and you can just use this:

!^select (.*) from (.*)$!i


问:
Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-linear-gradient:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.
```
<p>When I upgraded to Mac os Big sur and run,</p>
```npx react-native run-android
```
<p>I got this error (Android). I have tried a lot of solutions from Stack Overflow, but none of them worked.</p>
<p>I have created a fresh project and it's working. Also some of the old projects are also working perfectly.</p>
```*react-native Version: "0.63.3",*
```

Please help me to find a solution?

答:
I have used every method and found out what worked for me so I have decided to compile it down for others.
As told by @Heinous_Games in the comment section, install Java Uninstall Tool and it will remove Java from your system and to make sure that it works run this manually from your terminal :

```<code>sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/Java/JavaVirtualMachines
sudo rm -rf /Library/Application\ Support/Oracle/Java/
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
</code>```

Go to Java Downloads page and download the file suitable for your system in my case "macOS x64 DMG Installer" and follow the instructions.
I hope it works and if it doen't then restart your system once.

Body:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-linear-gradient:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.

When I upgraded to Mac os Big sur and run,

npx react-native run-android

I got this error (Android). I have tried a lot of solutions from Stack Overflow, but none of them worked.

I have created a fresh project and it's working. Also some of the old projects are also working perfectly.

*react-native Version: "0.63.3",*

Please help me to find a solution?

Body:
I have used every method and found out what worked for me so I have decided to compile it down for others.
As told by @Heinous_Games in the comment section, install Java Uninstall Tool and it will remove Java from your system and to make sure that it works run this manually from your terminal :

sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/Java/JavaVirtualMachines
sudo rm -rf /Library/Application\ Support/Oracle/Java/
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane

Go to Java Downloads page and download the file suitable for your system in my case "macOS x64 DMG Installer" and follow the instructions.
I hope it works and if it doen't then restart your system once.


问:
C language how to call a member of multi-dimensional array in corresponding to a structure
I have a problem with how to call a member of a structure. For example, there is a struct

```<code>typedef struct FAVORITE_TBL_S
{
    UI32_T apple;
    UI32_T banana;
    UI16_T puzzle;
    UI16_T car;
}FAVORITE_TBL_T;
</code>```

And in the function, I have created a multi-dimensional array about this struct.

```<code>FUNCTION_NO_T
call_myFavoriteTbl(
    const UI32_T unit,
    const UI32_T value)
{
    FUNCTION_NO_T ret = FUNCTION_E_GOOD;
    UI8_T num_of_list = 4;
    UI32_T i = 0;
    FAVORITE_TBL_T *ptr_fav = NULL;

    ptr_fav = priviate_alloc(sizeof(FAVORITE_TBL_T ) * num_of_list );
    priviate_memset(ptr_fav, 0, sizeof(FAVORITE_TBL_T ) * num_of_list );

    /* In this function, if I want to use member in the multi-dim array */
    for (i = 0, i < value, i++)
    {
        if (BRAND_PINKLADY == ptr_fav[i]->apple)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }

        if (BRAND_COSTAPICA == ptr_fav[i].banana)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }
    }

    return ret;
}
</code>```

So why ptr_fav[i]->apple is wrong and ptr_fav[i].banana is right?

答: ptr_fav[i] has already dereferenced it and now you have structure value not pointer. If you want to use -> you should try (ptr_fav + i)->apple.</p>

Body:
I have a problem with how to call a member of a structure. For example, there is a struct

typedef struct FAVORITE_TBL_S
{
    UI32_T apple;
    UI32_T banana;
    UI16_T puzzle;
    UI16_T car;
}FAVORITE_TBL_T;

And in the function, I have created a multi-dimensional array about this struct.

FUNCTION_NO_T
call_myFavoriteTbl(
    const UI32_T unit,
    const UI32_T value)
{
    FUNCTION_NO_T ret = FUNCTION_E_GOOD;
    UI8_T num_of_list = 4;
    UI32_T i = 0;
    FAVORITE_TBL_T *ptr_fav = NULL;

    ptr_fav = priviate_alloc(sizeof(FAVORITE_TBL_T ) * num_of_list );
    priviate_memset(ptr_fav, 0, sizeof(FAVORITE_TBL_T ) * num_of_list );

    /* In this function, if I want to use member in the multi-dim array */
    for (i = 0, i < value, i++)
    {
        if (BRAND_PINKLADY == ptr_fav[i]->apple)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }

        if (BRAND_COSTAPICA == ptr_fav[i].banana)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }
    }

    return ret;
}

So why ptr_fav[i]->apple is wrong and ptr_fav[i].banana is right?


问:
How to bulk rename JSON files?
I am trying to rename and replace a certain text with the hexadecimal for thousands of JSON files.

Could you help how to rename and replace them in bulk files?

For instance, the current file name is 10 and it has 10 in the JSON file, I
would like to rename/switch to A.

答:
Here is a theoretical solution:

import os

file_names = ["1_file.json", "10_file.json", "27_file.json", "44_file.json"]

for file in file_names:
   file_name_parts = file.split('_')
   file_name_parts[0] = hex(int(file_name_parts[0])).replace('0x', '').upper()
   renamed_file = '_'.join(file_name_parts)
   print(file, 'will be',  renamed_file)
   os.rename(file, renamed_file)
```
```1_file.json will be 1_file.json
10_file.json will be A_file.json
27_file.json will be 1B_file.json
44_file.json will be 2C_file.json
```

Other stuff depends on details that you didn't describe

Title: How to bulk rename JSON files?

Body:
Here is a theoretical solution:

import os

file_names = ["1_file.json", "10_file.json", "27_file.json", "44_file.json"]

for file in file_names:
   file_name_parts = file.split('_')
   file_name_parts[0] = hex(int(file_name_parts[0])).replace('0x', '').upper()
   renamed_file = '_'.join(file_name_parts)
   print(file, 'will be',  renamed_file)
   os.rename(file, renamed_file)

1_file.json will be 1_file.json
10_file.json will be A_file.json
27_file.json will be 1B_file.json
44_file.json will be 2C_file.json

Other stuff depends on details that you didn't describe


Title: get last week date from last group for each group by pandas?

Body:
        hy_code date       week_date   last_week_date
340     880301  2006/10/31  2006/11/5   NaT
341     880301  2006/11/1   2006/11/5   NaT
342     880301  2006/11/2   2006/11/5   NaT
343     880301  2006/11/3   2006/11/5   NaT
355     880301  2006/11/21  2006/11/26  2006/11/5
482916  880969  2021/12/24  2021/12/26  NaT
482918  880969  2021/12/28  2022/1/2    2021/12/26
482919  880969  2021/12/29  2022/1/2    2021/12/26
482920  880969  2021/12/30  2022/1/2    2021/12/26
482921  880969  2021/12/31  2022/1/2    2021/12/26

Goal

I want to get last week date for each group week date.The expected result is above.

Try

df['new_week_date']=tmp_df.groupby(['hy_code','week_date'])['week_date'].shift(1), but failed.

    hy_code date    week_date   last_week_date
340 880301  2006-10-31  2006-11-05  NaT
341 880301  2006-11-01  2006-11-05  2006-11-05
342 880301  2006-11-02  2006-11-05  2006-11-05
343 880301  2006-11-03  2006-11-05  2006-11-05
355 880301  2006-11-21  2006-11-26  NaT
482916  880969  2021-12-24  2021-12-26  NaT
482918  880969  2021-12-28  2022-01-02  2021-12-26
482919  880969  2021-12-29  2022-01-02  2022-01-02
482920  880969  2021-12-30  2022-01-02  2022-01-02
482921  880969  2021-12-31  2022-01-02  2022-01-02

Body:
You can first compute the shifted week as a series with a double groupby:

s = (df
   .groupby(['hy_code','week_date'],sort=False)['week_date'].first()
   .groupby('hy_code').shift()
   .rename('last_week_date')
 )

hy_code  week_date
880301   2006/11/5            NaN
         2006/11/26     2006/11/5
880969   2021/12/26           NaN
         2022/1/2      2021/12/26
Name: last_week_date, dtype: object

Then merge it to the original data:

# ensure last_week_date is not pre-existing
# df = df.drop(columns='last_week_date')
# merge
df.merge(s, left_on=['hy_code','week_date'], right_index=True)

Output:

        hy_code        date   week_date last_week_date
340      880301  2006/10/31   2006/11/5            NaN
341      880301   2006/11/1   2006/11/5            NaN
342      880301   2006/11/2   2006/11/5            NaN
343      880301   2006/11/3   2006/11/5            NaN
355      880301  2006/11/21  2006/11/26      2006/11/5
482916   880969  2021/12/24  2021/12/26            NaN
482918   880969  2021/12/28    2022/1/2     2021/12/26
482919   880969  2021/12/29    2022/1/2     2021/12/26
482920   880969  2021/12/30    2022/1/2     2021/12/26
482921   880969  2021/12/31    2022/1/2     2021/12/26


问:
Angular Material Icons Not Rendering Within Component
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

```<code>{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}
</code>```

Here is my app.module...

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

Here's my module where I house my material imports...

```<code>import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}
</code>```

My component where I'm trying to use icons...

```<code>// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>
    <a routerLink="/home">
        <mat-icon>menu</mat-icon>
    </a>
</mat-toolbar>
</code>```

Here is my index.html...

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
</body>
</html>

</code>```

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

```<code>$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.
</code>```

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

答:
Your import order looks identical to mine, which works. Go over the install process again https://material.angular.io/guide/getting-started Add material with ng add.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { IconButtonComponent } from './icon-button/icon-button.component';
import { MaterialModule } from './material.module';

@NgModule({
  imports: [BrowserModule, FormsModule, MaterialModule],
  declarations: [AppComponent, HelloComponent, IconButtonComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}
```
<pre class="lang-js prettyprint-override"><code>import { NgModule } from "@angular/core";
import { MatButtonModule } from "@angular/material/button";
import { MatIconModule } from "@angular/material/icon";
import { MatCardModule } from '@angular/material/card';
import { MatToolbarModule } from '@angular/material/toolbar';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
    ]
})
export class MaterialModule {}
</code>```

Working example: https://stackblitz.com/edit/icon-button-dxlpsw?file=src%2Fapp%2Fmaterial.module.ts

Body:
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}

Here is my app.module...

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's my module where I house my material imports...

import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}

My component where I'm trying to use icons...

// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>

        <mat-icon>menu</mat-icon>

</mat-toolbar>

Here is my index.html...

<!doctype html>

  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

Body:
Your import order looks identical to mine, which works. Go over the install process again https://material.angular.io/guide/getting-started Add material with ng add.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { IconButtonComponent } from './icon-button/icon-button.component';
import { MaterialModule } from './material.module';

@NgModule({
  imports: [BrowserModule, FormsModule, MaterialModule],
  declarations: [AppComponent, HelloComponent, IconButtonComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

import { NgModule } from "@angular/core";
import { MatButtonModule } from "@angular/material/button";
import { MatIconModule } from "@angular/material/icon";
import { MatCardModule } from '@angular/material/card';
import { MatToolbarModule } from '@angular/material/toolbar';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
    ]
})
export class MaterialModule {}

Working example: https://stackblitz.com/edit/icon-button-dxlpsw?file=src%2Fapp%2Fmaterial.module.ts


问:
JUnit5 - Parallel execution @ParameterizedTest
I try to make parallel execution using JUnit5 + Maven Surefire Plugin. For that I made some settings:

```<code>      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                <properties>
                    <configurationParameters>
                        junit.jupiter.execution.parallel.enabled = true
                        junit.jupiter.execution.parallel.mode.default = concurrent
                    </configurationParameters>
                </properties>
            </configuration>
        </plugin>
    </plugins>
</code>```

And it works correctly for test methods that marked annotation @Test.
But I also have tests that marked annotation @ParameterizedTest and I expect that they should run in parallel using different values from the source. But it doesn't work as I expect - it runs in one thread.
Is there possible to fix that or it is a feature in JUnit 5.

答: Use @Execution(ExecutionMode.CONCURRENT) tag along with @ParameterizedTest to run the scripts in parallel for the each set of data.</p>

Body:
I try to make parallel execution using JUnit5 + Maven Surefire Plugin. For that I made some settings:

      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                <properties>
                    <configurationParameters>
                        junit.jupiter.execution.parallel.enabled = true
                        junit.jupiter.execution.parallel.mode.default = concurrent
                    </configurationParameters>
                </properties>
            </configuration>
        </plugin>
    </plugins>

And it works correctly for test methods that marked annotation @Test.
But I also have tests that marked annotation @ParameterizedTest and I expect that they should run in parallel using different values from the source. But it doesn't work as I expect - it runs in one thread.
Is there possible to fix that or it is a feature in JUnit 5.


问:
Static UILabel not showing in uiview
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

```<code>#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end
</code>```

答: Is this xib example from your MainWindow or your ViewController for the tab bar item?  Also, did you remember to change the NIB Name in the View Controller properties to the name, usually called SettingsViewController (the name of the xib file), which is what is usually generated if you used Xcode to create the class?  In your screen shot, it says "View from 'Settings'", which may not be correct.</p>

Title: Static UILabel not showing in uiview

Body:
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end


问:
Do I need to fence/sync when I use GL_MAP_COHERENT_BIT in a PMB?
I've seen contradictory documentation about it. In the Khronos documentation it's a bit ambiguous whether I need to glFinish (or variants) or not. I'm currently triple-buffering my buffer to avoid this problem (as I use the PMB dynamically) but it obviously consumes a lot of memory. I know that the flag makes the data-changes automatically visible both to the GPU and CPU, but don't know if I have to sync the writes with the reads. I need to know if I really need to sync the GL_MAP_COHERENT_BIT flag or there's an implicit synchronization.</p>

答:
There's no implicit synchronization because the driver/GPU has no idea when you're accessing the mapped pointer. That's what persistent mapping is all about, after all.

And yes, you still need synchronization. If you're trying to read something the GPU has written... you need the GPU to have written it before you can read it. And vice-versa for writing; you don't want to write to data that's being read by the GPU.

So use synchronization. If you're triple-buffering, odds are good that the wait-fence call will be a quick no-op.


问:
How to update Tweepy Streaming Python code
I had this code running for an earlier version of Python but now want to upgrade it to the latest version of Python and Tweepy however I cant seem to make it work.  Any help would be much appreciated!  The error I get is:

ImportError: cannot import name 'StreamListener' from 'tweepy.streaming' (C:\Users\mmanenica\anaconda3\lib\site-packages\tweepy\streaming.py)

```<code>import sys

from tweepy import OAuthHandler
from tweepy import API
from tweepy import Stream
from tweepy.streaming import StreamListener
import pandas as pd
from time import sleep
from random import randint

CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""

auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = API(auth, wait_on_rate_limit=True,
          wait_on_rate_limit_notify=True)

tweets = pd.DataFrame(columns=['description', 'location', 'text', 'name', 'user_created',
                  'followers', 'user_id', 'created', 'retweets', 'analysis', 'sentiment'])

class Listener(StreamListener):
    def __init__(self, output_file=sys.stdout):
        super(Listener,self).__init__()
        self.output_file = output_file
        self.counter = 0
        self.limit = 3
    def on_status(self, status):
        try:
            name = status.user.screen_name
            sleep(randint(100,190))
            print(name)
            api.create_friendship(name)

            print(status.text, file=self.output_file)

            self.counter += 1
            if self.counter <= self.limit:
                print(self.counter)
                return True
            else:
                print('Limit reached')
        except:
            print("Error in adding friendship")

    def on_error(self, status_code):
        print('Error ' + str(status_code))
        return False

listener = Listener()

stream = Stream(auth=api.auth, listener=listener)
try:

    stream.filter(track=['NFTs', 'Buying NFT', 'Buy NFT', '-filter:links', '-filter:retweets'])

    print('Start streaming.')
except KeyboardInterrupt:
    print("Stopped.")
finally:
    print('Done.')
    stream.disconnect()
</code>```

答:
First of all, make sure you have installed the last version of tweepy (4.5.0). You can guarantee this by typing in your terminal pip install --user --upgrade tweepy. You can try it without the --user part. It should upgrade too.
Now, with the latest version installed, you can start to collect a stream with some code like the following (based on https://docs.tweepy.org/en/stable/streaming.html):

```<code>import tweepy

class StreamCollector(tweepy.Stream):

    def on_data(self, data):
        print(data)

stream = StreamCollector(
  "Consumer Key here", "Consumer Secret here",
  "Access Token here", "Access Token Secret here"
)
stream.filter(track=["Obama"])
</code>```

Note that on_data method recieve the raw_data directly from Twitter. We are just printing it with the code above, but you can treat this data object like a python dictionary and extract whatever information about the tweets that you want.

I suggest, instead of printing the data object, something like the following (import json library and put the rest of the code inside def on_data, instead of print(data)):

```<code>import json

tweet_info = json.loads(data)
print(tweet_info['text'])
</code>```

Note that we have accessed the data object and extracted only the tweet ' text ' information. You can go deeper and access other informations from the tweet_info dictionary and also complement the code above with your necessities showed in the question.

Hope it helped. :)

Body:
I had this code running for an earlier version of Python but now want to upgrade it to the latest version of Python and Tweepy however I cant seem to make it work.  Any help would be much appreciated!  The error I get is:

ImportError: cannot import name 'StreamListener' from 'tweepy.streaming' (C:\Users\mmanenica\anaconda3\lib\site-packages\tweepy\streaming.py)

import sys

from tweepy import OAuthHandler
from tweepy import API
from tweepy import Stream
from tweepy.streaming import StreamListener
import pandas as pd
from time import sleep
from random import randint

CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""

auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = API(auth, wait_on_rate_limit=True,
          wait_on_rate_limit_notify=True)

tweets = pd.DataFrame(columns=['description', 'location', 'text', 'name', 'user_created',
                  'followers', 'user_id', 'created', 'retweets', 'analysis', 'sentiment'])

class Listener(StreamListener):
    def __init__(self, output_file=sys.stdout):
        super(Listener,self).__init__()
        self.output_file = output_file
        self.counter = 0
        self.limit = 3
    def on_status(self, status):
        try:
            name = status.user.screen_name
            sleep(randint(100,190))
            print(name)
            api.create_friendship(name)

            print(status.text, file=self.output_file)

            self.counter += 1
            if self.counter <= self.limit:
                print(self.counter)
                return True
            else:
                print('Limit reached')
        except:
            print("Error in adding friendship")

    def on_error(self, status_code):
        print('Error ' + str(status_code))
        return False

listener = Listener()

stream = Stream(auth=api.auth, listener=listener)
try:

    stream.filter(track=['NFTs', 'Buying NFT', 'Buy NFT', '-filter:links', '-filter:retweets'])

    print('Start streaming.')
except KeyboardInterrupt:
    print("Stopped.")
finally:
    print('Done.')
    stream.disconnect()

Body:
First of all, make sure you have installed the last version of tweepy (4.5.0). You can guarantee this by typing in your terminal pip install --user --upgrade tweepy. You can try it without the --user part. It should upgrade too.
Now, with the latest version installed, you can start to collect a stream with some code like the following (based on https://docs.tweepy.org/en/stable/streaming.html):

import tweepy

class StreamCollector(tweepy.Stream):

    def on_data(self, data):
        print(data)

stream = StreamCollector(
  "Consumer Key here", "Consumer Secret here",
  "Access Token here", "Access Token Secret here"
)
stream.filter(track=["Obama"])

Note that on_data method recieve the raw_data directly from Twitter. We are just printing it with the code above, but you can treat this data object like a python dictionary and extract whatever information about the tweets that you want.

I suggest, instead of printing the data object, something like the following (import json library and put the rest of the code inside def on_data, instead of print(data)):

import json

tweet_info = json.loads(data)
print(tweet_info['text'])

Note that we have accessed the data object and extracted only the tweet ' text ' information. You can go deeper and access other informations from the tweet_info dictionary and also complement the code above with your necessities showed in the question.

Hope it helped. :)


问:
Calculate partial eta-squared with type 3 sum of square in r
I have ran a 2 X 2 X 2 mixed ANOVA using ezANOVA and type 3 sum of squared in r.

The code looks like

```<code>ezANOVA(data = D, between = condition, within = c(Notation,Operation), dv = Acc, wid = ID,type=3)
</code>```

The output does not include the sum of square and the effect size was the generalized eta-squared. I am not sure how to calculate the partial eta-squared with type 3 sum of square in r.

I have tried to use the aov() function and eta_squared（） function from package effectsize, but the aov() function uses type 1 sum of square and so the effect size is different from the type 3 sum of square effect size.

Thus, I am wondering if there is any way to calculate the partial eta squared for a 3-way mixed ANOVA using type 3 sum of square in R.

Thank you in advance for your help

答:
Short of manually calculating partial eta squared, I wasn't able to find a function that worked with ezANOVA. I want to point out that the column labeled ges is the generalized eta squared (not partial, though).

However, I do have a method that will work for using SS 3 from the package jmv, along with both within and between ANOVA, while providing partial eta squared. It's a bit more of a mouthful to put together the function, as well. I added tons of options that you don't have outlined in your function in the question. I did this because this package's help isn't all that helpful. You definitely don't need to use all of these parameters, but at least you'll know what the package is expecting if you do use these options.

Your question isn't reproducible. I started by creating some arbitrary data to work with.

```<code>library(jmv)

# some fake data to work with
set.seed(253)
df1 <- data.frame(x = rnorm(200, 50, 3),
                  y = rnorm(200, 25, 5),
                  z = rnorm(200, 1.5, .1),
                  direc = as.factor(rep(c("left","right"), times = 100)))
</code>```

Next the repeated measures + between ANOVA:

```<code>fit = anovaRM(data = df1,
              ss = "3",                       # type of SS (1, 2, or 3)
              bs = list("direc"),             # between subjects
              bsTerms = list("direc"),        # between subjects
              rm = list(list(label = "tests", # within subjects
                             levels = c("pretest","mid","posttest"))),
                                   # can use levels(data$factor) if easier
                                   # does not have to be a real variable**
              rmCells = list(list(measure = "x",      # continuous value
                                  cell = "pretest"),  # group label
                             list(measure = "y",      # continuous value
                                  cell = "mid"),      # group label
                             list(measure = "z",      # continuous value
                                  cell = "posttest")), # group
              rmTerms = list("tests"),                # grouping variable/within measures
              emMeans = list(list("tests","direc")),  # all grouping vars (em tables)
              emmPlots = T,                  # show emm plot
              emmTables = T,                 # show emm tables
              effectSize = "partEta",        # use partial eta (multi options, see help)
              spherTests = T,                # use Mauchley test
              spherCorr = "GG",              # Greenhouse (multi options`, see help)
              leveneTest = T,                # check homogeneity (p > .05 = good**)
              qq = T,                        # plot normality validation qq plot
              postHocCorr = "tukey")         # use TukeyHSD
</code>```

This is the type of output you'll see when you call fit (or whatever you name your ANOVA object).

```<code>#
#  REPEATED MEASURES ANOVA
#
#  Within Subjects Effects
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#                   Sphericity Correction    Sum of Squares    df            Mean Square     F              p             η²-p
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#    tests          Greenhouse-Geisser          235493.0127      1.399431    168277.62891    9808.561967    < .0000001    0.9802130
#    tests:direc    Greenhouse-Geisser             105.1735      1.399431        75.15443       4.380599     0.0247609    0.0216454
#    Residual       Greenhouse-Geisser            4753.7668    277.087435        17.15620
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#    Note. Type 3 Sums of Squares
#
#
#  Between Subjects Effects
#  ──────────────────────────────────────────────────────────────────────────────────────────
#                Sum of Squares    df     Mean Square    F           p            η²-p
#  ──────────────────────────────────────────────────────────────────────────────────────────
#    direc             22.01519      1       22.01519    1.954001    0.1637204    0.0097723
#    Residual        2230.81167    198       11.26673
#  ──────────────────────────────────────────────────────────────────────────────────────────
#    Note. Type 3 Sums of Squares
#
#
#  ASSUMPTIONS
#
#  Tests of Sphericity
#  ───────────────────────────────────────────────────────────────────────────────
#             Mauchly's W    p             Greenhouse-Geisser ε    Huynh-Feldt ε
#  ───────────────────────────────────────────────────────────────────────────────
#    tests      0.5708482    < .0000001               0.6997157        0.7031690
#  ───────────────────────────────────────────────────────────────────────────────
#
#
#  Homogeneity of Variances Test (Levene's)
#  ───────────────────────────────────────────────
#         F              df1    df2    p
#  ───────────────────────────────────────────────
#    x    1.653217e-4      1    198    0.9897542
#    y     0.42682247      1    198    0.5143102
#    z     0.01824029      1    198    0.8927043
#  ───────────────────────────────────────────────
#
#
#  ESTIMATED MARGINAL MEANS
#
#  TESTS:DIREC
#
#  Estimated Marginal Means - tests:direc
#  ───────────────────────────────────────────────────────────────────────────
#    direc    tests       Mean         SE             Lower        Upper
#  ───────────────────────────────────────────────────────────────────────────
#    left     pretest     50.224630    0.307314811    49.618600    50.830660
#             mid         24.048471    0.508157857    23.046375    25.050567
#             posttest     1.499185    0.009470430     1.480509     1.517860
#    right    pretest     49.818121    0.307314811    49.212091    50.424151
#             mid         25.590657    0.508157857    24.588561    26.592753
#             posttest     1.512816    0.009470430     1.494140     1.531492
#  ───────────────────────────────────────────────────────────────────────────
#
</code>```

These are the two plots you'll see (or a variation of these: qq and emm).

This is really an amazing package, but it isn't very self-explanatory. If you have any questions, leave a comment.

Body:
I have ran a 2 X 2 X 2 mixed ANOVA using ezANOVA and type 3 sum of squared in r.

The code looks like

ezANOVA(data = D, between = condition, within = c(Notation,Operation), dv = Acc, wid = ID,type=3)

The output does not include the sum of square and the effect size was the generalized eta-squared. I am not sure how to calculate the partial eta-squared with type 3 sum of square in r.

I have tried to use the aov() function and eta_squared（） function from package effectsize, but the aov() function uses type 1 sum of square and so the effect size is different from the type 3 sum of square effect size.

Thus, I am wondering if there is any way to calculate the partial eta squared for a 3-way mixed ANOVA using type 3 sum of square in R.

Thank you in advance for your help

Body:
Short of manually calculating partial eta squared, I wasn't able to find a function that worked with ezANOVA. I want to point out that the column labeled ges is the generalized eta squared (not partial, though).

However, I do have a method that will work for using SS 3 from the package jmv, along with both within and between ANOVA, while providing partial eta squared. It's a bit more of a mouthful to put together the function, as well. I added tons of options that you don't have outlined in your function in the question. I did this because this package's help isn't all that helpful. You definitely don't need to use all of these parameters, but at least you'll know what the package is expecting if you do use these options.

Your question isn't reproducible. I started by creating some arbitrary data to work with.

library(jmv)

# some fake data to work with
set.seed(253)
df1 <- data.frame(x = rnorm(200, 50, 3),
                  y = rnorm(200, 25, 5),
                  z = rnorm(200, 1.5, .1),
                  direc = as.factor(rep(c("left","right"), times = 100)))

Next the repeated measures + between ANOVA:

fit = anovaRM(data = df1,
              ss = "3",                       # type of SS (1, 2, or 3)
              bs = list("direc"),             # between subjects
              bsTerms = list("direc"),        # between subjects
              rm = list(list(label = "tests", # within subjects
                             levels = c("pretest","mid","posttest"))),
                                   # can use levels(data$factor) if easier
                                   # does not have to be a real variable**
              rmCells = list(list(measure = "x",      # continuous value
                                  cell = "pretest"),  # group label
                             list(measure = "y",      # continuous value
                                  cell = "mid"),      # group label
                             list(measure = "z",      # continuous value
                                  cell = "posttest")), # group
              rmTerms = list("tests"),                # grouping variable/within measures
              emMeans = list(list("tests","direc")),  # all grouping vars (em tables)
              emmPlots = T,                  # show emm plot
              emmTables = T,                 # show emm tables
              effectSize = "partEta",        # use partial eta (multi options, see help)
              spherTests = T,                # use Mauchley test
              spherCorr = "GG",              # Greenhouse (multi options`, see help)
              leveneTest = T,                # check homogeneity (p > .05 = good**)
              qq = T,                        # plot normality validation qq plot
              postHocCorr = "tukey")         # use TukeyHSD

This is the type of output you'll see when you call fit (or whatever you name your ANOVA object).

#
#  REPEATED MEASURES ANOVA
#
#  Within Subjects Effects
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#                   Sphericity Correction    Sum of Squares    df            Mean Square     F              p             η²-p
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#    tests          Greenhouse-Geisser          235493.0127      1.399431    168277.62891    9808.561967    < .0000001    0.9802130
#    tests:direc    Greenhouse-Geisser             105.1735      1.399431        75.15443       4.380599     0.0247609    0.0216454
#    Residual       Greenhouse-Geisser            4753.7668    277.087435        17.15620
#  ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#    Note. Type 3 Sums of Squares
#
#
#  Between Subjects Effects
#  ──────────────────────────────────────────────────────────────────────────────────────────
#                Sum of Squares    df     Mean Square    F           p            η²-p
#  ──────────────────────────────────────────────────────────────────────────────────────────
#    direc             22.01519      1       22.01519    1.954001    0.1637204    0.0097723
#    Residual        2230.81167    198       11.26673
#  ──────────────────────────────────────────────────────────────────────────────────────────
#    Note. Type 3 Sums of Squares
#
#
#  ASSUMPTIONS
#
#  Tests of Sphericity
#  ───────────────────────────────────────────────────────────────────────────────
#             Mauchly's W    p             Greenhouse-Geisser ε    Huynh-Feldt ε
#  ───────────────────────────────────────────────────────────────────────────────
#    tests      0.5708482    < .0000001               0.6997157        0.7031690
#  ───────────────────────────────────────────────────────────────────────────────
#
#
#  Homogeneity of Variances Test (Levene's)
#  ───────────────────────────────────────────────
#         F              df1    df2    p
#  ───────────────────────────────────────────────
#    x    1.653217e-4      1    198    0.9897542
#    y     0.42682247      1    198    0.5143102
#    z     0.01824029      1    198    0.8927043
#  ───────────────────────────────────────────────
#
#
#  ESTIMATED MARGINAL MEANS
#
#  TESTS:DIREC
#
#  Estimated Marginal Means - tests:direc
#  ───────────────────────────────────────────────────────────────────────────
#    direc    tests       Mean         SE             Lower        Upper
#  ───────────────────────────────────────────────────────────────────────────
#    left     pretest     50.224630    0.307314811    49.618600    50.830660
#             mid         24.048471    0.508157857    23.046375    25.050567
#             posttest     1.499185    0.009470430     1.480509     1.517860
#    right    pretest     49.818121    0.307314811    49.212091    50.424151
#             mid         25.590657    0.508157857    24.588561    26.592753
#             posttest     1.512816    0.009470430     1.494140     1.531492
#  ───────────────────────────────────────────────────────────────────────────
#

These are the two plots you'll see (or a variation of these: qq and emm).

This is really an amazing package, but it isn't very self-explanatory. If you have any questions, leave a comment.