问:
How in R, can you create new columns using existing columns as variables?
I am new to R, and so would greatly appreciate more explanation for any code you might have to help solve my issue.

I have a data.frame with groups of columns related to each other and I want to perform a calculation on each of those many groups to get new output columns. For example, many biological replicates in an experiment where I want to perform the calculations on each replicate independently before collapsing them.

I know I could use mutate in dplyr to create new columns, but I am not sure how to do this in a loop or how to use lapply type strategy to avoid re-tying the columns names each time. My biggest issue is understanding how to convert the column names into something usable by one of these strategies.

For example:

```<code>> A.1 <- c(11,12,13,4,15,6,17,18)
> A.2 <- c(2,4,5,5,19,7,5,1)
>
> B.1 <- c (3,4,5,1,31,76,13,70)
> B.2 <- c (10,9,8,15,31,12,13,12)
>
> C.1 <- c(1,2,3,4,5,6,7,8)
> C.2 <- c(2,4,5,8,10,12,15,18)
>
> df <- data.frame(A.1, A.2, B.1, B.2, C.1, C.2)
>
> df
A.1 A.2 B.1 B.2 C.1 C.2
1  11   2   3  10   1   2
2  12   4   4   9   2   4
3  13   5   5   8   3   5
4   4   5   1  15   4   8
5  15  19  31  31   5  10
6   6   7  76  12   6  12
7  17   5  13  13   7  15
8  18   1  70  12   8  18
>
</code>```

Where I want to create new columns where A.new = A.1/A.2, B.new = B.1/B.2 etc. without typing out each column name explicitly. Also note the "A" and "B" are really character strings, so typing all of them would be very messy and time consuming.

Something like this, but a general case for many column groups:

```<code>> df <- df %>% mutate(A.new = A.1/A.2)
> df <- df %>% mutate(B.new = B.1/B.2)
> df <- df %>% mutate(C.new = C.1/C.2)
>
> df
 A.1 A.2 B.1 B.2 C.1 C.2      A.new      B.new     C.new
1  11   2   3  10   1   2  5.5000000 0.30000000 0.5000000
2  12   4   4   9   2   4  3.0000000 0.44444444 0.5000000
3  13   5   5   8   3   5  2.6000000 0.62500000 0.6000000
4   4   5   1  15   4   8  0.8000000 0.06666667 0.5000000
5  15  19  31  31   5  10  0.7894737 1.00000000 0.5000000
6   6   7  76  12   6  12  0.8571429 6.33333333 0.5000000
7  17   5  13  13   7  15  3.4000000 1.00000000 0.4666667
8  18   1  70  12   8  18 18.0000000 5.83333333 0.4444444
>
</code>```

I don't see the answer to my question on here already, but if you could point me to existing answers that would be much appreciated! I am currently thinking about the column names as containing the variable, but maybe that is not the correct way to approach this (R is also the first programming language I am learning) and so my searches for answers haven't yielded much yet.

Thank you for your guidance in advance!

答:
As mentioned by @A. S. K. it is easier to do the calculation if you have data in a long format.

We can use pivot_longer to get data in long format and for every row divide the first value by second value for that group of column.

```<code>library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  tidyr::pivot_longer(cols = -row,
                      names_to = c('.value', 'group'),
                      names_sep = '\\.') %>%
   group_by(row) %>%
   summarise(across(A:C, list(new = ~.[1]/.[2]))) %>%
   #If you have an older version of dplyr use
   #summarise_at(vars(A:C), list(new = ~.[1]/.[2])) %>%
   select(-row) %>%
   bind_cols(df, .)

#  A.1 A.2 B.1 B.2 C.1 C.2  A_new  B_new C_new
#1  11   2   3  10   1   2  5.500 0.3000 0.500
#2  12   4   4   9   2   4  3.000 0.4444 0.500
#3  13   5   5   8   3   5  2.600 0.6250 0.600
#4   4   5   1  15   4   8  0.800 0.0667 0.500
#5  15  19  31  31   5  10  0.789 1.0000 0.500
#6   6   7  76  12   6  12  0.857 6.3333 0.500
#7  17   5  13  13   7  15  3.400 1.0000 0.467
#8  18   1  70  12   8  18 18.000 5.8333 0.444
</code>```

You can specify range of column names using A:C in summarise step. Also, note that in pivot_longer step the names_sep argument is used to differentiate column group. Since you have column names as A.1, A.2 I use '.' as a separator, you might need to change it according to the column names that you have.

Body:
I am new to R, and so would greatly appreciate more explanation for any code you might have to help solve my issue.

I have a data.frame with groups of columns related to each other and I want to perform a calculation on each of those many groups to get new output columns. For example, many biological replicates in an experiment where I want to perform the calculations on each replicate independently before collapsing them.

I know I could use mutate in dplyr to create new columns, but I am not sure how to do this in a loop or how to use lapply type strategy to avoid re-tying the columns names each time. My biggest issue is understanding how to convert the column names into something usable by one of these strategies.

For example:

> A.1 <- c(11,12,13,4,15,6,17,18)
> A.2 <- c(2,4,5,5,19,7,5,1)
>
> B.1 <- c (3,4,5,1,31,76,13,70)
> B.2 <- c (10,9,8,15,31,12,13,12)
>
> C.1 <- c(1,2,3,4,5,6,7,8)
> C.2 <- c(2,4,5,8,10,12,15,18)
>
> df <- data.frame(A.1, A.2, B.1, B.2, C.1, C.2)
>
> df
A.1 A.2 B.1 B.2 C.1 C.2
1  11   2   3  10   1   2
2  12   4   4   9   2   4
3  13   5   5   8   3   5
4   4   5   1  15   4   8
5  15  19  31  31   5  10
6   6   7  76  12   6  12
7  17   5  13  13   7  15
8  18   1  70  12   8  18
>

Where I want to create new columns where A.new = A.1/A.2, B.new = B.1/B.2 etc. without typing out each column name explicitly. Also note the "A" and "B" are really character strings, so typing all of them would be very messy and time consuming.

Something like this, but a general case for many column groups:

> df <- df %>% mutate(A.new = A.1/A.2)
> df <- df %>% mutate(B.new = B.1/B.2)
> df <- df %>% mutate(C.new = C.1/C.2)
>
> df
 A.1 A.2 B.1 B.2 C.1 C.2      A.new      B.new     C.new
1  11   2   3  10   1   2  5.5000000 0.30000000 0.5000000
2  12   4   4   9   2   4  3.0000000 0.44444444 0.5000000
3  13   5   5   8   3   5  2.6000000 0.62500000 0.6000000
4   4   5   1  15   4   8  0.8000000 0.06666667 0.5000000
5  15  19  31  31   5  10  0.7894737 1.00000000 0.5000000
6   6   7  76  12   6  12  0.8571429 6.33333333 0.5000000
7  17   5  13  13   7  15  3.4000000 1.00000000 0.4666667
8  18   1  70  12   8  18 18.0000000 5.83333333 0.4444444
>

I don't see the answer to my question on here already, but if you could point me to existing answers that would be much appreciated! I am currently thinking about the column names as containing the variable, but maybe that is not the correct way to approach this (R is also the first programming language I am learning) and so my searches for answers haven't yielded much yet.

Thank you for your guidance in advance!

Body:
As mentioned by @A. S. K. it is easier to do the calculation if you have data in a long format.

We can use pivot_longer to get data in long format and for every row divide the first value by second value for that group of column.

library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  tidyr::pivot_longer(cols = -row,
                      names_to = c('.value', 'group'),
                      names_sep = '\\.') %>%
   group_by(row) %>%
   summarise(across(A:C, list(new = ~.[1]/.[2]))) %>%
   #If you have an older version of dplyr use
   #summarise_at(vars(A:C), list(new = ~.[1]/.[2])) %>%
   select(-row) %>%
   bind_cols(df, .)

#  A.1 A.2 B.1 B.2 C.1 C.2  A_new  B_new C_new
#1  11   2   3  10   1   2  5.500 0.3000 0.500
#2  12   4   4   9   2   4  3.000 0.4444 0.500
#3  13   5   5   8   3   5  2.600 0.6250 0.600
#4   4   5   1  15   4   8  0.800 0.0667 0.500
#5  15  19  31  31   5  10  0.789 1.0000 0.500
#6   6   7  76  12   6  12  0.857 6.3333 0.500
#7  17   5  13  13   7  15  3.400 1.0000 0.467
#8  18   1  70  12   8  18 18.000 5.8333 0.444

You can specify range of column names using A:C in summarise step. Also, note that in pivot_longer step the names_sep argument is used to differentiate column group. Since you have column names as A.1, A.2 I use '.' as a separator, you might need to change it according to the column names that you have.


来源: stackexchange

问:
how to make my ggplotly tootip show the original value when axis log-transformed
I have a plotly histogram where x-axis is log tranformed. I'm trying to make my histogram tooltip show the original value rather than the log10-transformed value.  I'm referring to this example. Overwriting the text attribute.

Below is my code.  However, my tooltip does not show anything.  Does anyone know how I can modify the text attributes in this case?

```<code>g=iris %>%
  #select(Petal.Length) %>%
  ggplot(aes(x=Petal.Length))+
  geom_histogram()+
  scale_x_log10()
gg <- ggplotly(g)
gg$x$data[[1]]$text = paste(x,y)
gg
</code>```

答:
Define what you want to show inside aes(), and then call it in ggplotly.

```<code>g=iris %>%
  ggplot(aes(x=Petal.Length, text=paste("X:",iris$Petal.Length) )) +
  geom_histogram()+
  scale_x_log10()
gg <- ggplotly(g, tooltip=c("text"))
gg
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a plotly histogram where x-axis is log tranformed. I'm trying to make my histogram tooltip show the original value rather than the log10-transformed value.  I'm referring to this example. Overwriting the text attribute.

Below is my code.  However, my tooltip does not show anything.  Does anyone know how I can modify the text attributes in this case?

g=iris %>%
  #select(Petal.Length) %>%
  ggplot(aes(x=Petal.Length))+
  geom_histogram()+
  scale_x_log10()
gg <- ggplotly(g)
gg$x$data[[1]]$text = paste(x,y)
gg

Body:
Define what you want to show inside aes(), and then call it in ggplotly.

g=iris %>%
  ggplot(aes(x=Petal.Length, text=paste("X:",iris$Petal.Length) )) +
  geom_histogram()+
  scale_x_log10()
gg <- ggplotly(g, tooltip=c("text"))
gg


问:
CSS: Is there a way to apply inherited padding as negative margin?
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

```

<pre class="lang-css prettyprint-override"><code>a {
  padding: inherit;
  margin: <negative of inherited padding>
}
</code>```

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

答:
Last resort javascript solution:

1) Add a resize-event listener to the window.

2) Use getComputedStyle to get the padding on resize.

3) Check console for output and adjust string to your needs.

4) Add the wanted minus sign and set the margin via the style property.

Body:
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

a {
  padding: inherit;
  margin: <negative of inherited padding>
}

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?


问:
How do I change java logging console output from std err to std out?
I'm using the standard ConsoleHandler from java.util.logging and by default the console output is directed to the error stream (i.e. System.err).

How do I change the console output to the output stream (i.e. System.out)?

答:
Step 1: Set parent handlers to false.

```<code>log.setUseParentHandlers(false);
</code>```

Step 2: Add a handler that writes to System.out

```<code>log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));
</code>```

Thats it..

```<code>import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;

public class App {

     static final Logger log = Logger.getLogger("com.sample.app.App");

     static void processData() {
          log.info("Started Processing Data");
          log.info("Finished processing data");
     }

     public static void main(String args[]) throws IOException {
          log.setUseParentHandlers(false);

          log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));

          processData();
     }
}
</code>```

OwnerDisplayName: Obediah Stane

ContentLicense: CC BY-SA 3.0

Body:
Step 1: Set parent handlers to false.

log.setUseParentHandlers(false);

Step 2: Add a handler that writes to System.out

log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));

Thats it..

import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;

public class App {

     static final Logger log = Logger.getLogger("com.sample.app.App");

     static void processData() {
          log.info("Started Processing Data");
          log.info("Finished processing data");
     }

     public static void main(String args[]) throws IOException {
          log.setUseParentHandlers(false);

          log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));

          processData();
     }
}


问:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.' ERROR
I am trying to create Update function for my windows applications for some reason it's not working and come up with this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.'"  Any suggestions?</p>

```<code>    private void Update_Click(object sender, EventArgs e)
    {

            if (txt_BranchID.Text != "" && txt_BranchName.Text != "" && txt_BranchAddress.Text != "" && txt_Telephone.Text != "")
            {
            cmd = new SqlCommand("Update BInfo(BranchID, BranchName, BranchAddress, Telephone) values(@BranchID, @BranchName, @BranchAddress, @Telephone)", con);
            con.Open();

                cmd.Parameters.AddWithValue("@BranchName", txt_BranchName.Text);
                cmd.Parameters.AddWithValue("@BranchAddress", txt_BranchAddress.Text);
                cmd.Parameters.AddWithValue("@Telephone", txt_Telephone.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record updated Successfully");
                con.Close();
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            }
</code>```

答:
the syntax for update query is different than Insert query. It should look like:

```<code>update BInfo
SET
    BranchName = @BranchName,
    BranchAddress = @BranchAddress,
    Telephone = @Telephone
    where BranchID = @BranchID
</code>```

and there should also be a where clause specifying which Branch information we are going to update so at last line put where

in string form in the code it would be like:

```<code>cmd = new SqlCommand(@"Update BInfo
SET
    BranchName = @BranchName,
    BranchAddress = @BranchAddress,
    Telephone = @Telephone
    where BranchID = @BranchID",con);
</code>```

Also @BranchId is missing in your command parameters, it would be needed there:

```<code>cmd.Parameters.AddWithValue("@BranchID", "branchId here");
</code>```

Body:
I am trying to create Update function for my windows applications for some reason it's not working and come up with this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.'"  Any suggestions?

    private void Update_Click(object sender, EventArgs e)
    {

            if (txt_BranchID.Text != "" && txt_BranchName.Text != "" && txt_BranchAddress.Text != "" && txt_Telephone.Text != "")
            {
            cmd = new SqlCommand("Update BInfo(BranchID, BranchName, BranchAddress, Telephone) values(@BranchID, @BranchName, @BranchAddress, @Telephone)", con);
            con.Open();

                cmd.Parameters.AddWithValue("@BranchName", txt_BranchName.Text);
                cmd.Parameters.AddWithValue("@BranchAddress", txt_BranchAddress.Text);
                cmd.Parameters.AddWithValue("@Telephone", txt_Telephone.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record updated Successfully");
                con.Close();
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            }

Body:
the syntax for update query is different than Insert query. It should look like:

update BInfo
SET
    BranchName = @BranchName,
    BranchAddress = @BranchAddress,
    Telephone = @Telephone
    where BranchID = @BranchID

and there should also be a where clause specifying which Branch information we are going to update so at last line put where

in string form in the code it would be like:

cmd = new SqlCommand(@"Update BInfo
SET
    BranchName = @BranchName,
    BranchAddress = @BranchAddress,
    Telephone = @Telephone
    where BranchID = @BranchID",con);

Also @BranchId is missing in your command parameters, it would be needed there:

cmd.Parameters.AddWithValue("@BranchID", "branchId here");


问:
Array.map( ) only works on First Array but not on the Second. Can someone please explain why it doesn't work and provide proper solution
I have two arrays, each array gets mapped over and if the array doesn't match with "apiSuggestion" the element gets black background-color with red text.
This works:

```<code>let sentenceOne = ["somthing", "life", "nothing"];
let sentenceTwo = ["nummber", "seven", everythng"];

let apiSuggestion = ["something", "life", "nothing", "number", "seven", "everything"];

let matchMakerOne = sentenceOne.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `
               <span style="background-color:black; color:red">
                     ${word}
               </span>
       } else {
               return word
              }
          })
document.getElementById("sentenceOne").innerHTML = machMakerOne.join(' ')
//in the HTML i see "somthing" highlighted in black background-color with red text, as it doesnt match to api suggesstion
</code>```

This doesn't work even though its the same logic, where am I making a mistake?

```<code>let matchMakerTwo = sentenceTwo.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `
               <span style="background-color:black; color:red">
                     ${word}
               </span>
       } else {
               return word
              }
          })
document.getElementById("sentenceTwo").innerHTML = machMakerTwo.join(' ')
// "nummber", "seven", everythng" all get black background and red text
// nummber and everythng should get black background and red text
</code>```

I tried to "concat" sentenceOne and sentenceTwo, it only catches the spelling mistakes from first array but not the second. How can I highlight the spelling mistakes in both these arrays and render it in the HTML? Any help is appreciated. Thank you in advance.
i created JSFiddle

答:
The code is working correctly. You are looping every item in the array in returning colored text if the value of the item does not match the item in the same index in apiSuggestion.

sentence one:

```<code>sentenceOne[0] (somthing) | apiSuggestion[0] (something) - NOT
sentenceOne[1] (life) | apiSuggestion[1] (life) - MATCH
sentenceOne[2] (nothing) | apiSuggestion[2] (nothing) - MATCH
</code>```

sentence two:

```<code>sentenceTwo[0] (nummber) | apiSuggestion[0] (something) - NOT
sentenceTwo[1] (seven) | apiSuggestion[1] (life) - NOT
sentenceTwo[2] (everythng) | apiSuggestion[2] (nothing) - NOT
</code>```

I believe what you what to achieve is to return a colored text if the current item in the iteration is not in the apiSuggestion array. You can achieve that using the includes method. Your function should be:

```<code>let matchMakerTwo = sentenceTwo.map(function(word) {
    if (!apiSuggestion.includes(word)) {
        return `
            <span style="background-color:black; color:red">
                ${word}
            </span>
        `
    } else {
        return word
    }
})
</code>```

PS: You can embed a code snippet to your question. This way your question becomes cleaner and with a working model.

Body:
I have two arrays, each array gets mapped over and if the array doesn't match with "apiSuggestion" the element gets black background-color with red text.
This works:

let sentenceOne = ["somthing", "life", "nothing"];
let sentenceTwo = ["nummber", "seven", everythng"];

let apiSuggestion = ["something", "life", "nothing", "number", "seven", "everything"];

let matchMakerOne = sentenceOne.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `

                     ${word}

       } else {
               return word
              }
          })
document.getElementById("sentenceOne").innerHTML = machMakerOne.join(' ')
//in the HTML i see "somthing" highlighted in black background-color with red text, as it doesnt match to api suggesstion

This doesn't work even though its the same logic, where am I making a mistake?

let matchMakerTwo = sentenceTwo.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `

                     ${word}

       } else {
               return word
              }
          })
document.getElementById("sentenceTwo").innerHTML = machMakerTwo.join(' ')
// "nummber", "seven", everythng" all get black background and red text
// nummber and everythng should get black background and red text

I tried to "concat" sentenceOne and sentenceTwo, it only catches the spelling mistakes from first array but not the second. How can I highlight the spelling mistakes in both these arrays and render it in the HTML? Any help is appreciated. Thank you in advance.
i created JSFiddle

Body:
The code is working correctly. You are looping every item in the array in returning colored text if the value of the item does not match the item in the same index in apiSuggestion.

sentence one:

sentenceOne[0] (somthing) | apiSuggestion[0] (something) - NOT
sentenceOne[1] (life) | apiSuggestion[1] (life) - MATCH
sentenceOne[2] (nothing) | apiSuggestion[2] (nothing) - MATCH

sentence two:

sentenceTwo[0] (nummber) | apiSuggestion[0] (something) - NOT
sentenceTwo[1] (seven) | apiSuggestion[1] (life) - NOT
sentenceTwo[2] (everythng) | apiSuggestion[2] (nothing) - NOT

I believe what you what to achieve is to return a colored text if the current item in the iteration is not in the apiSuggestion array. You can achieve that using the includes method. Your function should be:

let matchMakerTwo = sentenceTwo.map(function(word) {
    if (!apiSuggestion.includes(word)) {
        return `
            <span style="background-color:black; color:red">
                ${word}
            </span>
        `
    } else {
        return word
    }
})

PS: You can embed a code snippet to your question. This way your question becomes cleaner and with a working model.


问:
Docker Compose Django + PostgreSQL access postgres host without using service name
So, basically i have this docker-compose.yml config:

```<code>services:
  postgres:
    container_name: youtube_manager_postgres
    restart: always
    image: postgres:alpine
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=qwerty123
      - POSTGRES_DB=ytmanager
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"

  django:
    container_name: youtube_manager_django
    restart: always
    build:
      context: ../
      dockerfile: deploy/django/Dockerfile
    command: sh -c "poetry run python3 manage.py migrate &&
                    poetry run python3 manage.py collectstatic --no-input --clear &&
                    poetry run uwsgi --ini /etc/uwsgi.ini"
    ports:
      - "8000:8000"
    volumes:
      - staticfiles:/code/static
      - mediafiles:/code/media
    depends_on:
      - postgres
</code>```

My Django's database preferences are:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}
</code>```

I wan't to use it in two ways:
1. Running docker-compose up -d postgres and then python3 manage.py runserver (actually, poetry run python3 manage.py runserver but for now it doesn't matter) during development.
2. Running docker-compose up during deployment.

For now, it works fine with the 1 option, but when I'm execution docker-compose up I'm getting an error:

```<code>youtube_manager_django | django.db.utils.OperationalError: could not connect to server: Connection refused
youtube_manager_django |        Is the server running on host "0.0.0.0" and accepting
youtube_manager_django |        TCP/IP connections on port 5432?
</code>```

If I'm changing Django database settings this way:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}
</code>```

Executing docker-compose up -d postgres and then python manage.py runserver causes an error:

```<code>django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution
</code>```

How could I properly config docker-compose.yml to use the same HOST in Django settings? (for example, 'HOST': '0.0.0.0' or 'HOST': 'postgres' for both options).

I've tried to use network_mode: host on my django and postgres services. It works fine, but is there any other way to solve a problem (for example, using networking settings? I've read docker-compose documentation on their website, but can't get what's going on there).

答:
Before editing Django DB config, please ensure the following:

Both containers are running in the same network.

Postgres service is up and running in the container.

Service 'postgres' is accessible from the webapp container. For this you can login to the container and perform a ping test.
docker exec -it containerID /bin/bash (in some cases /bin/sh) # to login to container

Solutions:

Similar:
Django connection to postgres by docker-compose

For you to connect to DB using service name in Django, as per the documentation if the HOST and PORT keys are left out of the dictionary then Django will try connecting with the complete "NAME" as a SID.

Hope it helps

Body:
So, basically i have this docker-compose.yml config:

services:
  postgres:
    container_name: youtube_manager_postgres
    restart: always
    image: postgres:alpine
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=qwerty123
      - POSTGRES_DB=ytmanager
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"

  django:
    container_name: youtube_manager_django
    restart: always
    build:
      context: ../
      dockerfile: deploy/django/Dockerfile
    command: sh -c "poetry run python3 manage.py migrate &&
                    poetry run python3 manage.py collectstatic --no-input --clear &&
                    poetry run uwsgi --ini /etc/uwsgi.ini"
    ports:
      - "8000:8000"
    volumes:
      - staticfiles:/code/static
      - mediafiles:/code/media
    depends_on:
      - postgres

My Django's database preferences are:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}

I wan't to use it in two ways:
1. Running docker-compose up -d postgres and then python3 manage.py runserver (actually, poetry run python3 manage.py runserver but for now it doesn't matter) during development.
2. Running docker-compose up during deployment.

For now, it works fine with the 1 option, but when I'm execution docker-compose up I'm getting an error:

youtube_manager_django | django.db.utils.OperationalError: could not connect to server: Connection refused
youtube_manager_django |        Is the server running on host "0.0.0.0" and accepting
youtube_manager_django |        TCP/IP connections on port 5432?

If I'm changing Django database settings this way:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}

Executing docker-compose up -d postgres and then python manage.py runserver causes an error:

django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution

How could I properly config docker-compose.yml to use the same HOST in Django settings? (for example, 'HOST': '0.0.0.0' or 'HOST': 'postgres' for both options).

I've tried to use network_mode: host on my django and postgres services. It works fine, but is there any other way to solve a problem (for example, using networking settings? I've read docker-compose documentation on their website, but can't get what's going on there).


问:
repeated logging in log 4j in java
I used log4j in a java program. I initialized it with :

```<code>BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}
</code>```

But, during the execution of the program i get 3 log statements instead of one. For example,

```<code>3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

instead of one line

```<code>1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

Are there any extra configurations to be done to log4j to avoid this?

答: I've experienced similar behavior, and it turned out that Log4J was configured more than once; using the BasicConfigurator, but also with a log4j.xml file I had forgotten about. Could it be that there's an additional Log4J configuration somewhere on the classpath?</p>

OwnerDisplayName: BHARATH

ContentLicense: CC BY-SA 2.5

Title: repeated logging in log 4j in java

Body:
I used log4j in a java program. I initialized it with :

BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}

But, during the execution of the program i get 3 log statements instead of one. For example,

3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

instead of one line

1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

Are there any extra configurations to be done to log4j to avoid this?

LastEditorDisplayName: Jon Skeet

OwnerDisplayName: Nils-Petter Nilsen


问:
Usage of printf and fgets together in a loop
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

```<code>int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}
</code>```

When I enter a string longer than 32 characters, it behaves anormally.

```<code>Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:
</code>```

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?

答:
fgets() does not limit the length of a line a user enters.  fgets() limits how much of that line is read.

With too much input, the remainder is left for the next input operation.

If input via fgets()lacks a '\n', then either

Entire line was not read, (common enough)

Input w/o '\n' and then end-of-file, (seldom)

A null character was read. (rare)

Input buffer smaller than 1. (pathological)

Below readily IDs the first 2.

```<code>// Test if anything was read.
if (fgets(pass, sizeof pass, stdin)) {
  // Was it missing a '\n'?
  if (strchr(pass, '\n') == NULL) {
    // Read rest of line and throw it away
    int ch;
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
      ;
    }
  }
}
</code>```

Body:
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}

When I enter a string longer than 32 characters, it behaves anormally.

Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?

Body:
fgets() does not limit the length of a line a user enters.  fgets() limits how much of that line is read.

With too much input, the remainder is left for the next input operation.

If input via fgets()lacks a '\n', then either

Entire line was not read, (common enough)

Input w/o '\n' and then end-of-file, (seldom)

A null character was read. (rare)

Input buffer smaller than 1. (pathological)

Below readily IDs the first 2.

// Test if anything was read.
if (fgets(pass, sizeof pass, stdin)) {
  // Was it missing a '\n'?
  if (strchr(pass, '\n') == NULL) {
    // Read rest of line and throw it away
    int ch;
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
      ;
    }
  }
}


问:
MySQL Check constraints: only one column is not null
This question is similar to Check Constraint to Confirm Exactly One is not NULL, but for MySQL and multiple columns, and MySQL supports check since v8.0.16.

For example, I have a "Post" Table and it has three columns which are author_id, manager_id, editor_id. Only one of these three columns should be not null.

How to achieve this in MySQL Check constraints?

Maybe something like

```<code>not_null_sum = (author_id is not null ? 1 : 0) + (manager_id is not null ? 1 : 0) + (editor_id is not null ? 1 : 0)
not_null_sum should == 1
</code>```

答:
Try summing up a boolean expression which checks the total count of null columns:</p>

```<code>CHECK (author_id IS NULL + manager_id IS NULL + editor_id IS NULL = 1)
</code>```

Body:
This question is similar to Check Constraint to Confirm Exactly One is not NULL, but for MySQL and multiple columns, and MySQL supports check since v8.0.16.

For example, I have a "Post" Table and it has three columns which are author_id, manager_id, editor_id. Only one of these three columns should be not null.

How to achieve this in MySQL Check constraints?

Maybe something like

not_null_sum = (author_id is not null ? 1 : 0) + (manager_id is not null ? 1 : 0) + (editor_id is not null ? 1 : 0)
not_null_sum should == 1

Body:
Try summing up a boolean expression which checks the total count of null columns:

CHECK (author_id IS NULL + manager_id IS NULL + editor_id IS NULL = 1)


问:
Need to move two menu items to the right side of the header in WordPress
I have created 6 pages for the website and added into my header, Now need to move last two pages to the right side of the header in my website. Please help me how to do that. Thank you</p>

答:
Do you use some menu inside of the header?
If you, just you have to take id values for that specific items who contains the links to those page and edit directly in the section Add CSS styles from your WP editor, and put something like this:

```<code>      #btn_Id_*,
      #btn_Id_* {
       float: right !important;
      }
</code>```

I hope this one help you.

Body:
Do you use some menu inside of the header?
If you, just you have to take id values for that specific items who contains the links to those page and edit directly in the section Add CSS styles from your WP editor, and put something like this:

      #btn_Id_*,
      #btn_Id_* {
       float: right !important;
      }

I hope this one help you.


问:
Is it possible to have an external file input for choicefields in django?
I have ChoiceField in my Django model which consist of several choices and i am using the CheckboxSelectMultiple widget in forms to have multiple select options.

models-

```<code>BREAKFAST_CHOICES = (('fruits', 'A bowl of fruits with nuts'),
                           ('tofu', 'Tofu Omlette'),
                           ('1', 'Option 1'),
                           ('2', 'Option 2'),
                           ('3', 'Option 3'),)
    breakfast = MultiSelectField(choices=VBREAKFAST_CHOICES, null=True, blank=True, default=False)
</code>```

forms-

```<code>widgets = {
        'breakfast': forms.CheckboxSelectMultiple,
}
</code>```

Now, in the future if I want to change the existing choice (options) with some other or add and delete options,how can i do this?
Is there an easier way for a non programmer to just externally update a file and achieve this? i.e can my choicefield take an external file containing the list of options which can be edited as and when required.

答: You can use foreign key relation. That way you can make the choice field dynamic. </p>

Body:
I have ChoiceField in my Django model which consist of several choices and i am using the CheckboxSelectMultiple widget in forms to have multiple select options.

models-

BREAKFAST_CHOICES = (('fruits', 'A bowl of fruits with nuts'),
                           ('tofu', 'Tofu Omlette'),
                           ('1', 'Option 1'),
                           ('2', 'Option 2'),
                           ('3', 'Option 3'),)
    breakfast = MultiSelectField(choices=VBREAKFAST_CHOICES, null=True, blank=True, default=False)

forms-

widgets = {
        'breakfast': forms.CheckboxSelectMultiple,
}

Now, in the future if I want to change the existing choice (options) with some other or add and delete options,how can i do this?
Is there an easier way for a non programmer to just externally update a file and achieve this? i.e can my choicefield take an external file containing the list of options which can be edited as and when required.


问:
Why does std::set.erase(first, last) impact the container from which (first, last) were taken?
I will preface that I'm fairly new to C++ in general. Recently, I ran into some perplexing behavior from the std::set.erase() method, which I have isolated into the following code. This code sample crashes with a segmentation fault when it hits the second for loop:

```<code>#include <set>
#include <iostream>

int main() {
    std::set<int> foo = {0, 1, 2};
    std::set<int> bar = {0, 1, 2, 3, 4};
    for(int i : foo) {
        printf("%d\n", i);
    }
    bar.erase(foo.begin(), foo.end());
    for(int i : foo) { //Crash happens right here, before entering the body of the loop.
        printf("%d\n", i);
    }
    return 0;
}
</code>```

Whereas if you remove the call to erase() it does not crash.

This is somewhat surprising behavior. Calling bar.erase() is obviously supposed to modify "bar" but I would not generally expect it to have any impact on how "foo" functions. What does std::set.erase() do that causes a segmentation fault to occur?

This is simple enough to bypass just by creating a copy of "foo" to supply start and end iterators to erase(), but I am curious why this behavior happens in the first place.

答:
You're passing iterators from foo into the erase call on bar. The iterator-pair overload of erase erases the range denoted by the pair, not every value that appears within that range. Therefore, it works only if you pass a valid range of the set you're calling erase on. If you'd like to remove all elements from the other set, you can use std::set_difference:

```<code>bar = [&] {
    std::set<int> result;
    std::set_difference(bar.begin(), bar.end(), foo.begin(), foo.end(), std::inserter(result));
    return result;
}();
</code>```

Body:
I will preface that I'm fairly new to C++ in general. Recently, I ran into some perplexing behavior from the std::set.erase() method, which I have isolated into the following code. This code sample crashes with a segmentation fault when it hits the second for loop:

#include <set>
#include <iostream>

int main() {
    std::set<int> foo = {0, 1, 2};
    std::set<int> bar = {0, 1, 2, 3, 4};
    for(int i : foo) {
        printf("%d\n", i);
    }
    bar.erase(foo.begin(), foo.end());
    for(int i : foo) { //Crash happens right here, before entering the body of the loop.
        printf("%d\n", i);
    }
    return 0;
}

Whereas if you remove the call to erase() it does not crash.

This is somewhat surprising behavior. Calling bar.erase() is obviously supposed to modify "bar" but I would not generally expect it to have any impact on how "foo" functions. What does std::set.erase() do that causes a segmentation fault to occur?

This is simple enough to bypass just by creating a copy of "foo" to supply start and end iterators to erase(), but I am curious why this behavior happens in the first place.

Body:
You're passing iterators from foo into the erase call on bar. The iterator-pair overload of erase erases the range denoted by the pair, not every value that appears within that range. Therefore, it works only if you pass a valid range of the set you're calling erase on. If you'd like to remove all elements from the other set, you can use std::set_difference:

bar = [&] {
    std::set<int> result;
    std::set_difference(bar.begin(), bar.end(), foo.begin(), foo.end(), std::inserter(result));
    return result;
}();


问:
How to do a replace for given example in Sql?
I want to replace always the last node in the string-

```<code>root/node1/node2
</code>```

If I pass node3 as the parameter it should do a replace like this -

```<code> root/node1/node3
</code>```

Can anyone help me do this say the column name was lineage and I have the id. So, the query would be -

```<code>Update
   tree
set
  lineage= -- replace(lineage,node3)  -- this is what i need  ?
where
  id=2
</code>```

答:
User Defined Function. You have the option of T-SQL or .NET languages. I, myself, would chose .NET, as it give the ability to use Regex to more efficiently hone in on the last part of the string, but you can split and reassemble a string using T-SQL. This shows splitting, for example:

http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

Body:
I want to replace always the last node in the string-

root/node1/node2

If I pass node3 as the parameter it should do a replace like this -

 root/node1/node3

Can anyone help me do this say the column name was lineage and I have the id. So, the query would be -

Update
   tree
set
  lineage= -- replace(lineage,node3)  -- this is what i need  ?
where
  id=2


问:
Reading HDFS small size partitions?
Our data loads into hdfs with partition columns as date daily. The issue is each partition has small file size less than 50mb. So when we read the data from all these partition to load the data to next table take  hours. How can we address this issue?</p>

答:
I'd suggest you to run end of the day job to coalesce/combine and make a large file which is significantly bigger in size for processing in spark, before reading from spark.

Further reading cloudera blog/docs to address these problems
Partition Management in Hadoop where several techniques were discussed to address these problems like

Merge partitions on selected tables

Archiving cold data

Delete partitions

Select one of the technique discussed in cloudera blog to match your kind of requirements. Hope this helps!

Other good options Typical use case  is using open source delta lake/ if you are using databricks go for their delta lake for getting rich set of features...

Example maven coordinates.

```<code><dependency>
  <groupId>io.delta</groupId>
  <artifactId>delta-core_2.11</artifactId>
  <version>0.6.1</version>
</dependency>

</code>```

using delta. lake you can insert/update/delete the data as you want. it will reduce maintenance steps...

Compacting Small Files in Delta Lakes

Title: Reading HDFS small size partitions?

Body:
I'd suggest you to run end of the day job to coalesce/combine and make a large file which is significantly bigger in size for processing in spark, before reading from spark.

Further reading cloudera blog/docs to address these problems
Partition Management in Hadoop where several techniques were discussed to address these problems like

Merge partitions on selected tables

Archiving cold data

Delete partitions

Select one of the technique discussed in cloudera blog to match your kind of requirements. Hope this helps!

Other good options Typical use case  is using open source delta lake/ if you are using databricks go for their delta lake for getting rich set of features...

Example maven coordinates.

<dependency>
  <groupId>io.delta</groupId>
  <artifactId>delta-core_2.11</artifactId>
  <version>0.6.1</version>
</dependency>

using delta. lake you can insert/update/delete the data as you want. it will reduce maintenance steps...

Compacting Small Files in Delta Lakes


问:
Select and compare two columns from different tables to find matched records
I'm just learning PHP and MySQL and I have two tables in the same database : FirstYear , SecondYear that have a structure like this :

```<code>StudentId |Math | Physics       StudentId1 | Math1 | physics1
Joe         10     14              Alan       12       17
Alan        13     17              Smith      11       13
Smith       9      9               Joe        10       15
</code>```

Is it possible to write a query that select and compare the two columns StudentId , StudentId1 to find matched records and if for example Joe=Joe after that compare records of math with math1 and physics with physics1 that are in the same row as matched records of StudentId with StudentId1 ;the idea of this query is to study the improvement of same student from first year to the second one ,Thanks .

答:
Yes, it is possible but you have to complete SQL fundamental course.

In this situation you have to know about JOIN. Such as, Inner Join, Left Join, Right Join, Full Join etc. Also, compare with unique id, not name. Because, name always duplicate. It is not good practice.  So, Know about primary key and foreign key.
However,

Query-

SELECT * FROM FirstYear INNER JOIN SecondYear ON FirstYear.StudentId = SecondYear.StudentId1 WHERE FirstYear.id = 1

Something like that, alternatively, you can try to another logic.

Body:
I'm just learning PHP and MySQL and I have two tables in the same database : FirstYear , SecondYear that have a structure like this :

StudentId |Math | Physics       StudentId1 | Math1 | physics1
Joe         10     14              Alan       12       17
Alan        13     17              Smith      11       13
Smith       9      9               Joe        10       15

Is it possible to write a query that select and compare the two columns StudentId , StudentId1 to find matched records and if for example Joe=Joe after that compare records of math with math1 and physics with physics1 that are in the same row as matched records of StudentId with StudentId1 ;the idea of this query is to study the improvement of same student from first year to the second one ,Thanks .


问:
Table storage showing data in only string format
I'm using ADF pipeline to copy data from data lake to blob storage and then from blob storage to table storage.

As you can see below, here are the column types in ADF Data Flow Sink - Blob Storage (integer, string, timestamp):

Here is the Mapping settings in Copy data activity:

On checking the output in table storage, I see all columns are of string type:

Why is table storage saving data in string values? How do I resolve this issue in table storage so that it will accept columns in the right type (integer, string, timestamp)? Please let me know. Thank you!

答:
In usually, when load data from blob storage in Data Factory, all the default data type in blob file are String, Data Factory will help you convert the data type automatically to Sink.

But it also can not meet all our requests.

I tested copy data from Blob to Table Storage and found that: if we don't specify the data type manually in Source, after pipeline executed, all the data type will be String in Sink(Table Storage).

For example, this my Source blob file:

If I don't change the source data type, it seems that everything is ok in Sink table:

But after the pipeline executed, the data type in table storage are all String:

If we change the data type in Source blob manually, and it works ok!

For another question, a little confuse that just from you screenshot, that seems the UI of Mapping Data Flow Sink, but Mapping Data Flow doesn't support Table Storage as Sink.

Hope this helps.


问:
Can we delete a PowerBI Dashboard using Powershell
I am trying to copy Power BI Dashboard from one workspace to the other using below code

```<code>New-PowerBIDashboard -Name $dashboard_name -WorkspaceId $target_workspace_ID
</code>```

The Dashboard is created successfully but in case a dashboard with same name exist the it is not being overridden instead I see 2 dashboards with same name. Is there a way I can delete the existing dashboard from target using powershell ?

答:
It seems the powershell command for deleting PowerBIDashboard doesnot exist.  And there is not a rest api existing which allows deleting a dashboard programmatically currently. You might have to delete it from the UI.

Here is a user voice to support Deleting a dashboard via the API. You can vote it up. Or you can create a new one for your own.

Body:
I am trying to copy Power BI Dashboard from one workspace to the other using below code

New-PowerBIDashboard -Name $dashboard_name -WorkspaceId $target_workspace_ID

The Dashboard is created successfully but in case a dashboard with same name exist the it is not being overridden instead I see 2 dashboards with same name. Is there a way I can delete the existing dashboard from target using powershell ?


问:
Consumer assignment with multiple topics with Kafka Streams
Apologies if this has been already covered before here, I couldn't find anything closely related. I have this Kafka Streams app which reads from multiple topics, persist the records on a DB and then publish an event to an output topic. Pretty straightforward, it's stateless in terms of kafka local stores. (Topology below)

Topic1(T1) has 5 partitions, Topic2(T2) has a single partition. The issue here is, while consuming from two topics, if I want to go "full speed" with T1 (5 consumers), it doesn't guarantee that I will have dedicated consumers for each partition on T1. It will be distributed within the two topic partitions and I might end up with unbalanced consumers (and idle consumers), something like below:

[c1: t1p1, t1p3], [c2: t1p2, t1p5], [c3: t1p4, t2p1], [c4: (idle consumer)], [c5: (idle consumer)]

[c1: t1p1, t1p2], [c2: t1p5], [c3: t1p4, t2p1], [c4: (idle consumer)], [c5: t1p3]

With that said:

Is it a good practice having a topology that reads from multiple topics within the same KafkaStreams instance?

Is there any way to achieve a partition assignment like the following if I want go "full speed" for T1? [c1: t1p1, t2p1], [c2: t1p2], [c3: t1p3], [c4: t1p4], [c5: t1p5]

Which of the topologies below is most optimal to what I want to achieve? Or is it completely unrelated?

Option A (Current topology)

```<code>Topologies:
   Sub-topology: 0
    Source: topic1-source (topics: [TOPIC1])
      --> topic1-processor
    Processor: topic1-processor (stores: [])
      --> topic1-sink
      <-- topic1-source
    Sink: topic1-sink (topic: OUTPUT-TOPIC)
      <-- topic1-processor

  Sub-topology: 1
    Source: topic2-source (topics: [TOPIC2])
      --> topic2-processor
    Processor: topic2-processor (stores: [])
      --> topic2-sink
      <-- topic2-source
    Sink: topic2-sink (topic: OUTPUT-TOPIC)
      <-- topic2-processor
</code>```

Option B:

```<code>Topologies:
   Sub-topology: 0
    Source: topic1-source (topics: [TOPIC1])
      --> topic1-processor
    Source: topic2-source (topics: [TOPIC2])
      --> topic2-processor
    Processor: topic1-processor (stores: [])
      --> response-sink
      <-- topic1-source
    Processor: topic2-processor (stores: [])
      --> response-sink
      <-- topic2-source
    Sink: response-sink (topic: OUTPUT-TOPIC)
      <-- topic2-processor, topic1-processor
</code>```

If I use two streams for each topic instead of a single streams with multiple topic, would that work for what I am trying to achieve?

```<code>config1.put("application.id", "app1");
KakfaStreams stream1 = new KafkaStreams(config1, topologyTopic1);
stream1.start();

config2.put("application.id", "app2");
KakfaStreams stream2 = new KafkaStreams(config2, topologyTopic2);
stream2.start();
</code>```

答:
The initial assignments you describe, would never happen with Kafka Streams (And also not with any default Consumer config). If there are 5 partitions and you have 5 consumers, each consumer would get 1 partition assigned (for a plain consumer with a custom PartitionAssignor you could do the assignment differently, but all default implementations would ensure proper load balancing).

Is it a good practice having a topology that reads from multiple topics within the same KafkaStreams instance?

There is not issue with that.

Is there any way to achieve a partition assignment like the following if I want go "full speed" for T1? [c1: t1p1, t2p1], [c2: t1p2], [c3: t1p3], [c4: t1p4], [c5: t1p5]

Depending how you write your topology, this would be the assignment Kafka Streams uses out-of-the-box. For you two options, option B would result in this assignment.

Which of the topologies below is most optimal to what I want to achieve? Or is it completely unrelated?

As mentioned above, Option B would result in the assignment above. For Option A, you could actually even use a 6th instance and each instance would processes exactly one partition (because there are two sub-topologies, you get 6 tasks, 5 for sub-topology-0 and 1 for sub-topology-1; sub-topologies are scaled out independently of each other); for Option A, you only get 5 tasks though because there is only one sub-topology and thus the maximum number of partitions of both input topic (that is 5) determines the number of tasks.

If I use two streams for each topic instead of a single streams with multiple topic, would that work for what I am trying to achieve?

Yes, it would be basically the same as Option A -- however, you get two consumer groups and thus "two application" instead of one.

Body:
Apologies if this has been already covered before here, I couldn't find anything closely related. I have this Kafka Streams app which reads from multiple topics, persist the records on a DB and then publish an event to an output topic. Pretty straightforward, it's stateless in terms of kafka local stores. (Topology below)

Topic1(T1) has 5 partitions, Topic2(T2) has a single partition. The issue here is, while consuming from two topics, if I want to go "full speed" with T1 (5 consumers), it doesn't guarantee that I will have dedicated consumers for each partition on T1. It will be distributed within the two topic partitions and I might end up with unbalanced consumers (and idle consumers), something like below:

[c1: t1p1, t1p3], [c2: t1p2, t1p5], [c3: t1p4, t2p1], [c4: (idle consumer)], [c5: (idle consumer)]

[c1: t1p1, t1p2], [c2: t1p5], [c3: t1p4, t2p1], [c4: (idle consumer)], [c5: t1p3]

With that said:

Is it a good practice having a topology that reads from multiple topics within the same KafkaStreams instance?

Is there any way to achieve a partition assignment like the following if I want go "full speed" for T1? [c1: t1p1, t2p1], [c2: t1p2], [c3: t1p3], [c4: t1p4], [c5: t1p5]

Which of the topologies below is most optimal to what I want to achieve? Or is it completely unrelated?

Option A (Current topology)

Topologies:
   Sub-topology: 0
    Source: topic1-source (topics: [TOPIC1])
      --> topic1-processor
    Processor: topic1-processor (stores: [])
      --> topic1-sink
      <-- topic1-source
    Sink: topic1-sink (topic: OUTPUT-TOPIC)
      <-- topic1-processor

  Sub-topology: 1
    Source: topic2-source (topics: [TOPIC2])
      --> topic2-processor
    Processor: topic2-processor (stores: [])
      --> topic2-sink
      <-- topic2-source
    Sink: topic2-sink (topic: OUTPUT-TOPIC)
      <-- topic2-processor

Option B:

Topologies:
   Sub-topology: 0
    Source: topic1-source (topics: [TOPIC1])
      --> topic1-processor
    Source: topic2-source (topics: [TOPIC2])
      --> topic2-processor
    Processor: topic1-processor (stores: [])
      --> response-sink
      <-- topic1-source
    Processor: topic2-processor (stores: [])
      --> response-sink
      <-- topic2-source
    Sink: response-sink (topic: OUTPUT-TOPIC)
      <-- topic2-processor, topic1-processor

If I use two streams for each topic instead of a single streams with multiple topic, would that work for what I am trying to achieve?

config1.put("application.id", "app1");
KakfaStreams stream1 = new KafkaStreams(config1, topologyTopic1);
stream1.start();

config2.put("application.id", "app2");
KakfaStreams stream2 = new KafkaStreams(config2, topologyTopic2);
stream2.start();


问:
Using Key by Azure Key Vault to Encrypt and Decrypt text
I'm trying use a key from Azure Key Vault to Encrypt and Decrypt the cookies of a web API.

To encryption proccess I'm using the RSA, in that class:

```<code>    public class SimpleRSA
    {
        private RSA _rsa;

        public SimpleRSA(RSA rsa)
        {
            _rsa = rsa;
        }

        public string EncryptAsync(string value)
        {
            var byteData = Encoding.Unicode.GetBytes(value);
            var encryptedText = _rsa.Encrypt(byteData, RSAEncryptionPadding.OaepSHA1);
            var encodedText = Convert.ToBase64String(encryptedText);
            return encodedText;
        }

        public string DecryptAsync(string encryptedText)
        {
            var encryptedBytes = Convert.FromBase64String(encryptedText);
            var decryptionResult = _rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA1);
            var decryptedText = Encoding.Unicode.GetString(decryptionResult);
            return decryptedText;
        }
    }
</code>```

And I'm getting my RSA from the Key, using that code:

```<code>  public RSA GetRSA(string appId, string appSecret)
        {
            AuthenticationCallback callback = async (authority, resource, scope) =>
            {
                var authContext = new AuthenticationContext(authority);

                var credential = new ClientCredential(appId, appSecret);
                var authResult = await authContext.AcquireTokenAsync(resource, credential);
                return authResult.AccessToken;
            };

            var client = new KeyVaultClient(callback);

            var result = client.GetKeyAsync(_vaultBaseUrl, _keyId).Result;
            var key = result.Key;

            return key.ToRSA();
        }
</code>```

I got the RSA from my Azure Key Vault and I managed encrypt my string. The problem is when I'm trying Decrypt the value. In that process I got that error:

```<code>System.Security.Cryptography.CryptographicException: 'Error decoding OAEP padding.'
</code>```

I think that can be happening because I'm without the private keys in RSA, but I've tried use this method to get the RSA with private key::

```<code>key.ToRSA(true);
</code>```

But a got that error:

So, I don't know how I can complete this process. Are there other way to do that? Or what's wrong?

答:
Key Vault can store three item types: Keys, Secrets and Certificates. Keys are always asymmetric - RSA or Elliptic Curve, and the private keys don't leave KV. What you need is to use a symmetric key, but you need to store that as a Secret, not a key. </p>

<p>So store a 256-bit random secret in KV, call it MyCoolCryptoKey, pull that symmetric key into your C# code and use that as a key for AES. </p>

Body:
I'm trying use a key from Azure Key Vault to Encrypt and Decrypt the cookies of a web API.

To encryption proccess I'm using the RSA, in that class:

    public class SimpleRSA
    {
        private RSA _rsa;

        public SimpleRSA(RSA rsa)
        {
            _rsa = rsa;
        }

        public string EncryptAsync(string value)
        {
            var byteData = Encoding.Unicode.GetBytes(value);
            var encryptedText = _rsa.Encrypt(byteData, RSAEncryptionPadding.OaepSHA1);
            var encodedText = Convert.ToBase64String(encryptedText);
            return encodedText;
        }

        public string DecryptAsync(string encryptedText)
        {
            var encryptedBytes = Convert.FromBase64String(encryptedText);
            var decryptionResult = _rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA1);
            var decryptedText = Encoding.Unicode.GetString(decryptionResult);
            return decryptedText;
        }
    }

And I'm getting my RSA from the Key, using that code:

  public RSA GetRSA(string appId, string appSecret)
        {
            AuthenticationCallback callback = async (authority, resource, scope) =>
            {
                var authContext = new AuthenticationContext(authority);

                var credential = new ClientCredential(appId, appSecret);
                var authResult = await authContext.AcquireTokenAsync(resource, credential);
                return authResult.AccessToken;
            };

            var client = new KeyVaultClient(callback);

            var result = client.GetKeyAsync(_vaultBaseUrl, _keyId).Result;
            var key = result.Key;

            return key.ToRSA();
        }

I got the RSA from my Azure Key Vault and I managed encrypt my string. The problem is when I'm trying Decrypt the value. In that process I got that error:

System.Security.Cryptography.CryptographicException: 'Error decoding OAEP padding.'

I think that can be happening because I'm without the private keys in RSA, but I've tried use this method to get the RSA with private key::

key.ToRSA(true);

But a got that error:

So, I don't know how I can complete this process. Are there other way to do that? Or what's wrong?

Body:
Key Vault can store three item types: Keys, Secrets and Certificates. Keys are always asymmetric - RSA or Elliptic Curve, and the private keys don't leave KV. What you need is to use a symmetric key, but you need to store that as a Secret, not a key.

So store a 256-bit random secret in KV, call it MyCoolCryptoKey, pull that symmetric key into your C# code and use that as a key for AES.


问:
How to copy a specific text from html attribute to a PHP String?
```<code><input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">
</code>```

This is the code which is generated, I made a string $payid, but it copies the whole code. All I need is hashValue=

$payid = getStr($html, '< input type="hidden" name="payFormParams" id="payFormParams" value="','">');
```

But I want to just copy the value of hashValue into $payid that is just 6a1562f5c4901522ab6926a4caf9f278
Can someone please help me how to do this? I am lost. I need help with it.

答:
```<code>$str = '<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">';

     $preg='/<input .*?hashValue=(.*?)".*?>/'; //Regular expression
     preg_match_all($preg,$str,$array);  //Match regular expression
     echo $array[1][0]; //return string
</code>```

Body:
<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">

This is the code which is generated, I made a string $payid, but it copies the whole code. All I need is hashValue=

$payid = getStr($html, '< input type="hidden" name="payFormParams" id="payFormParams" value="','">');

But I want to just copy the value of hashValue into $payid that is just 6a1562f5c4901522ab6926a4caf9f278
Can someone please help me how to do this? I am lost. I need help with it.


问:
Flutter Firebase - DropdownMenuItem: The method 'map' was called on null
In my application I would like to display vaccines according to the species of the animal (If is a dog or cat). I'm experiencing an error: The method 'map' was called on null. Tried calling: map DropdownMenuItem. Why is this happening? I already put async and await in the methods, I don't understand why it is still null. Bellow my code:

1) This is where I call my DropdownContent class in init to prepare my DropdownMenuItem in the row inside the widget

```<code>class _VaccineDetailFormState extends State<VaccineDetailForm> {

final DataRepository repository = DataRepository();
String selectedVaccine = "Select";
List<String> vaccinesBySpecie;

  initState() {
    DropdownContent.getVaccines(widget.selectedPetID).then((value) => vaccinesBySpecie = value);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
    [...]
              new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new DropdownButton<String>(
                      value:  widget.vaccine.name == null ? selectedVaccine: widget.vaccine.name,
                      underline: Container(
                        height: 2,
                        color: Colors.grey,
                      ),
                      onChanged: (String newValue) {
                        setState(() {
                          selectedVaccine = newValue;
                          widget.vaccine.name = newValue;
                        });
                      },
                      items: vaccinesBySpecie.map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                    )
                  ]),

                  [...]
</code>```

2) Here is the DropdownContent class that, inside the getVaccines() method, searches the repository to find out the species of the current animal and then returns the appropriate vaccine list.

```<code>class Dropdown content

static Future<List<String>> getVaccines(String petId) async {

    final DataRepository repository = DataRepository();
    String currentSpecie = await repository.getSpecie(petId);

    if (currentSpecie.contains('Dog')) {
      return listOfVaccinesForDogs();
    }
    if (currentSpecie.contains('Cat')) {
      return listOfVaccinesForCats();
    }
}
</code>```

3) Finally, the repository class that searches for the species of the animal

```<code> class Repository

   Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    await documentReference.get().then((snapshot) {
      return snapshot.data['specie'].toString();
    });
  }
</code>```

答:
What Dean said illuminated my ideas. I managed to solve it by reaching the following answer:

1) DropdownMenuItem inside the widget

```<code> Container(
                child:  FutureBuilder <List<String>>(
                    future: DropdownContent.getVaccines(widget.selectedPetID),
                    builder: (context, AsyncSnapshot snapshot) {
                      if(snapshot.data == null) {
                        return CircularProgressIndicator();
                      }
                      else {
                        return DropdownButton<String>(
                          value: widget.vaccine.name == null? selectedVaccine: widget.vaccine.name,
                          underline: Container(
                            height: 2,
                            color: Colors.grey,
                          ),
                          onChanged: (String newValue) {
                            setState(() {
                              selectedVaccine = newValue;
                              widget.vaccine.name = newValue;
                            });
                          },
                          items: snapshot.data.map<DropdownMenuItem<String>>((value) =>
                          new DropdownMenuItem<String>(
                            child: Text(value),
                            value: value,
                          ))
                              .toList(),
                        );
                      }
                    })
              )
</code>```

2) DropdownContent class that searches the repository to find out the species of the current animal and then returns the appropriate vaccine list:

```<code>  static Future<List<String>> getVaccines(String petId) async {
    final DataRepository repository = DataRepository();
    String currentSpecie;
    await repository.getSpecie(petId).then((value) {
      currentSpecie = value;
    });

    if (currentSpecie.contains('Dog')) {
      return listOfVaccinesForDogs();
    }
    if (currentSpecie.contains('Cat')) {
      return listOfVaccinesForCats();
    }
  }
</code>```

3) The repository class that searches for the species of the animal

```<code>  Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    String specie;
    await documentReference.get().then((snapshot) {
      specie = snapshot.data['specie'].toString();
    });
    return specie;
  }
</code>```

Body:
In my application I would like to display vaccines according to the species of the animal (If is a dog or cat). I'm experiencing an error: The method 'map' was called on null. Tried calling: map DropdownMenuItem. Why is this happening? I already put async and await in the methods, I don't understand why it is still null. Bellow my code:

1) This is where I call my DropdownContent class in init to prepare my DropdownMenuItem in the row inside the widget

class _VaccineDetailFormState extends State<VaccineDetailForm> {

final DataRepository repository = DataRepository();
String selectedVaccine = "Select";
List<String> vaccinesBySpecie;

  initState() {
    DropdownContent.getVaccines(widget.selectedPetID).then((value) => vaccinesBySpecie = value);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
    [...]
              new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new DropdownButton<String>(
                      value:  widget.vaccine.name == null ? selectedVaccine: widget.vaccine.name,
                      underline: Container(
                        height: 2,
                        color: Colors.grey,
                      ),
                      onChanged: (String newValue) {
                        setState(() {
                          selectedVaccine = newValue;
                          widget.vaccine.name = newValue;
                        });
                      },
                      items: vaccinesBySpecie.map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                    )
                  ]),

                  [...]

2) Here is the DropdownContent class that, inside the getVaccines() method, searches the repository to find out the species of the current animal and then returns the appropriate vaccine list.

class Dropdown content

static Future<List<String>> getVaccines(String petId) async {

    final DataRepository repository = DataRepository();
    String currentSpecie = await repository.getSpecie(petId);

    if (currentSpecie.contains('Dog')) {
      return listOfVaccinesForDogs();
    }
    if (currentSpecie.contains('Cat')) {
      return listOfVaccinesForCats();
    }
}

3) Finally, the repository class that searches for the species of the animal

 class Repository

   Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    await documentReference.get().then((snapshot) {
      return snapshot.data['specie'].toString();
    });
  }

Body:
What Dean said illuminated my ideas. I managed to solve it by reaching the following answer:

1) DropdownMenuItem inside the widget

 Container(
                child:  FutureBuilder <List<String>>(
                    future: DropdownContent.getVaccines(widget.selectedPetID),
                    builder: (context, AsyncSnapshot snapshot) {
                      if(snapshot.data == null) {
                        return CircularProgressIndicator();
                      }
                      else {
                        return DropdownButton<String>(
                          value: widget.vaccine.name == null? selectedVaccine: widget.vaccine.name,
                          underline: Container(
                            height: 2,
                            color: Colors.grey,
                          ),
                          onChanged: (String newValue) {
                            setState(() {
                              selectedVaccine = newValue;
                              widget.vaccine.name = newValue;
                            });
                          },
                          items: snapshot.data.map<DropdownMenuItem<String>>((value) =>
                          new DropdownMenuItem<String>(
                            child: Text(value),
                            value: value,
                          ))
                              .toList(),
                        );
                      }
                    })
              )

2) DropdownContent class that searches the repository to find out the species of the current animal and then returns the appropriate vaccine list:

  static Future<List<String>> getVaccines(String petId) async {
    final DataRepository repository = DataRepository();
    String currentSpecie;
    await repository.getSpecie(petId).then((value) {
      currentSpecie = value;
    });

    if (currentSpecie.contains('Dog')) {
      return listOfVaccinesForDogs();
    }
    if (currentSpecie.contains('Cat')) {
      return listOfVaccinesForCats();
    }
  }

3) The repository class that searches for the species of the animal

  Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    String specie;
    await documentReference.get().then((snapshot) {
      specie = snapshot.data['specie'].toString();
    });
    return specie;
  }


问:
COUNTIF Formula moves down when row at top added
I have the following COUNTIF Formula in my Google Sheet.

=COUNTIFS('Events/Incidents'!$E$3:$E,X4,'Events/Incidents'!$I$3:$I,"Accident")```
</div>
</div>
</p>

<p>This is a sample of the sheet which has the formula in the first row under the "Accidents" header:</p>

<p><img src="https://i.stack.imgur.com/ftQVE.png" alt="enter image description here"></p>

<p>It works until a user adds a row 3 to the top of the source sheet (Events/Incidents) then the formula changes to the following so that it captures row 4 down instead of the desired row 3.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>=COUNTIFS('Events/Incidents'!$E$4:$E,X4,'Events/Incidents'!$I$4:$I,"Accident")</code>```

I used the Query function for "All Events" (the first 3 columns). The Countif formula is under each of the Incidents. In my Countif example, X4 is the Employee, John White which was returned in the QUERY.

The QUERY continues to return/include row 3 but I don't know how to do this for the individual Incidents. I tried adding ArrayFormula to the Countif function but I have the same problem.

Would appreciate some help with this.

答:
I worked it out by combining Countifs with ImportRange:

=COUNTIFS(IMPORTRANGE("1-f6OU8ylDSlpqdpt4P5B7GDcIel3IboVkUbY2huMA6U","Events/Incidents!$E$3:$E"),X4,IMPORTRANGE("1-f6OU8ylDSlpqdpt4P5B7GDcIel3IboVkUbY2huMA6U","Events/Incidents!$I$3:$I"),"Accident")```

Body:
I have the following COUNTIF Formula in my Google Sheet.

=COUNTIFS('Events/Incidents'!$E$3:$E,X4,'Events/Incidents'!$I$3:$I,"Accident")

This is a sample of the sheet which has the formula in the first row under the "Accidents" header:

It works until a user adds a row 3 to the top of the source sheet (Events/Incidents) then the formula changes to the following so that it captures row 4 down instead of the desired row 3.

=COUNTIFS('Events/Incidents'!$E$4:$E,X4,'Events/Incidents'!$I$4:$I,"Accident")

I used the Query function for "All Events" (the first 3 columns). The Countif formula is under each of the Incidents. In my Countif example, X4 is the Employee, John White which was returned in the QUERY.

The QUERY continues to return/include row 3 but I don't know how to do this for the individual Incidents. I tried adding ArrayFormula to the Countif function but I have the same problem.

Would appreciate some help with this.


问:
Running a set function name in multiple Powershell scripts
I am building a testing framework for my current development team. One thing that I'd like to let them do is create a Powershell script to run their tests. The system is a database deploy system, so to test it they will need to potentially run some set-up code, then the deploy will be kicked off, then they will run some check code at the end.

Since the deploy takes awhile I'd like to have the framework handle that once for all of the tests. So, the basic flow is:

```<code>Run test #1 set-up
Run test #2 set-up
Run test #3 set-up
Run the deploy process
Run the code to confirm that test #1 passed
Run the code to confirm that test #2 passed
Run the code to confirm that test #3 passed
</code>```

I figured that I would have the framework always call a function called "setup" (or something similar) in all of the Powershell scripts in a particular directory. If no "setup" function exists that's ok and it shouldn't error out. Then I would run the deploy and then run the other functions in the Powershell scripts.

Given a directory listing, how could I cycle through each Powershell script and run these functions?

Thanks for any guidance!

答:
Thanks to Matt's ideas I was able to come across Invoke-Expression. Ideally I would have liked to use Invoke-Command with the -filepath parameter, which supposedly defaults to running locally. However, there is a bug that requires using the -ComputerName parameter even when running locally. If you use that parameter then it requires remoting to be turned on, even when running on the local computer.

Here's the code that I used in my script:

```<code># Run the setup functions from all of the Powershell test scripts
foreach ($testPSScript in Get-ChildItem "$testScriptDir\*.ps1") {
    Invoke-Expression "$testPSScript -Setup"
}

# Do some other stuff

# Run the tests in the Powershell test scripts
foreach ($testPSScript in Get-ChildItem "$testScriptDir\*.ps1") {
    Invoke-Expression "$testPSScript"
}
</code>```

My test script then looked like this:

```<code>param([switch]$Setup = $false)

if ($Setup) {write-host "Setting things up"; return}

Write-Host "Running the tests"
</code>```

Body:
I am building a testing framework for my current development team. One thing that I'd like to let them do is create a Powershell script to run their tests. The system is a database deploy system, so to test it they will need to potentially run some set-up code, then the deploy will be kicked off, then they will run some check code at the end.

Since the deploy takes awhile I'd like to have the framework handle that once for all of the tests. So, the basic flow is:

Run test #1 set-up
Run test #2 set-up
Run test #3 set-up
Run the deploy process
Run the code to confirm that test #1 passed
Run the code to confirm that test #2 passed
Run the code to confirm that test #3 passed

I figured that I would have the framework always call a function called "setup" (or something similar) in all of the Powershell scripts in a particular directory. If no "setup" function exists that's ok and it shouldn't error out. Then I would run the deploy and then run the other functions in the Powershell scripts.

Given a directory listing, how could I cycle through each Powershell script and run these functions?

Thanks for any guidance!

Body:
Thanks to Matt's ideas I was able to come across Invoke-Expression. Ideally I would have liked to use Invoke-Command with the -filepath parameter, which supposedly defaults to running locally. However, there is a bug that requires using the -ComputerName parameter even when running locally. If you use that parameter then it requires remoting to be turned on, even when running on the local computer.

Here's the code that I used in my script:

# Run the setup functions from all of the Powershell test scripts
foreach ($testPSScript in Get-ChildItem "$testScriptDir\*.ps1") {
    Invoke-Expression "$testPSScript -Setup"
}

# Do some other stuff

# Run the tests in the Powershell test scripts
foreach ($testPSScript in Get-ChildItem "$testScriptDir\*.ps1") {
    Invoke-Expression "$testPSScript"
}

My test script then looked like this:

param([switch]$Setup = $false)

if ($Setup) {write-host "Setting things up"; return}

Write-Host "Running the tests"


问:
react native - should I run the server with the command react-native start so that users can use the app?
When deploying react-native, should I run the server with the command react-native start so that users can use the app?</p>

答:
Hope this question understand when you react-native start
What are the difference between these React Native start commands?
React-native start should use in development environment. When your device or simulator connected to server</p>