问:
How to extract values from string lists in R?
I want to extract the X-squared value and p-value (number only) from three string vectors.

```<code>smr.text1

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T1"
[5] "X-squared = 0.017361, df = 1, p-value = 0.8952"
[6] ""

smr.txt2

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T2"
[5] "X-squared = 2.5679e-32, df = 1, p-value = 1"
[6] ""

smr.text3

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T3"
[5] "X-squared = 0.17857, df = 1, p-value = 0.6726"
[6] ""
</code>```

It was easy for me to extract those values from the first string vector using indexing numbers:

```<code>> c1 <- as.numeric(str_sub(smr.txt1[5], 13, 20))

> c1
</code>```

[1] 0.017361

```<code>> p1 <- as.numeric(str_sub(smr.txt1[5], -6))

> p1
</code>```

[1] 0.8952

But in the second string vector I can't really do the same since it's a scientific number. Also I could do the same with the third string vector, but is there a better way, for example using a loop to extract these values only and put them in the same data frame? Thanks in advance!

答:
Instead of str_sub (which is position based and it wouldn't work when the start/end positions are not constant as in example 2) we may use regex lookaround to extract for p-value substring and the digits with . that follows (str_extract)

```<code>library(stringr)
f1 <- function(x, categ ="p-value") {
     as.numeric(str_extract(x,
        glue::glue("(?<={categ} \\= )[0-9.]+(e-[0-9]*)?")))
     }
</code>```

-testing

```<code>> f1("X-squared = 0.017361, df = 1, p-value = 0.8952")
[1] 0.8952
> f1("X-squared = 0.017361, df = 1, p-value = 0.8952", "X-squared")
[1] 0.017361
> f1("X-squared = 2.5679e-32, df = 1, p-value = 1")
[1] 1
> f1("X-squared = 2.5679e-32, df = 1, p-value = 1", "X-squared")
[1] 2.5679e-32
> f1("X-squared = 0.17857, df = 1, p-value = 0.6726")
[1] 0.6726
> f1("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857
</code>```

Another option would be to convert to data.frame with column names as 'X-squared', 'p-value', 'df' and then extract the column values

```<code>f2 <- function(x, categ = "p-value") {

   x1 <-  gsub(",\\s*", "\n", gsub("\\s*=\\s*", ":", x))
   type.convert(as.data.frame(read.dcf(textConnection(x1))),
       as.is = TRUE)[[categ]]

}
</code>```

-testing

```<code>> f2("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857
> f2("X-squared = 0.017361, df = 1, p-value = 0.8952")
[1] 0.8952
> f2("X-squared = 0.017361, df = 1, p-value = 0.8952", "X-squared")
[1] 0.017361
>  f2("X-squared = 2.5679e-32, df = 1, p-value = 1")
[1] 1
> f2("X-squared = 2.5679e-32, df = 1, p-value = 1", "X-squared")
[1] 2.5679e-32
> f2("X-squared = 0.17857, df = 1, p-value = 0.6726")
[1] 0.6726
> f2("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857
</code>```

It is not clear why we need to convert the output list output from chisq.test to string for extraction i.e. from the output of chisq.test, it is easier to extract with $ or [[

```<code>M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("F", "M"),
                    party = c("Democrat","Independent", "Republican"))
Xsq <- chisq.test(M)
Xsq$p.value
#[1] 2.953589e-07
Xsq$statistic[["X-squared"]]
[1] 30.07015
</code>```

Body:
I want to extract the X-squared value and p-value (number only) from three string vectors.

smr.text1

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T1"
[5] "X-squared = 0.017361, df = 1, p-value = 0.8952"
[6] ""

smr.txt2

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T2"
[5] "X-squared = 2.5679e-32, df = 1, p-value = 1"
[6] ""

smr.text3

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T3"
[5] "X-squared = 0.17857, df = 1, p-value = 0.6726"
[6] ""

It was easy for me to extract those values from the first string vector using indexing numbers:

> c1 <- as.numeric(str_sub(smr.txt1[5], 13, 20))

> c1

[1] 0.017361

> p1 <- as.numeric(str_sub(smr.txt1[5], -6))

> p1

[1] 0.8952

But in the second string vector I can't really do the same since it's a scientific number. Also I could do the same with the third string vector, but is there a better way, for example using a loop to extract these values only and put them in the same data frame? Thanks in advance!

Body:
Instead of str_sub (which is position based and it wouldn't work when the start/end positions are not constant as in example 2) we may use regex lookaround to extract for p-value substring and the digits with . that follows (str_extract)

library(stringr)
f1 <- function(x, categ ="p-value") {
     as.numeric(str_extract(x,
        glue::glue("(?<={categ} \\= )[0-9.]+(e-[0-9]*)?")))
     }

-testing

> f1("X-squared = 0.017361, df = 1, p-value = 0.8952")
[1] 0.8952
> f1("X-squared = 0.017361, df = 1, p-value = 0.8952", "X-squared")
[1] 0.017361
> f1("X-squared = 2.5679e-32, df = 1, p-value = 1")
[1] 1
> f1("X-squared = 2.5679e-32, df = 1, p-value = 1", "X-squared")
[1] 2.5679e-32
> f1("X-squared = 0.17857, df = 1, p-value = 0.6726")
[1] 0.6726
> f1("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857

Another option would be to convert to data.frame with column names as 'X-squared', 'p-value', 'df' and then extract the column values

f2 <- function(x, categ = "p-value") {

   x1 <-  gsub(",\\s*", "\n", gsub("\\s*=\\s*", ":", x))
   type.convert(as.data.frame(read.dcf(textConnection(x1))),
       as.is = TRUE)[[categ]]

}

-testing

> f2("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857
> f2("X-squared = 0.017361, df = 1, p-value = 0.8952")
[1] 0.8952
> f2("X-squared = 0.017361, df = 1, p-value = 0.8952", "X-squared")
[1] 0.017361
>  f2("X-squared = 2.5679e-32, df = 1, p-value = 1")
[1] 1
> f2("X-squared = 2.5679e-32, df = 1, p-value = 1", "X-squared")
[1] 2.5679e-32
> f2("X-squared = 0.17857, df = 1, p-value = 0.6726")
[1] 0.6726
> f2("X-squared = 0.17857, df = 1, p-value = 0.6726", "X-squared")
[1] 0.17857

It is not clear why we need to convert the output list output from chisq.test to string for extraction i.e. from the output of chisq.test, it is easier to extract with $ or [[

M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("F", "M"),
                    party = c("Democrat","Independent", "Republican"))
Xsq <- chisq.test(M)
Xsq$p.value
#[1] 2.953589e-07
Xsq$statistic[["X-squared"]]
[1] 30.07015


来源: stackexchange

问:
Why is Tomcat doubling my log lines in the catalina.out logfile?
Every time I look at Tomcat's catalina.out log file, I see double lines for every log entry.  Why is this happening?  Has this happen before to any Java (Tomcat) users?

答: Is your webapp's log4j.properties set to log to catalina.out? Tomcat already logs events there and if your application also logs there, that would probably explain the doubled entries.</p>

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: dmondark


问:
Bash history without line numbers
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

```<code>  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 histor<em>y</em></code>```

Historical graphic source.

Desired Output:

```<code>man history
ls
ll
clear
cd ~
histor<em>y</em></code>```

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

答:
history command does not have an option to suppress line numbers. You will have to combine multiple commands as everyone is suggesting:

Example :

```<code>history | cut -d' ' -f4- | sed 's/^ \(.*$\)/\1/g'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash history without line numbers

Body:
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 history

Historical graphic source.

Desired Output:

man history
ls
ll
clear
cd ~
history

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

Body:
history command does not have an option to suppress line numbers. You will have to combine multiple commands as everyone is suggesting:

Example :

history | cut -d' ' -f4- | sed 's/^ \(.*$\)/\1/g'


问:
Creating a vector of mobile variances of a time series
I am trying to create a vector of 50 trading days variances of a time series. With the following for cycle (which works fine for the mean) I am getting a vector of "NULL":

```<code>for(i in 1:1742){
  TSLA$mean50[i] = mean(TSLA$rendimenti[i:i+49])
}

for(i in 1:1742){
  TSLA$var50[i] = as.numeric(var(TSLA$rendimenti[i:i+49]))
}
</code>```

This is what my XTS data looks like

For some reasons if I add values manually (by replacing the index i with a specific value) the code works perfectly fine.

答:
```<code>for(i in 1:1742){
  TSLA$mean50[i] = mean(TSLA$rendimenti[i:(i+49)])
}

for(i in 1:1742){
  TSLA$var50[i] = as.numeric(var(TSLA$rendimenti[i:(i+49)]))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a vector of 50 trading days variances of a time series. With the following for cycle (which works fine for the mean) I am getting a vector of "NULL":

for(i in 1:1742){
  TSLA$mean50[i] = mean(TSLA$rendimenti[i:i+49])
}

for(i in 1:1742){
  TSLA$var50[i] = as.numeric(var(TSLA$rendimenti[i:i+49]))
}

This is what my XTS data looks like

For some reasons if I add values manually (by replacing the index i with a specific value) the code works perfectly fine.


问:
How to delete the last element from an array?
Now I'm working with the recursive backtracking,my assignment is to find the longest path in the maze,the mass is presented as the field covered with the coordinates,and the coordinates of the walls are sore in the file.
I have made a parser to parse the input file and build the walls,but I have also stored this coordinates in the array of an object type Coordinate,to check whether it is possible to move the next piece of the "snake" on the next field,then I have created this  method,now I have understood that I will need a method to remove the last coordinate from the array when I will use backtracking,how can I do it?the goal is not to use array lists or linked lists only arrays!
Thank you!

```<code>public class Coordinate {
int xCoord;
int yCoord;

 Coordinate(int x,int y) {
     this.xCoord=x;
     this.yCoord=y;
 }

 public int getX() {
     return this.xCoord;
 }

 public int getY() {
     return this.yCoord;
 }
 public String toString() {
     return this.xCoord + "," + this.yCoord;

 }

 }
</code>```

And

```<code>public class Row {
static final int MAX_NUMBER_OF_COORD=1000;

Coordinate[] coordArray;
int numberOfElements;

Row(){
    coordArray = new Coordinate[MAX_NUMBER_OF_COORD];
    numberOfElements=0;

   }

void add(Coordinate toAdd) {
    coordArray[numberOfElements]=toAdd;
    numberOfElements +=1;
}
boolean ifPossible(Coordinate c1){
    for(int i=0;i<numberOfElements;i++){

        if(coordArray[i].xCoord==c1.xCoord && coordArray[i].yCoord==c1.yCoord){
                return false;
            }
        }

    return true;
}

 }
</code>```

答:
Well, I found a more efficient option:

```<code>System.arraycopy(input, 0, new_array, 0, arr.length - 1);
</code>```

In a nutshell, this method will copy arr's elements to new_array, without the last element. However this method will require you to create and use another array than the original.

Body:
Now I'm working with the recursive backtracking,my assignment is to find the longest path in the maze,the mass is presented as the field covered with the coordinates,and the coordinates of the walls are sore in the file.
I have made a parser to parse the input file and build the walls,but I have also stored this coordinates in the array of an object type Coordinate,to check whether it is possible to move the next piece of the "snake" on the next field,then I have created this  method,now I have understood that I will need a method to remove the last coordinate from the array when I will use backtracking,how can I do it?the goal is not to use array lists or linked lists only arrays!
Thank you!

public class Coordinate {
int xCoord;
int yCoord;

 Coordinate(int x,int y) {
     this.xCoord=x;
     this.yCoord=y;
 }

 public int getX() {
     return this.xCoord;
 }

 public int getY() {
     return this.yCoord;
 }
 public String toString() {
     return this.xCoord + "," + this.yCoord;

 }

 }

And

public class Row {
static final int MAX_NUMBER_OF_COORD=1000;

Coordinate[] coordArray;
int numberOfElements;

Row(){
    coordArray = new Coordinate[MAX_NUMBER_OF_COORD];
    numberOfElements=0;

   }

void add(Coordinate toAdd) {
    coordArray[numberOfElements]=toAdd;
    numberOfElements +=1;
}
boolean ifPossible(Coordinate c1){
    for(int i=0;i<numberOfElements;i++){

        if(coordArray[i].xCoord==c1.xCoord && coordArray[i].yCoord==c1.yCoord){
                return false;
            }
        }

    return true;
}

 }

Body:
Well, I found a more efficient option:

System.arraycopy(input, 0, new_array, 0, arr.length - 1);

In a nutshell, this method will copy arr's elements to new_array, without the last element. However this method will require you to create and use another array than the original.


问:
How to place a view and a recyclerView in the same screen
I am trying to put recyclerView with a screen (Fragment) that has textView.

The .xml file of the fragment i'm trying to add to:

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ways.WaysFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/ways_quote"
        android:layout_marginTop="@dimen/card_margin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:textSize="18sp"
        android:layout_marginBottom="10dp"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:listitem="@layout/custom_ways_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I will try to describe the appearance (result) of what I tried to do with code and words, rather than pictures, I think it will be easily understood that way.

At first I added textView and just put the recyclerView under it.
And the result(appearance on my test device) I got look like:

```<code>Layout:
    ....
    TextView:
        ....

    ScrollView:
        ....
        and the contents of my recyclerView
</code>```

By this I mean, the textView doesn't scroll but the recyclerView does.

Next I put the textView and recyclerView inside the a single scrollView. But the textView scrolls seperately from the recyclerView, as if textView and recyclerView were in different scrollView.
the result(appearance on my test device) I got look like:

```<code>Layout:
    ....

    ScrollView:
        ....

        TextView:
            ....

    ScrollView:
        ....
        and the contents of my recyclerView
</code>```

And my desired Appearances, is:

```<code>Layout:
    ....

    ScrollView:
    ....

        TextView:
            ....
        Contents of my recyclerView:
            ....
</code>```

答:
I have discovered I named this question wrong it should have been "how to put header in a recyclerview using kotlin".

To do I created a new layout for the header, and an adapter.

Then I used ConcatAdapter To add the adapter of the header and recyclerview together.

I followed this tutorial on medium.

Body:
I am trying to put recyclerView with a screen (Fragment) that has textView.

The .xml file of the fragment i'm trying to add to:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ways.WaysFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/ways_quote"
        android:layout_marginTop="@dimen/card_margin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:textSize="18sp"
        android:layout_marginBottom="10dp"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:listitem="@layout/custom_ways_item" />
</androidx.constraintlayout.widget.ConstraintLayout>

I will try to describe the appearance (result) of what I tried to do with code and words, rather than pictures, I think it will be easily understood that way.

At first I added textView and just put the recyclerView under it.
And the result(appearance on my test device) I got look like:

Layout:
    ....
    TextView:
        ....

    ScrollView:
        ....
        and the contents of my recyclerView

By this I mean, the textView doesn't scroll but the recyclerView does.

Next I put the textView and recyclerView inside the a single scrollView. But the textView scrolls seperately from the recyclerView, as if textView and recyclerView were in different scrollView.
the result(appearance on my test device) I got look like:

Layout:
    ....

    ScrollView:
        ....

        TextView:
            ....

    ScrollView:
        ....
        and the contents of my recyclerView

And my desired Appearances, is:

Layout:
    ....

    ScrollView:
    ....

        TextView:
            ....
        Contents of my recyclerView:
            ....


问:
for loop repeats until value is less than three
I dont know why my for loop is not working. I have been trying for so long. It just runs for the do / while and gives return. Everything in the do / while loop. I have declared a macro outside the main function and I am using it as loop condition. I can't add more details, all I have is code.

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 01;
    char day2 = 02;
    char day3 = 03;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    do
    {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year || year > MAX_YEAR))
        {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        }

        if ((JAN > month || month > DEC))
        {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        }

        if ((JAN <= month && month <= DEC) && (MIN_YEAR <= year && year <= MAX_YEAR))
        {
            printf("\n*** Log date set! ***\n\n");
            break;
        }

    } while ((MIN_YEAR <= year || year <= MAX_YEAR) && (JAN <= month || month <= DEC));

    for (int i = 0; i < LOG_DAYS; i++)
    {
        printf(" %d", year);
        printf("-");
        printf(" %d", month);
        printf("-");
        printf(" %d",day1);
        printf("   Morning rating (0.0-5.0): ");
        scanf(" %d", &ratingMorning);

        if (ratingMorning < 0 || ratingMorning > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }

        printf("   Evening rating (0.0-5.0): ");
        scanf(" %d", &ratingEvening);

        if (ratingEvening < 0 || ratingEvening > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }
    }
    return 0;
}
</code>```

答:
The test in the while part of the do / while loop is incorrect.  It is much simpler to use a for(;;) loop and break when the input is correct, avoiding redundant and sometime inconsistent tests.

The scanf() conversion specifier for float is %f, not %d.

Here is a modified version:

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void) {
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 1;
    char day2 = 2;
    char day3 = 3;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    for (;;) {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        if (scanf(" %d %d", &year, &month) != 2) {
            printf("invalid input\n");
            return 1;
        }
        if (year < MIN_YEAR || year > MAX_YEAR) {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        } else
        if (month < JAN || month > DEC)) {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        } else {
            printf("\n*** Log date set! ***\n\n");
            break;
        }
    }

    for (int i = 0; i < LOG_DAYS; i++) {
        printf(" %d- %d- %d", year, month, day1);
        printf("   Morning rating (0.0-5.0): ");
        if (scanf("%f", &ratingMorning) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (ratingMorning < 0 || ratingMorning > 5) {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
            continue;
        }

        printf("   Evening rating (0.0-5.0): ");
        if (scanf("%f", &ratingEvening) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (ratingEvening < 0 || ratingEvening > 5) {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
            continue;
        }
        // ... handle the ratings and report success
    }
    return 0;
}
</code>```

Body:
I dont know why my for loop is not working. I have been trying for so long. It just runs for the do / while and gives return. Everything in the do / while loop. I have declared a macro outside the main function and I am using it as loop condition. I can't add more details, all I have is code.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 01;
    char day2 = 02;
    char day3 = 03;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    do
    {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        scanf(" %d %d", &year, &month);

        if ((MIN_YEAR > year || year > MAX_YEAR))
        {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        }

        if ((JAN > month || month > DEC))
        {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        }

        if ((JAN <= month && month <= DEC) && (MIN_YEAR <= year && year <= MAX_YEAR))
        {
            printf("\n*** Log date set! ***\n\n");
            break;
        }

    } while ((MIN_YEAR <= year || year <= MAX_YEAR) && (JAN <= month || month <= DEC));

    for (int i = 0; i < LOG_DAYS; i++)
    {
        printf(" %d", year);
        printf("-");
        printf(" %d", month);
        printf("-");
        printf(" %d",day1);
        printf("   Morning rating (0.0-5.0): ");
        scanf(" %d", &ratingMorning);

        if (ratingMorning < 0 || ratingMorning > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }

        printf("   Evening rating (0.0-5.0): ");
        scanf(" %d", &ratingEvening);

        if (ratingEvening < 0 || ratingEvening > 5)
        {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
        }
    }
    return 0;
}

Body:
The test in the while part of the do / while loop is incorrect.  It is much simpler to use a for(;;) loop and break when the input is correct, avoiding redundant and sometime inconsistent tests.

The scanf() conversion specifier for float is %f, not %d.

Here is a modified version:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022

#define LOG_DAYS 3

int main(void) {
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;
    char day1 = 1;
    char day2 = 2;
    char day3 = 3;
    float ratingMorning = 0;
    float ratingEvening = 0;

    printf("General Well-being Log\n"
        "======================\n");

    for (;;) {
        printf("Set the year and month for the well-being log (YYYY MM): ");
        if (scanf(" %d %d", &year, &month) != 2) {
            printf("invalid input\n");
            return 1;
        }
        if (year < MIN_YEAR || year > MAX_YEAR) {
            printf("   ERROR: The year must be between 2012 and 2022 inclusive\n");
        } else
        if (month < JAN || month > DEC)) {
            printf("   ERROR: Jan.(1) - Dec.(12)\n");
        } else {
            printf("\n*** Log date set! ***\n\n");
            break;
        }
    }

    for (int i = 0; i < LOG_DAYS; i++) {
        printf(" %d- %d- %d", year, month, day1);
        printf("   Morning rating (0.0-5.0): ");
        if (scanf("%f", &ratingMorning) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (ratingMorning < 0 || ratingMorning > 5) {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
            continue;
        }

        printf("   Evening rating (0.0-5.0): ");
        if (scanf("%f", &ratingEvening) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (ratingEvening < 0 || ratingEvening > 5) {
            printf("      ERROR: Rating must be between 0.0 and 5.0 inclusive!");
            continue;
        }
        // ... handle the ratings and report success
    }
    return 0;
}


问:
How to check whether a Storage item is set?
How can I check if an item is set in localStorage? Currently I am using

```<code>if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}
</code>```

答:
As @Christian C. Salvadó has mentioned above you can do
if (xxx === null){}

but null is also a falsy value, like so:

```<code>if (null){
console.log ("hello");
}
</code>```

which does not print "hello".

Body:
How can I check if an item is set in localStorage? Currently I am using

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

Body:
As @Christian C. Salvadó has mentioned above you can do
if (xxx === null){}

but null is also a falsy value, like so:

if (null){
console.log ("hello");
}

which does not print "hello".


问:
How to join multiple tables in Athena?
I have two queries that I want to join them. The first query gives me p_sales and p_views for each day and shop group as you can see below. It only shows all shop groups, but M, N, O shop groups don't have p_sales in those tables.

```<code>SELECT date,
    CASE
    WHEN shop_group = 'MM' THEN
    'M'
    WHEN shop_group = 'NN' THEN
    'N'
    WHEN shop_group = 'OO' THEN
    'O'
     WHEN shop_group = 'RR' THEN
    'R'
    END AS shop_group,
    sum(p_sales) as p_sales,
    sum(p_views) as p_views
FROM  Z
GROUP BY  1, 2
</code>```

Thus, the second query will give me `p_sales' for M, N, O shop groups with the following query.

```<code>with sales as (
    SELECT
        book_id,
        SUM(COALESCE(sales, estimated_sales)) AS p_sales
    FROM X
    WHERE DATE(date) >= CURRENT_DATE - INTERVAL '10' DAY
GROUP BY book_id
HAVING SUM(COALESCE(sales, estimated_sales)) >= 0
)

SELECT
    date,
    CASE
    WHEN shop_id = 1 THEN
    'M'
    WHEN shop_id = 2 THEN
    'N'
    WHEN shop_id = 3 THEN
    'O'
    END AS shop_group,
    cast(shop_id as varchar) shop_id,
    SUM(p_sales) p_sales
FROM Y
JOIN sales
ON Y.book_id = sales.book_id
WHERE date(date) = current_date - interval '10' day
AND shop_id in (1, 2, 3)
GROUP BY 1, 2, 3
</code>```

How can I add the second query into the first one? I want to add the second query into the first one because the first query contains p_views for all shop groups, and p_values for all shops except for M, N, O shop groups. But the second query contains only p_sales for three shop groups (M, N, O). This is why the second query should be a subquery of the first one so that I can see all values for all shop groups.

The desired output will contain p_views and p_sales for all shop groups.

答:
are finding below like both query under the  CTE</p>
```<code>  with firstQuery as
        (SELECT date,
       CASE
    WHEN shop_group = 'MM' THEN
    'M'
    WHEN shop_group = 'NN' THEN
    'N'
    WHEN shop_group = 'OO' THEN
    'O'
     WHEN shop_group = 'RR' THEN
    'R'
    END AS shop_group,
    sum(p_sales) as p_sales,
    sum(p_views) as p_views
FROM  Z
GROUP BY  1, 2

),
sales as (
        SELECT
            book_id,
            SUM(COALESCE(sales, estimated_sales)) AS p_sales
        FROM X
        WHERE DATE(date) >= CURRENT_DATE - INTERVAL '10' DAY
    GROUP BY book_id
    HAVING SUM(COALESCE(sales, estimated_sales)) >= 0
    )

    SELECT
        date,
        CASE
        WHEN shop_id = 1 THEN
        'M'
        WHEN shop_id = 2 THEN
        'N'
        WHEN shop_id = 3 THEN
        'O'
        END AS shop_group,
        cast(shop_id as varchar) shop_id,
        SUM(p_sales) p_sales
    FROM Y
    JOIN sales
    ON Y.book_id = sales.book_id
    WHERE date(date) = current_date - interval '10' day
    AND shop_id in (1, 2, 3)
    GROUP BY 1, 2, 3
</code>```

Title: How to join multiple tables in Athena?

Body:
I have two queries that I want to join them. The first query gives me p_sales and p_views for each day and shop group as you can see below. It only shows all shop groups, but M, N, O shop groups don't have p_sales in those tables.

SELECT date,
    CASE
    WHEN shop_group = 'MM' THEN
    'M'
    WHEN shop_group = 'NN' THEN
    'N'
    WHEN shop_group = 'OO' THEN
    'O'
     WHEN shop_group = 'RR' THEN
    'R'
    END AS shop_group,
    sum(p_sales) as p_sales,
    sum(p_views) as p_views
FROM  Z
GROUP BY  1, 2

Thus, the second query will give me `p_sales' for M, N, O shop groups with the following query.

with sales as (
    SELECT
        book_id,
        SUM(COALESCE(sales, estimated_sales)) AS p_sales
    FROM X
    WHERE DATE(date) >= CURRENT_DATE - INTERVAL '10' DAY
GROUP BY book_id
HAVING SUM(COALESCE(sales, estimated_sales)) >= 0
)

SELECT
    date,
    CASE
    WHEN shop_id = 1 THEN
    'M'
    WHEN shop_id = 2 THEN
    'N'
    WHEN shop_id = 3 THEN
    'O'
    END AS shop_group,
    cast(shop_id as varchar) shop_id,
    SUM(p_sales) p_sales
FROM Y
JOIN sales
ON Y.book_id = sales.book_id
WHERE date(date) = current_date - interval '10' day
AND shop_id in (1, 2, 3)
GROUP BY 1, 2, 3

How can I add the second query into the first one? I want to add the second query into the first one because the first query contains p_views for all shop groups, and p_values for all shops except for M, N, O shop groups. But the second query contains only p_sales for three shop groups (M, N, O). This is why the second query should be a subquery of the first one so that I can see all values for all shop groups.

The desired output will contain p_views and p_sales for all shop groups.

Body:
are finding below like both query under the  CTE

  with firstQuery as
        (SELECT date,
       CASE
    WHEN shop_group = 'MM' THEN
    'M'
    WHEN shop_group = 'NN' THEN
    'N'
    WHEN shop_group = 'OO' THEN
    'O'
     WHEN shop_group = 'RR' THEN
    'R'
    END AS shop_group,
    sum(p_sales) as p_sales,
    sum(p_views) as p_views
FROM  Z
GROUP BY  1, 2

),
sales as (
        SELECT
            book_id,
            SUM(COALESCE(sales, estimated_sales)) AS p_sales
        FROM X
        WHERE DATE(date) >= CURRENT_DATE - INTERVAL '10' DAY
    GROUP BY book_id
    HAVING SUM(COALESCE(sales, estimated_sales)) >= 0
    )

    SELECT
        date,
        CASE
        WHEN shop_id = 1 THEN
        'M'
        WHEN shop_id = 2 THEN
        'N'
        WHEN shop_id = 3 THEN
        'O'
        END AS shop_group,
        cast(shop_id as varchar) shop_id,
        SUM(p_sales) p_sales
    FROM Y
    JOIN sales
    ON Y.book_id = sales.book_id
    WHERE date(date) = current_date - interval '10' day
    AND shop_id in (1, 2, 3)
    GROUP BY 1, 2, 3


问:
build array of object from tree object
I'm trying to get into javascript's built-in reduce function and with the help of that build objects inside array.
But you can use whatever function or method you want.

Expected output

```<code>[
  { 'team1': [14697807552, 6858384], '2021': [14697807552, 6858384], 'pepsi': [null, null], 'cola': [14697807552, 6858384] },
  { 'team2': [10268029152, 6922128], '2021': [10268029152, 6922128], 'pepsi': [null, 4800], 'cola': [10268029152, 6917328] },
]
</code>```

What I tried to do

I created a function which takes array as an argument and calls reduce for each array's element.

function transform(arr, obj = {}) {
  return arr.reduce((acc, item) => {
    const newObj = {};
    newObj[item.name] = item.metrics;
    acc.push(newObj);

    if (item.children) {
      transform(item.children, newObj);
    }

    return acc;
  }, []);
}
console.log(transform(arr))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  const arr = [{
      "name": "team1",
      "metrics": [
        14697807552,
        6858384
      ],
      "children": [{
        "name": "2021",
        "metrics": [
          14697807552,
          6858384
        ],
        "children": [{
            "name": "pepsi",
            "metrics": [
              null,
              null
            ]
          },
          {
            "name": "cola",
            "metrics": [
              14697807552,
              6858384
            ]
          }
        ]
      }]
    },
    {
      "name": "team2",
      "metrics": [
        10268029152,
        6922128
      ],
      "children": [{
        "name": "2021",
        "metrics": [
          10268029152,
          6922128
        ],
        "children": [{
            "name": "pepsi",
            "metrics": [
              null,
              4800
            ]
          },
          {
            "name": "cola",
            "metrics": [
              10268029152,
              6917328
            ]
          }
        ]
      }]
    }
  ]
</script></code>```

But it gives me output that I don't want:

```<code>[
  { team1: [ 14697807552, 6858384 ] },
  { team2: [ 10268029152, 6922128 ] }
]
</code>```

If you didn't understand my question or you have question, ask me. Thanks for paying attention!

答:
The transform function doesn't do anything with the second argument obj, and so when you call transform recursively, newObj is not extended: this makes the recursive call losing any desired effect.

Instead of passing that second argument, you could use Object.assign to collect all objects that come back from recursion, and so merge them into one object:

const convert = arr =>
    arr?.map(({name, metrics, children}) =>
        Object.assign({[name]: metrics}, ...convert(children))) ?? [];

const arr = [{"name": "team1","metrics": [14697807552,6858384],"children": [{"name": "2021","metrics": [14697807552,6858384],"children": [{"name": "pepsi","metrics": [null,null]},{"name": "cola","metrics": [14697807552,6858384]}]}]},{"name": "team2","metrics": [10268029152,6922128],"children": [{"name": "2021","metrics": [10268029152,6922128],"children": [{"name": "pepsi","metrics": [null,4800]},{"name": "cola","metrics": [10268029152,6917328]}]}]}];

console.log(convert(arr));```

Please realise that a property like '2021' is an index and will be ordered before other, non-index properties. Even if you print an object like { 'a': 2, '2021': 1 } you'll get the keys in opposite order for that same reason.

If the order of the object keys is important to you, then you should go for an array of pairs in stead of a plain object. Arrays are the structure of choice when you need order, and plain objects should be used when order is not essential.

Title: build array of object from tree object

Body:
I'm trying to get into javascript's built-in reduce function and with the help of that build objects inside array.
But you can use whatever function or method you want.

Expected output

[
  { 'team1': [14697807552, 6858384], '2021': [14697807552, 6858384], 'pepsi': [null, null], 'cola': [14697807552, 6858384] },
  { 'team2': [10268029152, 6922128], '2021': [10268029152, 6922128], 'pepsi': [null, 4800], 'cola': [10268029152, 6917328] },
]

What I tried to do

I created a function which takes array as an argument and calls reduce for each array's element.

function transform(arr, obj = {}) {
  return arr.reduce((acc, item) => {
    const newObj = {};
    newObj[item.name] = item.metrics;
    acc.push(newObj);

    if (item.children) {
      transform(item.children, newObj);
    }

    return acc;
  }, []);
}
console.log(transform(arr))

But it gives me output that I don't want:

[
  { team1: [ 14697807552, 6858384 ] },
  { team2: [ 10268029152, 6922128 ] }
]

If you didn't understand my question or you have question, ask me. Thanks for paying attention!

Body:
The transform function doesn't do anything with the second argument obj, and so when you call transform recursively, newObj is not extended: this makes the recursive call losing any desired effect.

Instead of passing that second argument, you could use Object.assign to collect all objects that come back from recursion, and so merge them into one object:

const convert = arr =>
    arr?.map(({name, metrics, children}) =>
        Object.assign({[name]: metrics}, ...convert(children))) ?? [];

const arr = [{"name": "team1","metrics": [14697807552,6858384],"children": [{"name": "2021","metrics": [14697807552,6858384],"children": [{"name": "pepsi","metrics": [null,null]},{"name": "cola","metrics": [14697807552,6858384]}]}]},{"name": "team2","metrics": [10268029152,6922128],"children": [{"name": "2021","metrics": [10268029152,6922128],"children": [{"name": "pepsi","metrics": [null,4800]},{"name": "cola","metrics": [10268029152,6917328]}]}]}];

console.log(convert(arr));

Please realise that a property like '2021' is an index and will be ordered before other, non-index properties. Even if you print an object like { 'a': 2, '2021': 1 } you'll get the keys in opposite order for that same reason.

If the order of the object keys is important to you, then you should go for an array of pairs in stead of a plain object. Arrays are the structure of choice when you need order, and plain objects should be used when order is not essential.


问:
Conditional mean in table pandas
```<code>df = {'Name': ['Gabriel', 'João', 'Marcela', 'Augusto', 'Mariana', 'Ana', 'Paula'],
      'Grupo Funcional':  ['Analista','Analista','Analista','Assessor','Diretor','Diretor','Gerente'],
      'Salary': ['1000', '1700', '1200', '600', '2000', '3000', '4000'],
        }

df = pd.DataFrame(df)

display (df)
</code>```

What i need is the mean of 'Salary' by 'Grupo Funcional', something like that:

Mean Analista = R$ 3.500,00

Mean Diretor = R$ 2.500,00

I know i can get this by .groupby, but this table has another columns like "Place of Work" and "Residence", so i would like a way to filter as many variables i want and get the mean of the Salary

答:
You can do that with something like the following</p>
```<code>df = {'Name': ['Gabriel', 'João', 'Marcela', 'Augusto', 'Mariana', 'Ana', 'Paula'],
      'Grupo Funcional':  ['Analista','Analista','Analista','Assessor','Diretor','Diretor','Gerente'],
      'Salary': [1000, 1700, 1200, 600, 2000, 3000, 4000],
        }

df = pd.DataFrame(df)

df2 = df.groupby("Grupo Funcional").agg({"Salary":"mean"}).reset_index()

print(df2)
  Grupo Funcional  Salary
0        Analista    1300
1        Assessor     600
2         Diretor    2500
3         Gerente    4000
</code>```

Title: Conditional mean in table pandas

Body:
df = {'Name': ['Gabriel', 'João', 'Marcela', 'Augusto', 'Mariana', 'Ana', 'Paula'],
      'Grupo Funcional':  ['Analista','Analista','Analista','Assessor','Diretor','Diretor','Gerente'],
      'Salary': ['1000', '1700', '1200', '600', '2000', '3000', '4000'],
        }

df = pd.DataFrame(df)

display (df)

What i need is the mean of 'Salary' by 'Grupo Funcional', something like that:

Mean Analista = R$ 3.500,00

Mean Diretor = R$ 2.500,00

I know i can get this by .groupby, but this table has another columns like "Place of Work" and "Residence", so i would like a way to filter as many variables i want and get the mean of the Salary

Body:
You can do that with something like the following

df = {'Name': ['Gabriel', 'João', 'Marcela', 'Augusto', 'Mariana', 'Ana', 'Paula'],
      'Grupo Funcional':  ['Analista','Analista','Analista','Assessor','Diretor','Diretor','Gerente'],
      'Salary': [1000, 1700, 1200, 600, 2000, 3000, 4000],
        }

df = pd.DataFrame(df)

df2 = df.groupby("Grupo Funcional").agg({"Salary":"mean"}).reset_index()

print(df2)
  Grupo Funcional  Salary
0        Analista    1300
1        Assessor     600
2         Diretor    2500
3         Gerente    4000


问:
Excel - Count days for each month from start and end date range
I am trying to write an excel formula which can be dragged across a row of cells to give the number of days in each month between two specified dates. Can any one help with Forumla or Macro please.

Example under attached image B4:C4 has total 5 days vacation, 3 in Aug 2021 and 2 days in Sep 2021.

答:
From the image it seems the Dates row is actual excel date and not in text format. Therefore, the below formula should work:

Formula used in cell E2

```<code>=SUMPRODUCT(N(TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy")))
</code>```

• And Fill Down & Fill Right !

• The below formula creates an array of date numbers from vacation start date to vacation end of the time period.

```<code>ROW(INDIRECT($A2&":"&$B2))
</code>```

• The TEXT function is used to convert the serial date numbers to the Month & Year, in the same format as the dates are in cell E1:K1 (refer the image below),

```<code>TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")
</code>```

• Now compare the months & years to the months and years in Row 1, and get an array of TRUE/FALSE,

```<code>TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy")
</code>```

•  N function converts that to an array of 0 & 1, and we SUM the result using SUMPRODUCT Function,

```<code>N(TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy"))
</code>```

Body:
From the image it seems the Dates row is actual excel date and not in text format. Therefore, the below formula should work:

Formula used in cell E2

=SUMPRODUCT(N(TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy")))

• And Fill Down & Fill Right !

• The below formula creates an array of date numbers from vacation start date to vacation end of the time period.

ROW(INDIRECT($A2&":"&$B2))

• The TEXT function is used to convert the serial date numbers to the Month & Year, in the same format as the dates are in cell E1:K1 (refer the image below),

TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")

• Now compare the months & years to the months and years in Row 1, and get an array of TRUE/FALSE,

TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy")

•  N function converts that to an array of 0 & 1, and we SUM the result using SUMPRODUCT Function,

N(TEXT(ROW(INDIRECT($A2&":"&$B2)),"mmm-yy")=TEXT(E$1,"mmm-yy"))


问:
Dagger/Hilt missing binding. Repository cannot be provided without an @Provides-annotated method
I have this interface

```<code>interface ShowsScheduleRepository {
    suspend fun getShowsSchedule(medium: String, timeSlot: String): ShowsSchedule
}
</code>```

which is provided in this class

```<code>class GetShowsScheduleUseCase @Inject constructor(
    private val repository: ShowsScheduleRepository
)
</code>```

by

```<code>@Provides
@Singleton
fun provideShowsScheduleRepository(api: TDRetrofitApi): ShowsScheduleRepository {
    return ShowsScheduleRepoImpl(api)
}
</code>```

and then this class is injected in a viewModel

```<code>@HiltViewModel
class HomeFragmentViewModel @Inject constructor(
    private val getShowsSchedule: GetShowsScheduleUseCase
) : ViewModel() {
</code>```

And when I am trying to build I get the error that it cannot provide a ShowsScheduleRepository without an  @Provides-annotated method

答: The provideShowsScheduleRepository method should be placed in a module class (by saying that I mean a class annotated with @Module). Are you sure that this module is installed in the correct scope? If not, try adding @InstallIn(SingletonComponent::class). (You can replace SingletonComponent with any other component that is described here based on your needs)

Body:
I have this interface

interface ShowsScheduleRepository {
    suspend fun getShowsSchedule(medium: String, timeSlot: String): ShowsSchedule
}

which is provided in this class

class GetShowsScheduleUseCase @Inject constructor(
    private val repository: ShowsScheduleRepository
)

by

@Provides
@Singleton
fun provideShowsScheduleRepository(api: TDRetrofitApi): ShowsScheduleRepository {
    return ShowsScheduleRepoImpl(api)
}

and then this class is injected in a viewModel

@HiltViewModel
class HomeFragmentViewModel @Inject constructor(
    private val getShowsSchedule: GetShowsScheduleUseCase
) : ViewModel() {

And when I am trying to build I get the error that it cannot provide a ShowsScheduleRepository without an  @Provides-annotated method


问:
I need some random image spawn in my game but i just don't know now
I'm trying to do a scroller type game but I need help with the coins spawning.

This is my code:

```<code>import os
import pygame

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode(((0, 0)), pygame.FULLSCREEN)
pygame.display.set_caption('First game')
image = pygame.image.load('Game_icon.png')
pygame.display.set_icon(image)

GREEN = (0, 150, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0,)
FPS = 60
FPS_SLOMO = 30
VEL = 5
PLAYER_WIDTH, PLAYER_HEIGHT = 55, 55
COIN_WIDTH, COIN_HEIGHT = 20, 20

PLAYER_IMAGE = pygame.image.load(os.path.join('Assets', 'Player.png'))
PLAYER = pygame.transform.rotate(pygame.transform.scale(
    PLAYER_IMAGE, (PLAYER_WIDTH, PLAYER_HEIGHT)), 0)

COIN_IMAGE = pygame.image.load(os.path.join("Assets", 'coin.png'))
COIN = pygame.transform.rotate(pygame.transform.scale(
    COIN_IMAGE, (COIN_WIDTH, COIN_HEIGHT)), 0)

def draw_window(player, coin):
    WIN.fill(GREEN)
    WIN.blit(PLAYER, (player.x, player.y))
    WIN.blit(COIN, (coin.x, coin.y))
    pygame.display.update()

def main():
    player = pygame.Rect(100, 300, PLAYER_WIDTH, PLAYER_HEIGHT)
    coin = pygame.Rect(100, 100, COIN_WIDTH, COIN_HEIGHT)
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_a]:
            player.x -= VEL
        if keys_pressed[pygame.K_d]:
            player.x += VEL
        if keys_pressed[pygame.K_w]:
            player.y -= VEL
        if keys_pressed[pygame.K_s]:
            player.y += VEL
        if keys_pressed[pygame.K_LSHIFT]:
            clock.tick(FPS_SLOMO)
        draw_window(player, coin)

    pygame.quit()

if __name__ == "__main__":
    main()
</code>```

答:
If I understand your problem well, it could be solved like this:

```<code>import random

NUM_COINS = 100

coins = [[
random.randint(0, WIDTH), random.randint(0, HEIGHT)] for _ in range(NUM_COINS)]

def draw_window(player):
    WIN.fill(GREEN)
    WIN.blit(PLAYER, (player.x, player.y))
    for pos in coins:
        WIN.blit(COIN, (pos[0], pos[1]))
    pygame.display.update()
</code>```

I hope it will help you, Adam.

PS: I would recommend reducing the VEL and increasing the FPS for a better game experience

Body:
I'm trying to do a scroller type game but I need help with the coins spawning.

This is my code:

import os
import pygame

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode(((0, 0)), pygame.FULLSCREEN)
pygame.display.set_caption('First game')
image = pygame.image.load('Game_icon.png')
pygame.display.set_icon(image)

GREEN = (0, 150, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0,)
FPS = 60
FPS_SLOMO = 30
VEL = 5
PLAYER_WIDTH, PLAYER_HEIGHT = 55, 55
COIN_WIDTH, COIN_HEIGHT = 20, 20

PLAYER_IMAGE = pygame.image.load(os.path.join('Assets', 'Player.png'))
PLAYER = pygame.transform.rotate(pygame.transform.scale(
    PLAYER_IMAGE, (PLAYER_WIDTH, PLAYER_HEIGHT)), 0)

COIN_IMAGE = pygame.image.load(os.path.join("Assets", 'coin.png'))
COIN = pygame.transform.rotate(pygame.transform.scale(
    COIN_IMAGE, (COIN_WIDTH, COIN_HEIGHT)), 0)

def draw_window(player, coin):
    WIN.fill(GREEN)
    WIN.blit(PLAYER, (player.x, player.y))
    WIN.blit(COIN, (coin.x, coin.y))
    pygame.display.update()

def main():
    player = pygame.Rect(100, 300, PLAYER_WIDTH, PLAYER_HEIGHT)
    coin = pygame.Rect(100, 100, COIN_WIDTH, COIN_HEIGHT)
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_a]:
            player.x -= VEL
        if keys_pressed[pygame.K_d]:
            player.x += VEL
        if keys_pressed[pygame.K_w]:
            player.y -= VEL
        if keys_pressed[pygame.K_s]:
            player.y += VEL
        if keys_pressed[pygame.K_LSHIFT]:
            clock.tick(FPS_SLOMO)
        draw_window(player, coin)

    pygame.quit()

if __name__ == "__main__":
    main()

Body:
If I understand your problem well, it could be solved like this:

import random

NUM_COINS = 100

coins = [[
random.randint(0, WIDTH), random.randint(0, HEIGHT)] for _ in range(NUM_COINS)]

def draw_window(player):
    WIN.fill(GREEN)
    WIN.blit(PLAYER, (player.x, player.y))
    for pos in coins:
        WIN.blit(COIN, (pos[0], pos[1]))
    pygame.display.update()

I hope it will help you, Adam.

PS: I would recommend reducing the VEL and increasing the FPS for a better game experience


问:
jquery-based HTML5 forms validation
I am searching for a jquery-based validation library which becomes active if the browser isn't HTML5 compliant for the particular attribute (e.g. 'required', 'placeholder', etc).  I've searched and found numerous libraries but either they aren't yet production-quality or, as is the case with the default JQuery Validation library, they don't follow the HTML5 syntax;  they use classes instead of attributes to specify the rules.   I want my HTML to be natively compatible with the new browsers so that validation library in particular doesn't meet the requirements.</p>

答: jQuery Validate added improved HTML5 support last week. In particular, you can use the required attribute and HTML5 types instead of using the class attribute.</p>

Title: jquery-based HTML5 forms validation


问:
Strict Secure Cookie policy error in AdMob after updating to Android 11
After updating my app to compile with API level 30 (Android R, 11), I can't see AdMob test ads, and I'm receiving this error in the log:

Strict Secure Cookie policy does not allow setting a secure cookie for
http://googleads.g.doubleclick.net/ for apps targeting >= R. Please
either use the 'https:' scheme for this URL or omit the 'Secure'
directive in the cookie value.

I'm using the last AdMob version, and I don't have "org.apache.http.legacy" references in Gradle or manifest.

答:
I'm using flutter and I'm facing the same issue while implementing banner test ads.
Just add the below in android manifest file under application:

```<code>android:usesCleartextTraffic="true"
</code>```

and issue will be resolved.

Body:
I'm using flutter and I'm facing the same issue while implementing banner test ads.
Just add the below in android manifest file under application:

android:usesCleartextTraffic="true"

and issue will be resolved.


问:
When I open new tab I read "chrome://new tab"
Tomorrow when I open new tab I read "chrome://new tab". What is that? is dangerous? How can I remove this?</p>

答:
The url "chrome://newtab" means a new tab opened by chrome itself.
It is secure and configurable which can be modified in Settings -> On startup.


问:
Terraform AWS: "ssh: unable to authenticate, attempted methods [none publickey]"
I'm experimenting with IaC automation. I'm standing up this instance (with associated simple VPC infrastructure, not shown):

```<code>resource "aws_instance" "ansible" {
  ami = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  associate_public_ip_address = true
  subnet_id = aws_subnet.public.id
  key_name = aws_key_pair.instance.key_name
  vpc_security_group_ids = [aws_security_group.allow-ssh.id]
  user_data = "${file("ansible.conf")}"

  ebs_block_device {
    device_name = "/dev/sda1"
    delete_on_termination = true
    volume_size = 8
    volume_type = "gp3"
  }

  metadata_options {
    http_endpoint = "enabled"
    http_tokens = "required"
  }

  tags = {
    Name = "ansible01"
  }
}

resource "aws_security_group" "allow-ssh" {
  name = "allow-ssh"
  description = "A security group that allows inbound web traffic (TCP ports 80 and 443)."
  vpc_id = aws_vpc.vpc.id
    ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
    description = "Allow SSH traffic"
  }
  egress {
    from_port = 0
    to_port = 0
    protocol = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
</code>```

I have this resource block with provisioners in Terraform:

```<code>resource "null_resource" remoteExecProvisionerWFolder {
  depends_on = [
    local_file.hosts_cfg
  ]

  provisioner "file" {
    source      = "hosts.cfg"
    destination = "/home/ubuntu/hosts"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo mkdir /etc/ansible",
      "sudo mv /home/ubuntu/hosts /etc/ansible/"
    ]
  }

  connection {
    host     = aws_instance.ansible.public_ip
    type     = "ssh"
    user     = "ubuntu"
    private_key = aws_secretsmanager_secret_version.secret_version.secret_string
  }
}
</code>```

private_key is referencing a key pair which I designed to go straight into Secrets Manager (so no need to store locally):

```<code># KEY PAIR

resource "tls_private_key" "instance" {
  algorithm = "RSA"
}

resource "aws_key_pair" "instance" {
  key_name   = "wp-ansible-ssh21205"
  public_key = tls_private_key.instance.public_key_openssh
  tags = {
    Name = "wp-ansible-ssh21205"
  }
}

# SECRETS

resource "aws_secretsmanager_secret" "secret" {
  name = "wp-ansible-ssh21205"
}

resource "aws_secretsmanager_secret_version" "secret_version" {
  secret_id     = aws_secretsmanager_secret.secret.id
  secret_string = tls_private_key.instance.private_key_pem
}
</code>```

...but when I run apply, I get this error:

```<code>Error: timeout - last error: SSH authentication failed (ubuntu@X.X.X.X:22): ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain
</code>```

The kicker: I swear I had this working. I was able to run Terraform Apply, stand up the EC2 with generated key pair which was then placed into Secrets Manager, and the provisioner was running by successfully referencing the secret_string. Build completed with no errors and I could SSH into the instance and see my proivisioned files and changes.

But then I expanded my experimentation and changed some things, now it's broken. I've put things back to the working configuration as best as I can recall, but I still get this error so I must be missing something here. Any ideas?

答: I solved the issue. It ended being a typo in my instance code - I don't recall exactly what, but it was kind of random and not intuitively connected to SSH keys in any way. So all I can say is this: if you encounted a bizarre issue that you can't figure out, try going back to the start of the your TF template and double-check that everything is formatted/spelled correctly.</p>

Body:
I'm experimenting with IaC automation. I'm standing up this instance (with associated simple VPC infrastructure, not shown):

resource "aws_instance" "ansible" {
  ami = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  associate_public_ip_address = true
  subnet_id = aws_subnet.public.id
  key_name = aws_key_pair.instance.key_name
  vpc_security_group_ids = [aws_security_group.allow-ssh.id]
  user_data = "${file("ansible.conf")}"

  ebs_block_device {
    device_name = "/dev/sda1"
    delete_on_termination = true
    volume_size = 8
    volume_type = "gp3"
  }

  metadata_options {
    http_endpoint = "enabled"
    http_tokens = "required"
  }

  tags = {
    Name = "ansible01"
  }
}

resource "aws_security_group" "allow-ssh" {
  name = "allow-ssh"
  description = "A security group that allows inbound web traffic (TCP ports 80 and 443)."
  vpc_id = aws_vpc.vpc.id
    ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
    description = "Allow SSH traffic"
  }
  egress {
    from_port = 0
    to_port = 0
    protocol = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

I have this resource block with provisioners in Terraform:

resource "null_resource" remoteExecProvisionerWFolder {
  depends_on = [
    local_file.hosts_cfg
  ]

  provisioner "file" {
    source      = "hosts.cfg"
    destination = "/home/ubuntu/hosts"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo mkdir /etc/ansible",
      "sudo mv /home/ubuntu/hosts /etc/ansible/"
    ]
  }

  connection {
    host     = aws_instance.ansible.public_ip
    type     = "ssh"
    user     = "ubuntu"
    private_key = aws_secretsmanager_secret_version.secret_version.secret_string
  }
}

private_key is referencing a key pair which I designed to go straight into Secrets Manager (so no need to store locally):

# KEY PAIR

resource "tls_private_key" "instance" {
  algorithm = "RSA"
}

resource "aws_key_pair" "instance" {
  key_name   = "wp-ansible-ssh21205"
  public_key = tls_private_key.instance.public_key_openssh
  tags = {
    Name = "wp-ansible-ssh21205"
  }
}

# SECRETS

resource "aws_secretsmanager_secret" "secret" {
  name = "wp-ansible-ssh21205"
}

resource "aws_secretsmanager_secret_version" "secret_version" {
  secret_id     = aws_secretsmanager_secret.secret.id
  secret_string = tls_private_key.instance.private_key_pem
}

...but when I run apply, I get this error:

Error: timeout - last error: SSH authentication failed (ubuntu@X.X.X.X:22): ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

The kicker: I swear I had this working. I was able to run Terraform Apply, stand up the EC2 with generated key pair which was then placed into Secrets Manager, and the provisioner was running by successfully referencing the secret_string. Build completed with no errors and I could SSH into the instance and see my proivisioned files and changes.

But then I expanded my experimentation and changed some things, now it's broken. I've put things back to the working configuration as best as I can recall, but I still get this error so I must be missing something here. Any ideas?


问:
React how to specify animation @keyframes and classes locally
```<code>function Loader() {
    var style = {
        border: '16px solid #eee',
        borderTop: '16px solid #3ae',
        borderRadius: '50%',
        width: '1cm',
        height: '1cm',
        animation: 'spin 2s linear infinite',
    }
    return (
        <div style={style}>
        <style>{`
            @keyframes spin {
                 0% { transform: rotate(0deg); }
                 100% { transform: rotate(360deg); }
            }
        `}</style>
        </div>
    )
}
</code>```

Is there a way to specify @keyframes locally to the component (a component function in this example) without using an inlined string?

Also if you specify

答:
Here's how we will achieve it without adding any dependency.

```<code>{/*Your Js File Code */}

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import React from "react";
import "./test.css";

class Anim extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animationName: ""
    };
  }

  addStylesheetRules(rules) {
    var styleEl = document.createElement("style");
    document.head.appendChild(styleEl);
    var styleSheet = styleEl.sheet;
    styleSheet.insertRule(rules, 0);
  }

  clickHdl() {
    let animationName = `animation${Math.round(Math.random() * 100)}`;
    let keyframes = `
    @-webkit-keyframes ${animationName} {
        10% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        90% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        100% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
    }`;

    this.addStylesheetRules(keyframes);

    this.setState({
      animationName: animationName
    });
  }

  render() {
    let style = {
      animationName: this.state.animationName,
      animationTimingFunction: "ease-in-out",
      animationDuration: "0.6s",
      animationDelay: "0.0s",
      animationIterationCount: 1,
      animationDirection: "normal",
      animationFillMode: "forwards"
    };

    return (
      <div>
        <button type="button" onClick={this.clickHdl.bind(this)}>
          Animation!
        </button>
        <div className="box" style={style}></div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Anim />
  </StrictMode>,
  rootElement
);

{/*Css Code test.css */}

.box {
  width: 30px;
  height: 30px;
  background: red;
  border-radius: 50%;
  cursor: pointer;
}
</code>```

Demo: https://codesandbox.io/s/reverent-sun-qjo91?file=/src/index.js

Body:
function Loader() {
    var style = {
        border: '16px solid #eee',
        borderTop: '16px solid #3ae',
        borderRadius: '50%',
        width: '1cm',
        height: '1cm',
        animation: 'spin 2s linear infinite',
    }
    return (

    )
}

Is there a way to specify @keyframes locally to the component (a component function in this example) without using an inlined string?

Also if you specify

Body:
Here's how we will achieve it without adding any dependency.

{/*Your Js File Code */}

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import React from "react";
import "./test.css";

class Anim extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animationName: ""
    };
  }

  addStylesheetRules(rules) {
    var styleEl = document.createElement("style");
    document.head.appendChild(styleEl);
    var styleSheet = styleEl.sheet;
    styleSheet.insertRule(rules, 0);
  }

  clickHdl() {
    let animationName = `animation${Math.round(Math.random() * 100)}`;
    let keyframes = `
    @-webkit-keyframes ${animationName} {
        10% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        90% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        100% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
    }`;

    this.addStylesheetRules(keyframes);

    this.setState({
      animationName: animationName
    });
  }

  render() {
    let style = {
      animationName: this.state.animationName,
      animationTimingFunction: "ease-in-out",
      animationDuration: "0.6s",
      animationDelay: "0.0s",
      animationIterationCount: 1,
      animationDirection: "normal",
      animationFillMode: "forwards"
    };

    return (
      <div>
        <button type="button" onClick={this.clickHdl.bind(this)}>
          Animation!
        </button>
        <div className="box" style={style}></div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Anim />
  </StrictMode>,
  rootElement
);

{/*Css Code test.css */}

.box {
  width: 30px;
  height: 30px;
  background: red;
  border-radius: 50%;
  cursor: pointer;
}

Demo: https://codesandbox.io/s/reverent-sun-qjo91?file=/src/index.js


问:
How can I run a JHipster app on Ubuntu with Java 11?
I'm trying to run an app generated by JHipster 5.7. When I try to run the mnvw file, I get:

```<code>[WARNING] Rule 1: org.apache.maven.plugins.enforcer.RequireJavaVersion failed with message:
You are running an incompatible version of Java. JHipster requires JDK 1.8
</code>```

followed by a string of errors and a failure to run. I am indeed using JDK version 11. I've found some seemingly relevant information online but it's very difficult for me to really understand what any of it means, or even be entirely sure if it's relevant to my problem.

To avoid an XY problem I'm just going to ask my question in the most general, nooby way possible: how can I run a JHipster 5 app on Ubuntu (18.10) when I have JDK 11 installed? (If the answer is to install a different version of Java this is fine, but I don't know how to do this or how to tell JHipster to use that version).

答:
I had the same problem, I resolved it by updating also my JAVA_HOME env variable.
Usually I don't use it, and I switch version using update-alternatives but JHipster seems to use JAVA_HOME and not the version called by the system</p>

Body:
I'm trying to run an app generated by JHipster 5.7. When I try to run the mnvw file, I get:

[WARNING] Rule 1: org.apache.maven.plugins.enforcer.RequireJavaVersion failed with message:
You are running an incompatible version of Java. JHipster requires JDK 1.8

followed by a string of errors and a failure to run. I am indeed using JDK version 11. I've found some seemingly relevant information online but it's very difficult for me to really understand what any of it means, or even be entirely sure if it's relevant to my problem.

To avoid an XY problem I'm just going to ask my question in the most general, nooby way possible: how can I run a JHipster 5 app on Ubuntu (18.10) when I have JDK 11 installed? (If the answer is to install a different version of Java this is fine, but I don't know how to do this or how to tell JHipster to use that version).


问:
How to get Component reference(this) in D3 Context Menu OnOpen and OnClose
I'm new to Angular and trying to add d3-context-menu in my Angular project. I successfully added Context Menu when user do right-click.

```<code>this.svg = d3.select(this.elementRef.nativeElement)
  .append('div')
  //.on('click', (d, this) => this.onClickTask(d3.event,taskData, this))
  .on('contextmenu', contextMenu(this.menuItems, {
    onOpen: () => {
      // const status = this.MycomponentVariable;   // issue here to get "this" of my component
      console.log('Menu has been OPENED.');
    },
    onClose: () => {
      // const status = this.MycomponentVariable;    // issue here to get "this" of my component
      console.log('Menu has been closed.');
    }
  }));
</code>```

But the problem I facing that I want a variable (this.MycomponentVariable) value of my angular component via this(component context) when contxt-menu is opened or closed. But it shows that this is undefined. So, I'm unable to get value of this.MycomponentVariable.

I read documentation of d3-context-menu over this-link but couldn't get any solution.
Can anyone help me out that how can I get my angular component context inside onOpen and onClose methods?

答:
Really use d3 (or jQuery) is not a great idea, but I imagine you can always create and dispach a CustomEvent.

```<code>this.svg = d3.select(this.elementRef.nativeElement)
  .append('div')
  .on('contextmenu', contextMenu(this.menuItems, {
    onOpen: () => {
      document.dispatchEvent(new CustomEvent('menu',{detail:'Open'}}));
    },
    onClose: () => {
      document.dispatchEvent(new CustomEvent('menu',{detail:'Close'}}));
    }
  }));
</code>```

And use rxjs fromEvent operator

```<code>  ngOnInit() {
    this.menuObs=fromEvent(document,'menu').subscribe((res:any)=>{
        console.log(res.detail)
    })

  ngOnDestroy(){
    this.menuObs.unsubscribe()
  }
</code>```

Body:
I'm new to Angular and trying to add d3-context-menu in my Angular project. I successfully added Context Menu when user do right-click.

this.svg = d3.select(this.elementRef.nativeElement)
  .append('div')
  //.on('click', (d, this) => this.onClickTask(d3.event,taskData, this))
  .on('contextmenu', contextMenu(this.menuItems, {
    onOpen: () => {
      // const status = this.MycomponentVariable;   // issue here to get "this" of my component
      console.log('Menu has been OPENED.');
    },
    onClose: () => {
      // const status = this.MycomponentVariable;    // issue here to get "this" of my component
      console.log('Menu has been closed.');
    }
  }));

But the problem I facing that I want a variable (this.MycomponentVariable) value of my angular component via this(component context) when contxt-menu is opened or closed. But it shows that this is undefined. So, I'm unable to get value of this.MycomponentVariable.

I read documentation of d3-context-menu over this-link but couldn't get any solution.
Can anyone help me out that how can I get my angular component context inside onOpen and onClose methods?

Body:
Really use d3 (or jQuery) is not a great idea, but I imagine you can always create and dispach a CustomEvent.

this.svg = d3.select(this.elementRef.nativeElement)
  .append('div')
  .on('contextmenu', contextMenu(this.menuItems, {
    onOpen: () => {
      document.dispatchEvent(new CustomEvent('menu',{detail:'Open'}}));
    },
    onClose: () => {
      document.dispatchEvent(new CustomEvent('menu',{detail:'Close'}}));
    }
  }));

And use rxjs fromEvent operator

  ngOnInit() {
    this.menuObs=fromEvent(document,'menu').subscribe((res:any)=>{
        console.log(res.detail)
    })

  ngOnDestroy(){
    this.menuObs.unsubscribe()
  }


问:
Can I update a document base on collection condition?
I would Like to make sure some condition is met before performing an update operation.

Is this possible with MongoDB in a single query?

For example, I have the following collection A:

{"_id":"1", "content":{"a":1, "b":2}},
{"_id":"2", "content":{"a":1, "b":2}},
```

I would like to perform an update on a document where "_id" is "1", only if there is no document that has "_id":"2" in this entire collection A.

答:
You can use a $lookup to check for the existence of doc _id:"2". After that, based on the $lookup result to perform $merge to update back to doc _id:"1".

db.collection.aggregate([
  {
    $match: {
      _id: "1"
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "let": {
        docId: "2"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $eq: [
                "$_id",
                "$$docId"
              ]
            }
          }
        }
      ],
      "as": "doc2"
    }
  },
  {
    $match: {
      doc2: []
    }
  },
  {
    $addFields: {
      someNewFields: "..."
    }
  },
  {
    $project: {
      doc2: false
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])
```

Here is the Mongo playground that doc _id:"2" exists.

Here is the Mongo playground that doc _id:"2" does not exist.

Body:
I would Like to make sure some condition is met before performing an update operation.

Is this possible with MongoDB in a single query?

For example, I have the following collection A:

{"_id":"1", "content":{"a":1, "b":2}},
{"_id":"2", "content":{"a":1, "b":2}},

I would like to perform an update on a document where "_id" is "1", only if there is no document that has "_id":"2" in this entire collection A.

Body:
You can use a $lookup to check for the existence of doc _id:"2". After that, based on the $lookup result to perform $merge to update back to doc _id:"1".

db.collection.aggregate([
  {
    $match: {
      _id: "1"
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "let": {
        docId: "2"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $eq: [
                "$_id",
                "$$docId"
              ]
            }
          }
        }
      ],
      "as": "doc2"
    }
  },
  {
    $match: {
      doc2: []
    }
  },
  {
    $addFields: {
      someNewFields: "..."
    }
  },
  {
    $project: {
      doc2: false
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])

Here is the Mongo playground that doc _id:"2" exists.

Here is the Mongo playground that doc _id:"2" does not exist.


问:
The project uses Gradle 2.10 which is incompatible with Android Studio 2020.3
While learning android studio from udacity they asked me to download a project; I did so but while I was importing it to android studio I got an error message:

The project uses Gradle 2.10 which is incompatible with Android Studio 2020.3.

Why did I get this error?

答:
I saw this issue several times with Android studio. Below trick worked me the best.

Android Studio suggests to upgrade to newer version, please upgrade it and let it sync

Mostly you would see error message again

Now, Go to File -> Invalidate Caches/Restart

It should work now

If it shows same error then I don't know what to do.
If it shows different error then repeat from step 1 to 3 for new error.

Hope, it helps some..


问:
Adding Duplicate to variable using useState
I am trying to update an object using useState by finding by id and adding a tag to it. The code below seems to be working perfectly. The ternary operator is there because originally, the tags property does not exist so it just initializes it on the first tag add.

```<code>let newStudents = students.map(student => {
    if(student.id === id) {
        student.tags ? student.tags.push(tag) : student.tags = [tag];
    }
    return student;
});

setStudents(newStudents);
</code>```

However, the method below seems to be adding duplicate tags. I am using prevStudents, which I believe uses the previous state stored in the useState, then making a new object with it that has the updated tags, and finally updating students with 'return newStudents'.

```<code>setStudents((prevStudents) => {
    const newStudents = prevStudents.map((student) => {
        if (student.id === id) {
            student.tags ? (student.tags.push(tag)) : (student.tags = [tag]);
        }
        return student;
   });
   return newStudents;
});
</code>```

答:
You should return new object when you want to update a student state:

```<code>setStudents((prevStudents) => {
    const newStudents = prevStudents.map((student) => {
        if (student.id === id) {
             return {
               ...student,
               tags: student.tags ? [...student.tags, tag] : [tag]
             };
        }
        return student;
   });
   return newStudents;
});
</code>```

I think it should work now.

Body:
I am trying to update an object using useState by finding by id and adding a tag to it. The code below seems to be working perfectly. The ternary operator is there because originally, the tags property does not exist so it just initializes it on the first tag add.

let newStudents = students.map(student => {
    if(student.id === id) {
        student.tags ? student.tags.push(tag) : student.tags = [tag];
    }
    return student;
});

setStudents(newStudents);

However, the method below seems to be adding duplicate tags. I am using prevStudents, which I believe uses the previous state stored in the useState, then making a new object with it that has the updated tags, and finally updating students with 'return newStudents'.

setStudents((prevStudents) => {
    const newStudents = prevStudents.map((student) => {
        if (student.id === id) {
            student.tags ? (student.tags.push(tag)) : (student.tags = [tag]);
        }
        return student;
   });
   return newStudents;
});

Body:
You should return new object when you want to update a student state:

setStudents((prevStudents) => {
    const newStudents = prevStudents.map((student) => {
        if (student.id === id) {
             return {
               ...student,
               tags: student.tags ? [...student.tags, tag] : [tag]
             };
        }
        return student;
   });
   return newStudents;
});

I think it should work now.


问:
The css code is working 'cause .bg works, but .container doesn't work. Whether i erase the .bg, .container starts to work. How can i fix it?
The css code is working 'cause .bg works, but .container doesn't work. Whether i erase the .bg, .container starts to work. How can i fix it?

This is my html that is normal, is simple but i can't see what is wrong.

```<code><html>

    <head>

        <title>QR Code Component</title>
        <meta charset="utf-8"/>
        <link href="css/style.css" type="text/css" rel="stylesheet"/>

    </head>

    <body>

        <div class="bg">

             It doesn't appear on css

            <div class="container">div aqui</div>
                <!-- <img class="image" src="images/image-qr-code.png"/> -->

            <h2>Improve your front-end skills by building projects</h2>
            <p>Scan the QR code to visit Frontend Mentor and take your coding skills to the next level</p>
        </div>

    </body>

</html>

and this is my css code:

*{
    margin: 0;
    padding: 0;
}

body{
    background-color: hsl(212, 45%, 89%);
}

.bg{
    width: 300px;
    height: 430px;
    background-color: hsl(0, 0%, 100%);
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    border-radius: 15px;
    overflow: hidden;
    text-align: center;
};
</code>```

This part doesn't appear, i can't see what's wrong in this part. One of these photos, is the project i'm copying, and the other is my copy.

```<code>.container{
    width:90%;
    height:265px;
    background-color:green;
    margin: 0 auto;
    margin-top: 5%;
    margin-bottom: 5%;
    border-radius: 10px;enter code here
};

</code>```

答:
This should work now. Remove Semicolons after the closing tags of class .bg and .container

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: hsl(212, 45%, 89%);
}

.bg {
  width: 300px;
  height: 430px;
  background-color: hsl(0, 0%, 100%);
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 15px;
  overflow: hidden;
  text-align: center;
}

.container {
  width: 90%;
  height: 265px;
  background-color: green;
  margin: 0 auto;
  margin-top: 5%;
  margin-bottom: 5%;
  border-radius: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bg">It doesn't appear on css
  <div class="container">div aqui</div>
  <h2>Improve your front-end skills by building projects</h2>
  <p>Scan the QR code to visit Frontend Mentor and take your coding skills to the next level</p>
</div></code>```

Body:
The css code is working 'cause .bg works, but .container doesn't work. Whether i erase the .bg, .container starts to work. How can i fix it?

This is my html that is normal, is simple but i can't see what is wrong.

        <title>QR Code Component</title>
        <meta charset="utf-8"/>
        <link href="css/style.css" type="text/css" rel="stylesheet"/>

             It doesn't appear on css

div aqui

Improve your front-end skills by building projects

Scan the QR code to visit Frontend Mentor and take your coding skills to the next level

and this is my css code:

*{
    margin: 0;
    padding: 0;
}

body{
    background-color: hsl(212, 45%, 89%);
}

.bg{
    width: 300px;
    height: 430px;
    background-color: hsl(0, 0%, 100%);
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    border-radius: 15px;
    overflow: hidden;
    text-align: center;
};

This part doesn't appear, i can't see what's wrong in this part. One of these photos, is the project i'm copying, and the other is my copy.

.container{
    width:90%;
    height:265px;
    background-color:green;
    margin: 0 auto;
    margin-top: 5%;
    margin-bottom: 5%;
    border-radius: 10px;enter code here
};

Body:
This should work now. Remove Semicolons after the closing tags of class .bg and .container

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: hsl(212, 45%, 89%);
}

.bg {
  width: 300px;
  height: 430px;
  background-color: hsl(0, 0%, 100%);
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 15px;
  overflow: hidden;
  text-align: center;
}

.container {
  width: 90%;
  height: 265px;
  background-color: green;
  margin: 0 auto;
  margin-top: 5%;
  margin-bottom: 5%;
  border-radius: 10px;
}

<div class="bg">It doesn't appear on css
  <div class="container">div aqui</div>
  <h2>Improve your front-end skills by building projects</h2>
  <p>Scan the QR code to visit Frontend Mentor and take your coding skills to the next level</p>
</div>


问:
c++ reverse Array elements using dynamic Allocation Operators
Hi i'm the beginner of c++.
This time, I try to reverse Array 's element-order using dynamic Allocation Operator.
For example an array{1,2,3,4} will be rearranged {4,3,2,1} through calling function 'reverseArray'.
Everything works fine but somehow i got unwanted integer '-1' along with rearranged Array.
For example {-1,4,3,2,1}.
It means i did wrong and i really want to learn my fault.
Here is my code, please help me to figure out. </p>

```<code>#include<iostream>
#include<new>

using namespace std;

void reverseArray(int [] , int);

int main(){

    int num=0;

    cout << "enter size of pointer : " ;
    cin >> num ;

    int *pointerArray = new int [num];

    cout << "enter integer numbers in pointer" << endl;

    for(int index = 0 ; index < num ; index++){
        cin >> pointerArray[index];
    }

    reverseArray(pointerArray, num);

delete[] pointerArray;
    return 0 ;
}

void reverseArray(int reverse[], int Size){
    int*ptArray[Size];

    cout << "the reverse order of entered numbers is : " << endl;
    for(int index = 0 ; Size >= 0 ; index++) {
        ptArray[index] = &reverse[Size];
        cout << *ptArray[index] << " " ;
        --Size;
    }

    return ;
}
</code>```

答:
#include
using namespace std;

int main() {

```<code>int n;
cin>>n;
int temp=n;

int rem=0;
int i=0;

while (n>0) {

    n= n/10;
    i++;

}

int *arr = new int(i);

i=0;

while (temp>0) {

    rem=temp%10;
    arr[i]=rem;

    i++;

    temp= temp/10;

}
int t=0;

while(t<i) {
    cout<<arr[t]<<" ";
    t++;
}

return 0;
</code>```

}

Body:
Hi i'm the beginner of c++.
This time, I try to reverse Array 's element-order using dynamic Allocation Operator.
For example an array{1,2,3,4} will be rearranged {4,3,2,1} through calling function 'reverseArray'.
Everything works fine but somehow i got unwanted integer '-1' along with rearranged Array.
For example {-1,4,3,2,1}.
It means i did wrong and i really want to learn my fault.
Here is my code, please help me to figure out.

#include<iostream>
#include<new>

using namespace std;

void reverseArray(int [] , int);

int main(){

    int num=0;

    cout << "enter size of pointer : " ;
    cin >> num ;

    int *pointerArray = new int [num];

    cout << "enter integer numbers in pointer" << endl;

    for(int index = 0 ; index < num ; index++){
        cin >> pointerArray[index];
    }

    reverseArray(pointerArray, num);

delete[] pointerArray;
    return 0 ;
}

void reverseArray(int reverse[], int Size){
    int*ptArray[Size];

    cout << "the reverse order of entered numbers is : " << endl;
    for(int index = 0 ; Size >= 0 ; index++) {
        ptArray[index] = &reverse[Size];
        cout << *ptArray[index] << " " ;
        --Size;
    }

    return ;
}

Body:
#include
using namespace std;

int main() {

int n;
cin>>n;
int temp=n;

int rem=0;
int i=0;

while (n>0) {

    n= n/10;
    i++;

}

int *arr = new int(i);

i=0;

while (temp>0) {

    rem=temp%10;
    arr[i]=rem;

    i++;

    temp= temp/10;

}
int t=0;

while(t<i) {
    cout<<arr[t]<<" ";
    t++;
}

return 0;

}


问:
Verifying resources in a deployment yaml
In a deployment yaml, how we can verify that the resources we need for the running pods are guaranteed by the k8s?

Is there a way to figure that out?

答:
There is QoS (Quality of Service) Classes for running pods in k8s. There is an option that is guaranteing and restricting request and limits. This option is qosClass: Guaranteed.

To be able to make your pods' QoS's Guaranteed;

```<code>Every Container in the Pod must have a memory limit and a memory request.
For every Container in the Pod, the memory limit must equal the memory request.
Every Container in the Pod must have a CPU limit and a CPU request.
For every Container in the Pod, the CPU limit must equal the CPU request.
These restrictions apply to init containers and app containers equally.
</code>```

also check out the reference page for more info :
https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/

Body:
There is QoS (Quality of Service) Classes for running pods in k8s. There is an option that is guaranteing and restricting request and limits. This option is qosClass: Guaranteed.

To be able to make your pods' QoS's Guaranteed;

Every Container in the Pod must have a memory limit and a memory request.
For every Container in the Pod, the memory limit must equal the memory request.
Every Container in the Pod must have a CPU limit and a CPU request.
For every Container in the Pod, the CPU limit must equal the CPU request.
These restrictions apply to init containers and app containers equally.

also check out the reference page for more info :
https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/


问:
Automatically sort Google Sheet by most recently updated row
I want to have a sheet which automatically sorts the most recently edited row to the top, in order to surface freshly edited results and not let them be buried by outdated entries.</p>

答:
This could work with an on form submit but not like you think

```<code>function onFormSubmit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == 'Sheet name' && e.range.columnStart != 2 && e.range.rowStart > 3) {
    e.range.offset(0, 2 - e.range.columnStart).setValue(Utilities.formatDate(new Date(), "GMT", "yyyy/MM/dd HH:mm:ss"));
    sh.getRange(3, 1, sh.getLastRow() - 2, 13).sort({ column: 2, ascending: false });
  }
}
</code>```

columStart will always be one so that will work

row start will work after you get past row 3

and the sheet will always have to be the linked sheet name and resorting the linked sheet seems kind of weird to me it's already sorted by time stamp

Body:
This could work with an on form submit but not like you think

function onFormSubmit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == 'Sheet name' && e.range.columnStart != 2 && e.range.rowStart > 3) {
    e.range.offset(0, 2 - e.range.columnStart).setValue(Utilities.formatDate(new Date(), "GMT", "yyyy/MM/dd HH:mm:ss"));
    sh.getRange(3, 1, sh.getLastRow() - 2, 13).sort({ column: 2, ascending: false });
  }
}

columStart will always be one so that will work

row start will work after you get past row 3

and the sheet will always have to be the linked sheet name and resorting the linked sheet seems kind of weird to me it's already sorted by time stamp


问:
How can I create a user input loop for a Guess the Number game between 1-100?
```<code>#Guess the number

from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_input != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            return "Guess a lower number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))
        else:
            return "Guess a higher number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)
</code>```

I have the bulk of the code ready. I just can't nail the user input loop. Each time I guess a number it exits the code.

答:
return will break the define so you should return the data when the user guess the correct answer

```<code>from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_guess != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            print("Guess a lower number\n")
            user_guess = int(input("Guess a number between 1 and 100.\n"))
        else:
            print("Guess a higher number\n")
            user_guess = int(input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)
</code>```

This will work

Body:
#Guess the number

from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_input != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            return "Guess a lower number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))
        else:
            return "Guess a higher number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)

I have the bulk of the code ready. I just can't nail the user input loop. Each time I guess a number it exits the code.

Body:
return will break the define so you should return the data when the user guess the correct answer

from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_guess != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            print("Guess a lower number\n")
            user_guess = int(input("Guess a number between 1 and 100.\n"))
        else:
            print("Guess a higher number\n")
            user_guess = int(input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)

This will work