问:
Read data in activity of recyclerview adapter
I have a recyclerview with a card and spinners in it, the values selected in the spinner I need to send it to the next activity to calculate estimated price. I have a button in the activity which is not of the recyclerview, that takes me to next activity where I need the values. So when I click this button I need it to collect the data and send it to next activity, how can I achieve that.

I have attached a picture. RED ARROW(data i need in next activity), BLUE ARROW(button press which takes me to next activity)

Screenshot of screen

I'm using this method to read the values

```<code>findMerchantTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i = 0; i < totalCards; i++) {
                    Spinner printColorSpinner = mRecyclerView.findViewHolderForLayoutPosition(i).itemView.findViewById(R.id.printColorSpinner);
                    Spinner printSidesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.printSidesSpinner);
                    Spinner printSizeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.paperSizeSpinner);
                    Spinner pagesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.pagesSpinner);
                    Spinner orientationSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.orientationSpinner);
                    Spinner bindingTypeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.bindingTypeSpinner);
                    MaterialTextView copiesTextView = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.copiesNumberText);
                    String color = printColorSpinner.getSelectedItem().toString().trim();
                    String sides = printSidesSpinner.getSelectedItem().toString().trim();
                    String size = printSizeSpinner.getSelectedItem().toString().trim();
                    String pages = pagesSpinner.getSelectedItem().toString().trim();
                    String orientation = orientationSpinner.getSelectedItem().toString().trim();
                    String bindingType = bindingTypeSpinner.getSelectedItem().toString().trim();
                    String totalCopies = copiesTextView.getText().toString().trim();
                }
            }
        });
</code>```

But when i becomes 2, findViewHolderForLayoutPosition returns NullPointerException. I searched and got to know that the views are recycled and only the views that are laid out on screen will be readable.

What will be the alternative to get these values? Thanks!

答:
The RecyclerView reuses the views to improve the performance and memory consumption and you only have access to the visible views. One way to accomplish your goal is to use an interface for the interactions between the Activity that contains the RecyclerView and the Adapter, and them update the main array of your objects.

Example:

Imagine you have a Class to define your data.

YourClass.java

```<code>public class YourClass extends Object implements Parcelable {

  public String color = "";
  public String sides = "";
  public String size = "";
  public String pages = "";
  public String orientation = "";
  public String bindingType = "";
  public String totalCopies = "";

  //... your methods and implementations
}
</code>```

Lets define an interface to handle the events of the spinners

AdapterSpinnerListener.java

```<code>public interface AdapterSpinnerListener {
    public void onSpinnerChanged(String spinnerType, String spinnerValue,  int position);

    //... other events
}
</code>```

Implements a Custom Adapter to for your RecyclerView

CustomAdapter.java

```<code>public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private AdapterActionListener adapterActionListener;

    // Your constructor receive the Fragment of Activity which implements the AdapterSpinnerListener.
    // Also receive the array of objects to populate the RecyclerView
    public CustomAdapter(YourActivity activity, ArrayList<YourClass> customRows)
    {
      this.adapterActionListener = activity;
    }

    //... implements all the needed functions for the RecyclerView
    //getItemId
    //getItemCount
    //getItemViewType
    //onCreateViewHolder

    //In your onBindViewHolder, you should add a listener for each one of your spinners.
    //Also I'm supossing you have a CustomViewHolder to reference the Layout and Spinners.

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
      CustomViewHolder holder = (CustomViewHolder)viewHolder;
      holder.textViewSomething.setText(...);

      holder.printColorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
              if (adapterActionListener != null) {
                  // You can retrieve the selected item using parent.getItemAtPosition(pos)
                  adapterActionListener.onSpinnerChanged("color", selectedValue,  position);
              }
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {

          }
      });

      //holder.printSidesSpinner.setOnItemSelectedListener...
      //...
      //...
      //... You should implement a listener for each spinner
    }
}
</code>```

In the Activity or Fragment that contains the RecyclerView you should implement the interface and define the array of your objects and populate the adapter with the data.

YourActivity.java

```<code>public class YourActivity extends AppCompatActivity implements AdapterSpinnerListener {
    private RecyclerView recyclerView;
    private CustomAdapter customAdapter;
    private ArrayList<YourClass> customRows;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        customAdapter = new CustomAdapter(this, customRows);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    }

  // Implements the method of the interface
  @Override
  public void onSpinnerChanged(String spinnerType, String spinnerValue,  int position) {
    if (spinnerType.equals("color")) {
      customRows.get(position).color = spinnerValue;
    } else if (spinnerType.equals("sides")) {
      customRows.get(position).sides = spinnerValue;
    }
    //...
    //...
  }
}
</code>```

Now the values of your spinners are inside the customRows Array. You can retrieve the values in your click event

```<code>findMerchantTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            for (int i = 0; i < customRows.size(); i++) {
                String color = customRows.get(i).color;
                String sides = customRows.get(i).sides;
                //...
                //...
                //... all the values you want to get for the next activity
                //...
            }
        }
    });
</code>```

Body:
I have a recyclerview with a card and spinners in it, the values selected in the spinner I need to send it to the next activity to calculate estimated price. I have a button in the activity which is not of the recyclerview, that takes me to next activity where I need the values. So when I click this button I need it to collect the data and send it to next activity, how can I achieve that.

I have attached a picture. RED ARROW(data i need in next activity), BLUE ARROW(button press which takes me to next activity)

Screenshot of screen

I'm using this method to read the values

findMerchantTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i = 0; i < totalCards; i++) {
                    Spinner printColorSpinner = mRecyclerView.findViewHolderForLayoutPosition(i).itemView.findViewById(R.id.printColorSpinner);
                    Spinner printSidesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.printSidesSpinner);
                    Spinner printSizeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.paperSizeSpinner);
                    Spinner pagesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.pagesSpinner);
                    Spinner orientationSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.orientationSpinner);
                    Spinner bindingTypeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.bindingTypeSpinner);
                    MaterialTextView copiesTextView = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.copiesNumberText);
                    String color = printColorSpinner.getSelectedItem().toString().trim();
                    String sides = printSidesSpinner.getSelectedItem().toString().trim();
                    String size = printSizeSpinner.getSelectedItem().toString().trim();
                    String pages = pagesSpinner.getSelectedItem().toString().trim();
                    String orientation = orientationSpinner.getSelectedItem().toString().trim();
                    String bindingType = bindingTypeSpinner.getSelectedItem().toString().trim();
                    String totalCopies = copiesTextView.getText().toString().trim();
                }
            }
        });

But when i becomes 2, findViewHolderForLayoutPosition returns NullPointerException. I searched and got to know that the views are recycled and only the views that are laid out on screen will be readable.

What will be the alternative to get these values? Thanks!

Body:
The RecyclerView reuses the views to improve the performance and memory consumption and you only have access to the visible views. One way to accomplish your goal is to use an interface for the interactions between the Activity that contains the RecyclerView and the Adapter, and them update the main array of your objects.

Example:

Imagine you have a Class to define your data.

YourClass.java

public class YourClass extends Object implements Parcelable {

  public String color = "";
  public String sides = "";
  public String size = "";
  public String pages = "";
  public String orientation = "";
  public String bindingType = "";
  public String totalCopies = "";

  //... your methods and implementations
}

Lets define an interface to handle the events of the spinners

AdapterSpinnerListener.java

public interface AdapterSpinnerListener {
    public void onSpinnerChanged(String spinnerType, String spinnerValue,  int position);

    //... other events
}

Implements a Custom Adapter to for your RecyclerView

CustomAdapter.java

public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private AdapterActionListener adapterActionListener;

    // Your constructor receive the Fragment of Activity which implements the AdapterSpinnerListener.
    // Also receive the array of objects to populate the RecyclerView
    public CustomAdapter(YourActivity activity, ArrayList<YourClass> customRows)
    {
      this.adapterActionListener = activity;
    }

    //... implements all the needed functions for the RecyclerView
    //getItemId
    //getItemCount
    //getItemViewType
    //onCreateViewHolder

    //In your onBindViewHolder, you should add a listener for each one of your spinners.
    //Also I'm supossing you have a CustomViewHolder to reference the Layout and Spinners.

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
      CustomViewHolder holder = (CustomViewHolder)viewHolder;
      holder.textViewSomething.setText(...);

      holder.printColorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
              if (adapterActionListener != null) {
                  // You can retrieve the selected item using parent.getItemAtPosition(pos)
                  adapterActionListener.onSpinnerChanged("color", selectedValue,  position);
              }
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {

          }
      });

      //holder.printSidesSpinner.setOnItemSelectedListener...
      //...
      //...
      //... You should implement a listener for each spinner
    }
}

In the Activity or Fragment that contains the RecyclerView you should implement the interface and define the array of your objects and populate the adapter with the data.

YourActivity.java

public class YourActivity extends AppCompatActivity implements AdapterSpinnerListener {
    private RecyclerView recyclerView;
    private CustomAdapter customAdapter;
    private ArrayList<YourClass> customRows;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        customAdapter = new CustomAdapter(this, customRows);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    }

  // Implements the method of the interface
  @Override
  public void onSpinnerChanged(String spinnerType, String spinnerValue,  int position) {
    if (spinnerType.equals("color")) {
      customRows.get(position).color = spinnerValue;
    } else if (spinnerType.equals("sides")) {
      customRows.get(position).sides = spinnerValue;
    }
    //...
    //...
  }
}

Now the values of your spinners are inside the customRows Array. You can retrieve the values in your click event

findMerchantTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            for (int i = 0; i < customRows.size(); i++) {
                String color = customRows.get(i).color;
                String sides = customRows.get(i).sides;
                //...
                //...
                //... all the values you want to get for the next activity
                //...
            }
        }
    });


来源: stackexchange

问:
Getting the CORS policy: No 'Access-Control-Allow-Origin' error
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

```<code>Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Here is my JavaScript,

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "<a href="+ myObj.articles[i].url +" target='blank'>";
            x += "<div style='background: linear-gradient(rgba(0,130,170,0),rgba(6,23,0,1)), url( "+ myObj.articles[i].urlToImage +" );height: 430px;margin-top: 20px;'>";
            x += "</div>";
            x += "</a>";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();
</code>```

HTML

```<code><div style="background-color: gray;height: 430px;margin-top: 20px;">
   p id="technology"></p>
</div>
</code>```

I don't understand why this is happening.

Please help me out,
Thanks in advance.

答:
```<code>var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var url = 'https://newsapi.org/v2/top-headlines?country=us&category=sports&pageSize=5&apiKey=<your-api-key>';
</code>```

Now you can you use the proxy_url to avoid the CORS policy error by adding the proxy_url in front of your URL with the API-KEY

```<code>new_url = proxy_url + url
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my JavaScript,

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "";
            x += "
";
            x += "
";
            x += "";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();

HTML

   p id="technology">

I don't understand why this is happening.

Please help me out,
Thanks in advance.

Body:
var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var url = 'https://newsapi.org/v2/top-headlines?country=us&category=sports&pageSize=5&apiKey=<your-api-key>';

Now you can you use the proxy_url to avoid the CORS policy error by adding the proxy_url in front of your URL with the API-KEY

new_url = proxy_url + url


问:
Change session cookie name and path in Spring Boot WebFlux
I'm creating a reactive Spring Boot project using WebFlux. I need to configure the session cookie name and path.

In a Tomcat based project it is very easy to configure the session cookie using the configuration file:

```<code>server.servlet.session.cookie.name = MYSESSIONID
server.servlet.session.cookie.path = /
</code>```

If I configure these properties in the WebFlux project it doesn't affect the cookie parameters. How to do that?

答:
If you happen to be using Spring Session you can create your own bean for the WebSessionIdResolver which is what sets the name (and other attributes) of the session cookie.

```<code>@Configuration
public class CookieConfig {

    @Bean
    public WebSessionIdResolver webSessionIdResolver() {
        CookieWebSessionIdResolver resolver = new CookieWebSessionIdResolver();
        resolver.setCookieName("MYSESSIONID");
        return resolver;
    }

}
</code>```

The Spring Session guides cover this in Spring Session - WebFlux with Custom Cookie.

Body:
I'm creating a reactive Spring Boot project using WebFlux. I need to configure the session cookie name and path.

In a Tomcat based project it is very easy to configure the session cookie using the configuration file:

server.servlet.session.cookie.name = MYSESSIONID
server.servlet.session.cookie.path = /

If I configure these properties in the WebFlux project it doesn't affect the cookie parameters. How to do that?

Body:
If you happen to be using Spring Session you can create your own bean for the WebSessionIdResolver which is what sets the name (and other attributes) of the session cookie.

@Configuration
public class CookieConfig {

    @Bean
    public WebSessionIdResolver webSessionIdResolver() {
        CookieWebSessionIdResolver resolver = new CookieWebSessionIdResolver();
        resolver.setCookieName("MYSESSIONID");
        return resolver;
    }

}

The Spring Session guides cover this in Spring Session - WebFlux with Custom Cookie.


问:
KEYCLOAK Test Connection doesn't work "Error! Failed to send email"
I am trying to use the Forgot Password function for my Keycloak authentication. So I have already set On for the Forgot Password in the Login section. And I have tried to set up the configurations under Realm Email.
  In the email tab I entered

```<code>host  smtp.gmail.com
smtp port 465
username  ***@gmail.com
SSL  enabled
Authentication - enabled with username and password
</code>```

But when i'm testing the connection, I keep getting the error "Error! Failed to send email".

Any Help would be highly appreciated, Thank you.

答:
You need to provide your email address to Keycloak administrator's email address, and turn on "Allow less secure apps" on Google account settings page.
https://support.google.com/accounts/answer/6010255?hl=en

If succeed, you can see SMTP test message from Keycloak in your mail box.

Body:
I am trying to use the Forgot Password function for my Keycloak authentication. So I have already set On for the Forgot Password in the Login section. And I have tried to set up the configurations under Realm Email.
  In the email tab I entered

host  smtp.gmail.com
smtp port 465
username  ***@gmail.com
SSL  enabled
Authentication - enabled with username and password

But when i'm testing the connection, I keep getting the error "Error! Failed to send email".

Any Help would be highly appreciated, Thank you.


问:
Use R to Randomly Assign of Participants to Treatments on a Daily Basis
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

```<code># There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)
</code>```

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

答:
Consider splitting data frame by day and gender with by, then run enough samples with replicate at 100 times to pick one of several where treatments are balanced:

Data

```<code>df <- merge(data.frame(participant = p, gender = g),
            data.frame(days = seq(1,365)),
            by=NULL)
</code>```

Solution

```<code>df_list <- by(df, list(df$gender, df$days), function(sub){
  t <- replicate(100, {                                        # RUN 100 REPETITIONS OF EXPRESSION
    s <- sample(c("T1", "T2"), size=nrow(sub), replace=TRUE)   # SAMPLE "T1" AND "T2" BY SIZE OF SUBSET
    s[ sum(s == "T1") == sum(s == "T2") ]                      # FILTER TO EQUAL TREATMENTS
  })

  t <- Filter(length, t)[[1]]             # SELECT FIRST OF SEVERAL NON-EMPTY RETURNS
  transform(sub, treatment = t)           # ASSIGN RESULT TO NEW COLUMN
})

# BIND DATA FRAMES AND RESET ROW.NAMES
final_df <- data.frame(do.call(rbind.data.frame, df_list), row.names=NULL)
</code>```

Output

Day 1

```<code>head(final_df, 16)

#    participant gender days treatment
# 1          P09      F    1        T1
# 2          P10      F    1        T2
# 3          P11      F    1        T2
# 4          P12      F    1        T1
# 5          P13      F    1        T2
# 6          P14      F    1        T2
# 7          P15      F    1        T1
# 8          P16      F    1        T1
# 9          P01      M    1        T1
# 10         P02      M    1        T1
# 11         P03      M    1        T2
# 12         P04      M    1        T2
# 13         P05      M    1        T2
# 14         P06      M    1        T1
# 15         P07      M    1        T1
# 16         P08      M    1        T2
</code>```

Day 365

```<code>tail(final_df, 16)

#      participant gender days treatment
# 5825         P09      F  365        T2
# 5826         P10      F  365        T2
# 5827         P11      F  365        T1
# 5828         P12      F  365        T2
# 5829         P13      F  365        T1
# 5830         P14      F  365        T2
# 5831         P15      F  365        T1
# 5832         P16      F  365        T1
# 5833         P01      M  365        T1
# 5834         P02      M  365        T2
# 5835         P03      M  365        T1
# 5836         P04      M  365        T2
# 5837         P05      M  365        T2
# 5838         P06      M  365        T2
# 5839         P07      M  365        T1
# 5840         P08      M  365        T1
</code>```

Ideally, for analytical purposes you should keep data in long format (i.e., tidy data). But if needing wide format consider reshape with helper and cleanup processing:

```<code># HELPER OBJECTS
final_df$participant_gender <- with(final_df, paste0(participant, gender))
new_names <- paste0(p, g)

# RESHAPE WIDE
wide_df <- reshape(final_df, v.names = "treatment", timevar = "participant_gender",
                   idvar="days", drop = c("gender", "participant"),
                   new.row.names = 1:365, direction = "wide")

# RENAME AND RE-ORDER COLUMNS
names(wide_df) <- gsub("treatment.", "", names(wide_df))
wide_df <- wide_df[c("days", new_names)]

head(wide_df)
#   days P01M P02M P03M P04M P05M P06M P07M P08M P09F P10F P11F P12F P13F P14F P15F P16F
# 1    1   T1   T1   T2   T2   T2   T1   T1   T2   T1   T2   T2   T1   T2   T2   T1   T1
# 2    2   T1   T1   T2   T1   T2   T1   T2   T2   T1   T2   T2   T1   T2   T2   T1   T1
# 3    3   T1   T1   T2   T1   T1   T2   T2   T2   T1   T2   T2   T2   T1   T2   T1   T1
# 4    4   T1   T1   T1   T2   T2   T2   T1   T2   T2   T1   T1   T2   T2   T1   T1   T2
# 5    5   T1   T1   T2   T1   T2   T2   T1   T2   T1   T1   T2   T1   T2   T2   T1   T2
# 6    6   T2   T1   T1   T1   T2   T2   T1   T2   T2   T2   T2   T1   T2   T1   T1   T1
</code>```

Body:
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

# There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

Body:
Consider splitting data frame by day and gender with by, then run enough samples with replicate at 100 times to pick one of several where treatments are balanced:

Data

df <- merge(data.frame(participant = p, gender = g),
            data.frame(days = seq(1,365)),
            by=NULL)

Solution

df_list <- by(df, list(df$gender, df$days), function(sub){
  t <- replicate(100, {                                        # RUN 100 REPETITIONS OF EXPRESSION
    s <- sample(c("T1", "T2"), size=nrow(sub), replace=TRUE)   # SAMPLE "T1" AND "T2" BY SIZE OF SUBSET
    s[ sum(s == "T1") == sum(s == "T2") ]                      # FILTER TO EQUAL TREATMENTS
  })

  t <- Filter(length, t)[[1]]             # SELECT FIRST OF SEVERAL NON-EMPTY RETURNS
  transform(sub, treatment = t)           # ASSIGN RESULT TO NEW COLUMN
})

# BIND DATA FRAMES AND RESET ROW.NAMES
final_df <- data.frame(do.call(rbind.data.frame, df_list), row.names=NULL)

Output

Day 1

head(final_df, 16)

#    participant gender days treatment
# 1          P09      F    1        T1
# 2          P10      F    1        T2
# 3          P11      F    1        T2
# 4          P12      F    1        T1
# 5          P13      F    1        T2
# 6          P14      F    1        T2
# 7          P15      F    1        T1
# 8          P16      F    1        T1
# 9          P01      M    1        T1
# 10         P02      M    1        T1
# 11         P03      M    1        T2
# 12         P04      M    1        T2
# 13         P05      M    1        T2
# 14         P06      M    1        T1
# 15         P07      M    1        T1
# 16         P08      M    1        T2

Day 365

tail(final_df, 16)

#      participant gender days treatment
# 5825         P09      F  365        T2
# 5826         P10      F  365        T2
# 5827         P11      F  365        T1
# 5828         P12      F  365        T2
# 5829         P13      F  365        T1
# 5830         P14      F  365        T2
# 5831         P15      F  365        T1
# 5832         P16      F  365        T1
# 5833         P01      M  365        T1
# 5834         P02      M  365        T2
# 5835         P03      M  365        T1
# 5836         P04      M  365        T2
# 5837         P05      M  365        T2
# 5838         P06      M  365        T2
# 5839         P07      M  365        T1
# 5840         P08      M  365        T1

Ideally, for analytical purposes you should keep data in long format (i.e., tidy data). But if needing wide format consider reshape with helper and cleanup processing:

# HELPER OBJECTS
final_df$participant_gender <- with(final_df, paste0(participant, gender))
new_names <- paste0(p, g)

# RESHAPE WIDE
wide_df <- reshape(final_df, v.names = "treatment", timevar = "participant_gender",
                   idvar="days", drop = c("gender", "participant"),
                   new.row.names = 1:365, direction = "wide")

# RENAME AND RE-ORDER COLUMNS
names(wide_df) <- gsub("treatment.", "", names(wide_df))
wide_df <- wide_df[c("days", new_names)]

head(wide_df)
#   days P01M P02M P03M P04M P05M P06M P07M P08M P09F P10F P11F P12F P13F P14F P15F P16F
# 1    1   T1   T1   T2   T2   T2   T1   T1   T2   T1   T2   T2   T1   T2   T2   T1   T1
# 2    2   T1   T1   T2   T1   T2   T1   T2   T2   T1   T2   T2   T1   T2   T2   T1   T1
# 3    3   T1   T1   T2   T1   T1   T2   T2   T2   T1   T2   T2   T2   T1   T2   T1   T1
# 4    4   T1   T1   T1   T2   T2   T2   T1   T2   T2   T1   T1   T2   T2   T1   T1   T2
# 5    5   T1   T1   T2   T1   T2   T2   T1   T2   T1   T1   T2   T1   T2   T2   T1   T2
# 6    6   T2   T1   T1   T1   T2   T2   T1   T2   T2   T2   T2   T1   T2   T1   T1   T1


问:
Edit account privilige in apex
i can't edit users privileges in apex as below image, it show read only.
account screenshot

the privileges are:

User is a developer

Application Builder Access

SQL Workshop Access

Team Development Access

答: The user in question is an administrator, which includes all of the other privileges already. There's nothing more to assign, and you can't assign the other privileges individually unless you take away the administrator privilege first.</p>

Title: Edit account privilige in apex


问:
CSS class not defined in theme.scss in shopify store
I am working on a shopify store and I want to change the properties of a class. Please see the code below:

```<code><svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-facebook" viewBox="0 0 32 32"><path fill="#444" d="M18.56 31.36V17.28h4.48l.64-5.12h-5.12v-3.2c0-1.28.64-2.56 2.56-2.56h2.56V1.28H19.2c-3.84 0-7.04 2.56-7.04 7.04v3.84H7.68v5.12h4.48v14.08h6.4z"/></svg>
</code>```

I would like to modify the properties of the "icon-facebook" class. Normally, this class would be defined in the theme.scss.liquid file (which I though is where all the classes are defined, I have been able to change properties of other classes in that file) however, the "icon-facebook" class is not there. Is there another file where the class could be defined? I have looked everywhere but have not found it.
Thank you.

答:
You can just style it in your main project file.because styling in the project file also adds the styles as from the external files.
And then you will have all the styles added to your class icon-facebook from both the files.

Body:
I am working on a shopify store and I want to change the properties of a class. Please see the code below:

<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-facebook" viewBox="0 0 32 32"><path fill="#444" d="M18.56 31.36V17.28h4.48l.64-5.12h-5.12v-3.2c0-1.28.64-2.56 2.56-2.56h2.56V1.28H19.2c-3.84 0-7.04 2.56-7.04 7.04v3.84H7.68v5.12h4.48v14.08h6.4z"/></svg>

I would like to modify the properties of the "icon-facebook" class. Normally, this class would be defined in the theme.scss.liquid file (which I though is where all the classes are defined, I have been able to change properties of other classes in that file) however, the "icon-facebook" class is not there. Is there another file where the class could be defined? I have looked everywhere but have not found it.
Thank you.


问:
Why Method Overriding is runtime bound
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

```<code>//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}
</code>```

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

答:
Consider this snippet.

```<code>test Create()
{
    return new test2();
}

test a = Create();
a.getStuff(0); // which method is called?
</code>```

The compiler can't know that the return value of the Create method is of type test2. It's explicitly hidden.

You should look at this from the compiler's point-of-view. Given that the compiler is looking at the value as if it was of type test how could it know to call the test2.getStuff method?

ContentLicense: CC BY-SA 3.0

Title: Why Method Overriding is runtime bound

Body:
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

Body:
Consider this snippet.

test Create()
{
    return new test2();
}

test a = Create();
a.getStuff(0); // which method is called?

The compiler can't know that the return value of the Create method is of type test2. It's explicitly hidden.

You should look at this from the compiler's point-of-view. Given that the compiler is looking at the value as if it was of type test how could it know to call the test2.getStuff method?


问:
Pandas, merge multiple CSV's into one and clean strings
I am having some issues using pandas to manipulate some files into the right format.

I have multiple CSV's that I want to merge into one file.

They all have this sort of structure,

```<code>  data1, data2 etc
</code>```

And then with the key values, which are area (ideally want to rename column there), any arearea that has two words in it has looks like this, [![enter image description here][2]][2] , with "%20" instead of a space, and I'd want to remove that %20 ideally.

And lastly, I want to have the arearea have their respective long and lats from this file here,

If anyone has some pointers on achieving this, that would be amazing, I'm stuck using df.merge, and keep receiving errors. So close to achieving getting it complete!

答:
You can use pd.concat (pandas documentation). As for string cleaning, you can apply a lambda function after the fact. Here's an example:

```<code>df1 = pd.read_csv('file1.csv')
df1

    a   b   c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat%20dog

df2 = pd.read_csv('file2.csv')
df2

    a   b   c
0   7   8   bus
1   9   10  boat
2   11  12  ferry%20plane

# use pd.concat
df = pd.concat([df1, df2]).reset_index(drop=True)
df

    a   b   c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat%20dog
3   7   8   bus
4   9   10  boat
5   11  12  ferry%20plane

# apply lambda to clean the %20
f = lambda s: s.replace('%20', ' ')
df['clean_c'] = df['c'].apply(f)

df[['a', 'b', 'clean_c']]

    a   b   clean_c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat dog
3   7   8   bus
4   9   10  boat
5   11  12  ferry plane
</code>```

Body:
I am having some issues using pandas to manipulate some files into the right format.

I have multiple CSV's that I want to merge into one file.

They all have this sort of structure,

  data1, data2 etc

And then with the key values, which are area (ideally want to rename column there), any arearea that has two words in it has looks like this, [![enter image description here][2]][2] , with "%20" instead of a space, and I'd want to remove that %20 ideally.

And lastly, I want to have the arearea have their respective long and lats from this file here,

If anyone has some pointers on achieving this, that would be amazing, I'm stuck using df.merge, and keep receiving errors. So close to achieving getting it complete!

Body:
You can use pd.concat (pandas documentation). As for string cleaning, you can apply a lambda function after the fact. Here's an example:

df1 = pd.read_csv('file1.csv')
df1

    a   b   c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat%20dog

df2 = pd.read_csv('file2.csv')
df2

    a   b   c
0   7   8   bus
1   9   10  boat
2   11  12  ferry%20plane

# use pd.concat
df = pd.concat([df1, df2]).reset_index(drop=True)
df

    a   b   c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat%20dog
3   7   8   bus
4   9   10  boat
5   11  12  ferry%20plane

# apply lambda to clean the %20
f = lambda s: s.replace('%20', ' ')
df['clean_c'] = df['c'].apply(f)

df[['a', 'b', 'clean_c']]

    a   b   clean_c
0   1   2   aardvark
1   3   4   pangolin
2   5   6   cat dog
3   7   8   bus
4   9   10  boat
5   11  12  ferry plane


问:
How to add profile picture on django
I have been trying to add a profile picture to users but the file seems to be "unknown" so I think the error is on the profile.html but I dont know how to fix it.

views.py

```<code>    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)
        user_posts = Profile.objects.filter(user_id=post_owner)
      else:
        post_owner = request.user
        user_posts = Profile.objects.filter(user=request.user)
      args1 = {
        'post_owner': post_owner,
        'user_posts': user_posts,
      }
      return render(request, 'profile.html', args1)
</code>```

models.py

```<code>    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank="True", default="default.png")

      def __str__(self):
        return f'{self.user.username} Profile'
</code>```

profile.hmtl

```<code>    <h2 class="account-heading">{{ post_owner.username }}</h2>
    <img class="account-img" src="{{ user.profile.profile_pics.url }}" style="max-width: 300px; max-height: 300px;margin-left: 15px;margin-right:15px;">
    <h2 class="account-heading">{{ post_owner.first_name }}</h2>
</code>```

btw I have pillow installed, but I will add the settings.py and urls.y so that you van see it:)

views.py

```<code>    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

urls.py

```<code>   from django.conf import settings
   from django.conf.urls.static import static

   urlpatterns = [
     path('', include('home.urls')),
     path('admin/', admin.site.urls),
     path('accounts/', include('accounts.urls')),
   ]
   urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
You define field as profile_pic but you try to reach profile_pics in your html file. Change the src attribute of img element like this:

src="{{ user.profile.profile_pic.url }}"
```

Title: How to add profile picture on django

Body:
I have been trying to add a profile picture to users but the file seems to be "unknown" so I think the error is on the profile.html but I dont know how to fix it.

views.py

    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)
        user_posts = Profile.objects.filter(user_id=post_owner)
      else:
        post_owner = request.user
        user_posts = Profile.objects.filter(user=request.user)
      args1 = {
        'post_owner': post_owner,
        'user_posts': user_posts,
      }
      return render(request, 'profile.html', args1)

models.py

    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank="True", default="default.png")

      def __str__(self):
        return f'{self.user.username} Profile'

profile.hmtl

{{ post_owner.username }}

{{ post_owner.first_name }}

btw I have pillow installed, but I will add the settings.py and urls.y so that you van see it:)

views.py

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

   from django.conf import settings
   from django.conf.urls.static import static

   urlpatterns = [
     path('', include('home.urls')),
     path('admin/', admin.site.urls),
     path('accounts/', include('accounts.urls')),
   ]
   urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


问:
AWS -- how can I tell what is using a service-linked role?
In my AWS console (IAM -> Access Management -> Roles), I noticed a service-linked role among the list of all the roles.

How do I determine what AWS resources can assume this service-linked role. I'm asking because I'm auditing a system and trying to get a handle on what permissions may be in use elsewhere.  Someone (don't know who) created it for a reason.  I'd like to figure out why.

How can I tell what is using this service-linked role?

答:
Service Linked roles are by-design used by one particular AWS service.
In the AWS Management Console for the IAM service, you can click on a role and view the "Summary". The summary contains a path attribute which looks like the following: /aws-service-role/access-analyzer.amazonaws.com/.

In this example you can see that the service which uses this role is called  Access Analyzer.

You can get information on the Service-Linked role for that particular service in the docs. [1]

Navigate to section "Security, Identity, and Compliance Services" -> search for row "IAM Access Analyzer" and click on the link Yes in the "Service-linked roles" column of the table. The linked docs usually tell you why AWS sets up this particulal service linked role and which permissions it includes.

General information about service linked roles is given by the IAM docs on "Service-Linked Roles" [2] and the IAM "Troubleshooting" guide [3].

If you want to know when a particular service linked role was last used in your account, use the Access Analyzer [4].

There are currently 3 posts on the topic service linked roles from the AWS official blog [5]. Two of them are probably related to your question:

The blog post "Greater Transparency into Actions AWS Services Perform on Your Behalf by Using AWS CloudTrail
" [6] goes into detail how to monitor the actions which are performed by the role. This is the procedure also suggested by @jellycsc's answer I guess.

Excerpt from the blog post [6]:

In this blog post, I demonstrate how to view CloudTrail logs so that you can more easily monitor and audit AWS services performing actions on your behalf. First, I show how AWS creates a service-linked role in your account automatically when you configure an AWS service that supports service-linked roles. Next, I show how you can view the policies of a service-linked role that grants an AWS service permission to perform actions on your behalf. Finally, I use the configured AWS service to perform an action and show you how the action appears in your CloudTrail logs.

The blog post "Now Use AWS IAM to Delete a Service-Linked Role When You No Longer Require an AWS Service to Perform Actions on Your Behalf" [7] makes the following statement:

When you delete a service-linked role, the linked service no longer has the permissions to perform actions on your behalf. To ensure your AWS services continue to function as expected when you delete a service-linked role, IAM validates that you no longer have resources that require the service-linked role to function properly. This prevents you from inadvertently revoking permissions required by an AWS service to manage your existing AWS resources and helps you maintain your resources in a consistent state. If there are any resources in your account that require the service-linked role, you will receive an error when you attempt to delete the service-linked role, and the service-linked role will remain in your account. If you do not have any resources that require the service-linked role, you can delete the service-linked role and IAM will remove the service-linked role from your account.

References

[1] https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html#admin_svcs

[2] https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#create-service-linked-role

[3] https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_new-role-appeared

[4] https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html?icmpid=docs_iam_console

[5] https://aws.amazon.com/de/blogs/security/tag/service-linked-roles/

[6] https://aws.amazon.com/de/blogs/security/get-greater-transparency-into-actions-aws-services-perform-on-your-behalf-by-using-aws-cloudtrail/

[7] https://aws.amazon.com/de/blogs/security/now-use-aws-iam-to-delete-a-service-linked-role-when-you-no-longer-require-an-aws-service-to-perform-actions-on-your-behalf/


问:
Struggle with UINavigationController
I was struggle with UINavigationController for many hours since it refused to show any title or even titleView, BackItem?.title, everything not work. I can see navigation bar on top, just blank. Here my codes:</p>

```<code>class tab1_main: UIViewController {
    var main_nav_controller = UINavigationController()
    override func viewDidLoad() {
        main_nav_controller.navigationBar.backItem?.title = "Hello" //NO LUCK
        main_nav_controller.navigationBar.topItem?.title = "Hello" //NO LUCK
        main_nav_controller.title = "Hello" //NO LUCK
        self.title = "Hello" //NO LUCK
        navigationItem.title = "Hello" //NO LUCK

        view.addSubview(main_nav_controller.view)
        tab1_startup()
    }
}
</code>```

答:
Here you go. :) I Hope it helps.  </p>

```<code>// Set up the title
self.navigationItem.title = "Title"
/// if you want to use large title then set true to use large title into small title if scroll down.
self.navigationController?.navigationBar.prefersLargeTitles = true
</code>```

Title: Struggle with UINavigationController

Body:
I was struggle with UINavigationController for many hours since it refused to show any title or even titleView, BackItem?.title, everything not work. I can see navigation bar on top, just blank. Here my codes:

class tab1_main: UIViewController {
    var main_nav_controller = UINavigationController()
    override func viewDidLoad() {
        main_nav_controller.navigationBar.backItem?.title = "Hello" //NO LUCK
        main_nav_controller.navigationBar.topItem?.title = "Hello" //NO LUCK
        main_nav_controller.title = "Hello" //NO LUCK
        self.title = "Hello" //NO LUCK
        navigationItem.title = "Hello" //NO LUCK

        view.addSubview(main_nav_controller.view)
        tab1_startup()
    }
}

Body:
Here you go. :) I Hope it helps.

// Set up the title
self.navigationItem.title = "Title"
/// if you want to use large title then set true to use large title into small title if scroll down.
self.navigationController?.navigationBar.prefersLargeTitles = true


问:
Not able to run a simple GET method XHR/AJAX javascript program
```<code>    document.querySelector("#btn").addEventListener("click",loadData);

    function loadData(){
    const xhr = new XMLHttpRequest();

    console.log("READYSTAT",xhr.readyState)

    xhr.open("GET","trial.txt", true)

    xhr.onload = function(){
        if(this.status === 200){
            console.log(this.responseText)
        }
    }
</code>```

This is the error

Access to XMLHttpRequest at
  'file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt' from
  origin 'null' has been blocked by CORS policy: Cross origin requests
  are only supported for protocol schemes: http, data, chrome,
  chrome-extension, https.

```<code>    xhr.send();
}
</code>```

答:
XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. source

XMLHttpRequest (XHR) objects are used to interact with servers. source

from this

```<code>file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt
</code>```

I am pretty sure that the URL in your browser is something like this
file:///C:/Users/kenne/OneDrive/Desktop/javascript/index.html

So the requested URL trial.txt will request to file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt, obviously, there is no server here

Run a local HTTP server using python

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
```

Body:
    document.querySelector("#btn").addEventListener("click",loadData);

    function loadData(){
    const xhr = new XMLHttpRequest();

    console.log("READYSTAT",xhr.readyState)

    xhr.open("GET","trial.txt", true)

    xhr.onload = function(){
        if(this.status === 200){
            console.log(this.responseText)
        }
    }

This is the error

Access to XMLHttpRequest at
  'file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt' from
  origin 'null' has been blocked by CORS policy: Cross origin requests
  are only supported for protocol schemes: http, data, chrome,
  chrome-extension, https.

    xhr.send();
}

Body:
XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. source

XMLHttpRequest (XHR) objects are used to interact with servers. source

from this

file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt

I am pretty sure that the URL in your browser is something like this
file:///C:/Users/kenne/OneDrive/Desktop/javascript/index.html

So the requested URL trial.txt will request to file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt, obviously, there is no server here

Run a local HTTP server using python

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...


问:
how to get words from string without SPLIT in c#
I'm stack with a task which ask for "read from console" (C#) a text (string) and get words separated by spaces.

for example: phrase=**"i love this world love"** BUT I need to try this WITHOUT methods or functions like SPLIT or REGEX or similar.

I need to compare 2 words and I dont know how to catch 'em in separated word1 word2 fullphrase.

What i want is word1="this" word2= "world" AND CHECK if there are 2 words REPEATED

```<code>string frase, palabra1="",pal2="";
bool si = false;
Console.WriteLine("Entra frase");
frase = Console.ReadLine();
int j = 0;
for (int i = 0; i < frase.Length; i++)
    {
      if (frase[i] != ' ')
         {
           palabra1 += frase[i];
           if (pal2 == palabra1) si = true;
         }
      else
         {
          pal2 = palabra1;
          palabra1 = "";
         }
    }
if (si == true) Console.WriteLine($" SI HAY palabras seguidamente
repetidas ");
else Console.WriteLine($"NO HAY PALABRAS REPETIDAS AQUI");
</code>```

答:
If you can't use any functions(split, regex, indexOf, etc), then what you should do is loop through each character of the text, and push the currently processed segment into your word list when you reach a (white)space.</p>

```<code>String testString = "This is  a test   string  ";
ArrayList words = new ArrayList();
string currentWord = "";

foreach(char c in testString)
{
    if(Char.IsWhiteSpace(c))
    {
        if(currentWord.Length > 0)
        {
            words.Add(currentWord);
            currentWord = "";
        }
    }
    else
    {
        currentWord+=c;
    }
}
</code>```

Body:
I'm stack with a task which ask for "read from console" (C#) a text (string) and get words separated by spaces.

for example: phrase=**"i love this world love"** BUT I need to try this WITHOUT methods or functions like SPLIT or REGEX or similar.

I need to compare 2 words and I dont know how to catch 'em in separated word1 word2 fullphrase.

What i want is word1="this" word2= "world" AND CHECK if there are 2 words REPEATED

string frase, palabra1="",pal2="";
bool si = false;
Console.WriteLine("Entra frase");
frase = Console.ReadLine();
int j = 0;
for (int i = 0; i < frase.Length; i++)
    {
      if (frase[i] != ' ')
         {
           palabra1 += frase[i];
           if (pal2 == palabra1) si = true;
         }
      else
         {
          pal2 = palabra1;
          palabra1 = "";
         }
    }
if (si == true) Console.WriteLine($" SI HAY palabras seguidamente
repetidas ");
else Console.WriteLine($"NO HAY PALABRAS REPETIDAS AQUI");

Body:
If you can't use any functions(split, regex, indexOf, etc), then what you should do is loop through each character of the text, and push the currently processed segment into your word list when you reach a (white)space.

String testString = "This is  a test   string  ";
ArrayList words = new ArrayList();
string currentWord = "";

foreach(char c in testString)
{
    if(Char.IsWhiteSpace(c))
    {
        if(currentWord.Length > 0)
        {
            words.Add(currentWord);
            currentWord = "";
        }
    }
    else
    {
        currentWord+=c;
    }
}


问:
Position absolute keeps pushing objects outside of the frame
Sorry, beginner in programming. but I am having an issue with some code.

I am trying to add a white background in the back of the text I, but there's a lot of empty white space in it. This: example 1

What i am trying to make is this: example 2

So, my approach for this is putting the paragraph in a div, and giving it the following code:

```<code>.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}
</code>```

and the tittle to have its background white, position absolute and margin big enough that it will go under the text, giving it the feeling like its same pannel.
But the tittle goes automatically on top of the page.

Why's this happening?

Here's an example of the code for the block:

```<code><h2>The problem</h2>
<div class="i_box">
<p>test test test </p>
</div>
</code>```

any suggestion please?
can't seem to figure this out

答:
So I'm not entirely sure what you want but I created something similar to what you asked for in image 2.
Here is a snippet:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    size: relative;

}
.title-thing{
   display: inline-block;
  background-color: rgb(245, 244, 244);
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 7px 7px 0px 0px;
}
.title-thing-parent{
  text-align: center;
  /*
  to center .title-thing, added display: inline-block to .title-thing so it can work.
  */
}
body{
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

<div class = "title-thing-parent">
<div class = "title-thing">
<h2 >The problem</h2>
</div>
</div>
<div class="i_box">
<p>test test test </p>
</div>

</body></code>```

Added the display: inline-block to the title and surrounded it in another div so it can be centered.

Body:
Sorry, beginner in programming. but I am having an issue with some code.

I am trying to add a white background in the back of the text I, but there's a lot of empty white space in it. This: example 1

What i am trying to make is this: example 2

So, my approach for this is putting the paragraph in a div, and giving it the following code:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}

and the tittle to have its background white, position absolute and margin big enough that it will go under the text, giving it the feeling like its same pannel.
But the tittle goes automatically on top of the page.

Why's this happening?

Here's an example of the code for the block:

The problem

test test test

any suggestion please?
can't seem to figure this out

Body:
So I'm not entirely sure what you want but I created something similar to what you asked for in image 2.
Here is a snippet:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    size: relative;

}
.title-thing{
   display: inline-block;
  background-color: rgb(245, 244, 244);
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 7px 7px 0px 0px;
}
.title-thing-parent{
  text-align: center;
  /*
  to center .title-thing, added display: inline-block to .title-thing so it can work.
  */
}
body{
  background-color: blue;
}

<body>

<div class = "title-thing-parent">
<div class = "title-thing">
<h2 >The problem</h2>
</div>
</div>
<div class="i_box">
<p>test test test </p>
</div>

</body>

Added the display: inline-block to the title and surrounded it in another div so it can be centered.


问:
Rails Admin render exceptionally slow in production
I am running Rails Admin, with Rails API in production with docker. For some reason, the rendering is extremely slow. A simple page load takes 15 seconds, it seems the rendering of the layouts which is taking an exceptionally long time.

Am I forgetting to compile assets somewhere in the docker build process, that is causing this?

```<code>User Load (18.8ms)  SELECT "users".* FROM "users" ORDER BY users.id desc LIMIT $1 OFFSET $2  [["LIMIT", 20], ["OFFSET", 0]]
    (20.8ms)  SELECT COUNT(*) FROM "users"
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/rails_admin/main/index.html.haml within layouts/rails_admin/application (Duration: 1559.2ms | Allocations: 49878)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_head.html.haml (Duration: 0.5ms | Allocations: 190)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_secondary_navigation.html.haml (Duration: 0.5ms | Allocations: 269)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_navigation.html.haml (Duration: 3.2ms | Allocations: 469)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_sidebar_navigation.html.haml (Duration: 35.2ms | Allocations: 17042)
    Rendering /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/pjax.html.haml
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/pjax.html.haml (Duration: 12.1ms | Allocations: 1683)
    Completed 200 OK in 2302ms (Views: 1590.1ms | ActiveRecord: 120.6ms | Allocations: 77826)
</code>```

答:
According to this issue on Github, you could try disabling statistics like so

RailsAdmin.config do |c|
  c.actions do
    dashboard do
      statistics false
    end
  end
end
```

Full documentation of this is here.

Body:
I am running Rails Admin, with Rails API in production with docker. For some reason, the rendering is extremely slow. A simple page load takes 15 seconds, it seems the rendering of the layouts which is taking an exceptionally long time.

Am I forgetting to compile assets somewhere in the docker build process, that is causing this?

User Load (18.8ms)  SELECT "users".* FROM "users" ORDER BY users.id desc LIMIT $1 OFFSET $2  [["LIMIT", 20], ["OFFSET", 0]]
    (20.8ms)  SELECT COUNT(*) FROM "users"
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/rails_admin/main/index.html.haml within layouts/rails_admin/application (Duration: 1559.2ms | Allocations: 49878)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_head.html.haml (Duration: 0.5ms | Allocations: 190)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_secondary_navigation.html.haml (Duration: 0.5ms | Allocations: 269)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_navigation.html.haml (Duration: 3.2ms | Allocations: 469)
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/_sidebar_navigation.html.haml (Duration: 35.2ms | Allocations: 17042)
    Rendering /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/pjax.html.haml
    Rendered /usr/local/bundle/gems/rails_admin-2.0.2views/layouts/rails_admin/pjax.html.haml (Duration: 12.1ms | Allocations: 1683)
    Completed 200 OK in 2302ms (Views: 1590.1ms | ActiveRecord: 120.6ms | Allocations: 77826)

Body:
According to this issue on Github, you could try disabling statistics like so

RailsAdmin.config do |c|
  c.actions do
    dashboard do
      statistics false
    end
  end
end

Full documentation of this is here.


问:
EventListener(ended) firing more than once
I am trying to make a music-app, so what I want to do is when the current music ends, it will automatically plays the next song in line, but what happens is, the EventListener get triggered by times 2, firstly it is triggered one time, and then 2 time, and then 4, and the number keeps increasing every time the EventListener gets triggered, I've tried searching for solutions in other websites but I just can't seem to find the answer, hope anyone can help

By the way I am using vue js

these are my data

```<code>data () {
return {
  current: {},
  index: 0,
  isPlaying: false,
  api_key: '4f40bf40b2msh6d957020229b6c6p1fe925jsn4ef16ee46284',
  url_base: 'https://deezerdevs-deezer.p.rapidapi.com',
  songs: [],
  query:'',
  player: new Audio()
}
},
</code>```

and this is my method for playing the music

```<code>play (song) {
  if (typeof song.title != "undefined") {
    this.current = song;
    this.player.src = this.current.preview;
  }

  this.player.play();
  //console.log(this.player);
  this.player.addEventListener('ended', function () {
    console.log(this.index);
    //this.index++;
    if (this.index > this.songs.length - 1) {
      this.index = 0;
    }
    this.current = this.songs[this.index];
    this.play(this.current);
  }.bind(this));

  this.isPlaying = true;
},
</code>```

if anyone has better suggestion for me to make this will also be a huge favour

答:
The problem is that each time your play method gets called, a new event listener gets added. Then, whenever a song ends, all of the previously added listeners get called.

(You seem to be under the impression that the listener gets retired after being called. This is not the case; they stick around until you remove them.)

You should move the addEventListener call from out of your play method, and put it somewhere else. E.g. you could do it in the constructor of your class, or in the outer-most scope.

Body:
I am trying to make a music-app, so what I want to do is when the current music ends, it will automatically plays the next song in line, but what happens is, the EventListener get triggered by times 2, firstly it is triggered one time, and then 2 time, and then 4, and the number keeps increasing every time the EventListener gets triggered, I've tried searching for solutions in other websites but I just can't seem to find the answer, hope anyone can help

By the way I am using vue js

these are my data

data () {
return {
  current: {},
  index: 0,
  isPlaying: false,
  api_key: '4f40bf40b2msh6d957020229b6c6p1fe925jsn4ef16ee46284',
  url_base: 'https://deezerdevs-deezer.p.rapidapi.com',
  songs: [],
  query:'',
  player: new Audio()
}
},

and this is my method for playing the music

play (song) {
  if (typeof song.title != "undefined") {
    this.current = song;
    this.player.src = this.current.preview;
  }

  this.player.play();
  //console.log(this.player);
  this.player.addEventListener('ended', function () {
    console.log(this.index);
    //this.index++;
    if (this.index > this.songs.length - 1) {
      this.index = 0;
    }
    this.current = this.songs[this.index];
    this.play(this.current);
  }.bind(this));

  this.isPlaying = true;
},

if anyone has better suggestion for me to make this will also be a huge favour


问:
How to divide incoming rows of data to be executed by CodeIgniter's update_batch() and insert_batch()?
My objective is to use a combination of CodeIgniter's insert_batch() and update_batch() to add incoming data to my macro_plan table.

In my script below I am attempting to query the database for existing rows based on sr_no values then appropriately call the batch querying methods.

```<code>function insert_batch($dataSet)
{
    $query = $this->db->query("select sr_no from macro_plan");
    $data = $query->result_array();
    $sr_nos=array();

    foreach($data as $key => $value):
        $sr_nos[$key]=$value['sr_no'];
    endforeach;

    $query1= $this->db->query("select * from macro_plan WHERE sr_no IN ('".$sr_nos."')");
    $update_query = $query1->result();
    if ($update_query->num_rows() > 0) {

        $this->db->update_batch($dataSet,$this->macro_plan);//update if ids exist
    } else {
        $this->db->insert_batch($dataSet,$this->macro_plan);//insert if does not exist
    }
}
</code>```

However, I am getting the "array to string conversion" error.

$dataset will resemble this:

```<code>Array (
    [0] => Array (
        [quantity_update] => 88
        [sr_no] => 2020-11-1
        [batch] => Batch 2
        [quantity_date_update] => 05-May-20
        [inq_id] => 49
    )
    [1] => Array (
        [quantity_update] => 99
        [sr_no] => 2020-11-2
        [batch] => Batch 1
        [quantity_date_update] => 11-May-20
        [inq_id] => 49
    )
)
</code>```

My table structure looks like this:

答:
Query your table for pre-existing rows that contain the sr_no values that exist in your $dataSet.

Then apply keys to the result set rows from the sr_no values -- this allows the swift lookup on new data against the old data (to see if the respective new rows should be inserted, executed as an update, or completely ignored because the data is the same.

Untested Suggestion:

```<code>function insertUpdateMacroPlan($dataSet)
{
    $keyedExistingRows = array_column(
        $this->db
            ->where_in('sr_no', array_column($dataSet, 'sr_no'))
            ->get('macro_plan')
            ->result_array(),
        null,
        'sr_no'
    );

    foreach ($dataSet as $data) {
        if (isset($keyedExistingRows[$data['sr_no']])) {
            // sr_no exists in the db, add known id to new data array
            $identified = ['id' => $keyedExistingRows[$data['sr_no']]['id']] + $data;

            if ($identified != $keyedExistingRows[$data['sr_no']]) {
                $updateBatch[] = $identified;
            }
            // if the arrays contain the same data, the new data will be discarded
        } else {
            $insertBatch[] = $data;
        }
    }

    if (!empty($insertBatch)) {
        $this->db->insert_batch('macro_plan', $insertBatch);
    }
    if (!empty($updateBatch)) {
        $this->db->update_batch('macro_plan', $updateBatch, 'id');
    }
}
</code>```

p.s. if your business logic requires that sr_no values are unique, I recommend that you reflect that in your table configuration by setting the sr_no column as a Unique Key.

Body:
My objective is to use a combination of CodeIgniter's insert_batch() and update_batch() to add incoming data to my macro_plan table.

In my script below I am attempting to query the database for existing rows based on sr_no values then appropriately call the batch querying methods.

function insert_batch($dataSet)
{
    $query = $this->db->query("select sr_no from macro_plan");
    $data = $query->result_array();
    $sr_nos=array();

    foreach($data as $key => $value):
        $sr_nos[$key]=$value['sr_no'];
    endforeach;

    $query1= $this->db->query("select * from macro_plan WHERE sr_no IN ('".$sr_nos."')");
    $update_query = $query1->result();
    if ($update_query->num_rows() > 0) {

        $this->db->update_batch($dataSet,$this->macro_plan);//update if ids exist
    } else {
        $this->db->insert_batch($dataSet,$this->macro_plan);//insert if does not exist
    }
}

However, I am getting the "array to string conversion" error.

$dataset will resemble this:

Array (
    [0] => Array (
        [quantity_update] => 88
        [sr_no] => 2020-11-1
        [batch] => Batch 2
        [quantity_date_update] => 05-May-20
        [inq_id] => 49
    )
    [1] => Array (
        [quantity_update] => 99
        [sr_no] => 2020-11-2
        [batch] => Batch 1
        [quantity_date_update] => 11-May-20
        [inq_id] => 49
    )
)

My table structure looks like this:

Body:
Query your table for pre-existing rows that contain the sr_no values that exist in your $dataSet.

Then apply keys to the result set rows from the sr_no values -- this allows the swift lookup on new data against the old data (to see if the respective new rows should be inserted, executed as an update, or completely ignored because the data is the same.

Untested Suggestion:

function insertUpdateMacroPlan($dataSet)
{
    $keyedExistingRows = array_column(
        $this->db
            ->where_in('sr_no', array_column($dataSet, 'sr_no'))
            ->get('macro_plan')
            ->result_array(),
        null,
        'sr_no'
    );

    foreach ($dataSet as $data) {
        if (isset($keyedExistingRows[$data['sr_no']])) {
            // sr_no exists in the db, add known id to new data array
            $identified = ['id' => $keyedExistingRows[$data['sr_no']]['id']] + $data;

            if ($identified != $keyedExistingRows[$data['sr_no']]) {
                $updateBatch[] = $identified;
            }
            // if the arrays contain the same data, the new data will be discarded
        } else {
            $insertBatch[] = $data;
        }
    }

    if (!empty($insertBatch)) {
        $this->db->insert_batch('macro_plan', $insertBatch);
    }
    if (!empty($updateBatch)) {
        $this->db->update_batch('macro_plan', $updateBatch, 'id');
    }
}

p.s. if your business logic requires that sr_no values are unique, I recommend that you reflect that in your table configuration by setting the sr_no column as a Unique Key.


答:
Probably the most simple way is to make your h2 have display: inline-block Look what I did here in an example:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}

body {
  background: yellow;
}

h2 {
  background: white;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>The problem</h2>
<div class="i_box">
<p>test test test </p>
</div></code>```

Title: Position absolute keeps pushing objects outside of the frame

Body:
Probably the most simple way is to make your h2 have display: inline-block Look what I did here in an example:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}

body {
  background: yellow;
}

h2 {
  background: white;
  display: inline-block;
}

<h2>The problem</h2>
<div class="i_box">
<p>test test test </p>
</div>


问:
Matplotlib: how to make the background transparent on Windows
I need the whole plot window to be transparent so that a chrome window, for example, on my desktop could be seen through the plot, so that I can add points to it while seeing what's behind it.

https://stackoverflow.com/a/45505906/13650485

The answer I've listed above is EXACTLY what I want to do, except my interactive system doesn't work with TK.  I'd like to use Qt5Agg.  When I run the code above, the system won't accept it -- it says QT5 is currently running.  If I run it without QT already loaded, it creates a blank transparent window (yay!) but if I move it or click on the icon it turns opaque black without any plot. If I change tk to Qt5 it complains on lift.  If I remove the "win" code, it has no transparency(obviously).  I've tried adding everything I can think of to make the canvas transparent and I can change the color but not make it transparent.

```<code>
import matplotlib
# make sure Tk backend is used
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

# create a figure and some subplots
fig, ax = plt.subplots(figsize=(4,2))
ax.plot([2,3,5,1])
fig.tight_layout()

win = plt.gcf().canvas.manager.window

win.lift()
win.attributes("-topmost", True)
win.attributes("-transparentcolor", "white")

plt.show()

</code>```

When I made the changes suggested by: eyllanesc

I found within a vanilla Spyder 4.1.3 | Python 3.7.7 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10

In order to import QtCore I had to first

conda install pyqt

not enough, so then conda install pyqt5

and also conda update --all

When I did that, the code ran without errors. This is a better first result!, but I still only get the frozen mpl.fig window.  This time, however, it is white. . .  The console returns, but the mpl window hangs.  Run again, a new frozen window.  Restart and run again: same result.

I hope that this is a simple error; please teach this newby.

@eyllanesc

Revised: Python screen tracing application – needs a mostly transparent plot window.
I need the whole plot window to be transparent so that a chrome window, for example, on my desktop could be seen through the plot, so that I can add plot (x, y) points to it while seeing what's behind it.

Adding the command win.setWindowFlags(QtCore.Qt.FramelessWindowHint) did indeed make the window transparent, but it made the tool bar transparent, got rid of the title bar, and removed the ability to move or resize the window.  It also made it so that the graph area was not sensitive to the mouse unless I was over the line.  I added the facecolor attribute to the subplots command so I could see what was going on.   As long as I put a non-zero value for either the fig-alpha or the ax-alpha, the graph is sensitive to the mouse over the whole area.

I need to be able to move and resize the window and would like to have the toolbar be opaque or at least sensitive to the mouse over the whole toolbar.  Can you help with this?  Thanks for past help!

```<code>## Python Code Fragment by Helen for Windows 10
## to test sequence creating plot with transparent
## background (to be used to trace and record xy pairs)

from PyQt5 import QtCore
import matplotlib
matplotlib.use("Qt5Agg")  #define backend, must be before pyplot is imported
import matplotlib.pyplot as plt

# create a figure and a subplot
fig,ax = plt.subplots(figsize=(4, 2),facecolor=(1.,1.,0.,0.1)) #facecolor of figure

fig.patch.set_alpha(0.1)
ax.patch.set_alpha(0.1)

# plot some fixed points
ax.plot([2, 3, 5, 1])
fig.tight_layout()

#make window transparent to the desktop
win = plt.gcf().canvas.manager.window
win.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
win.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
win.setStyleSheet("background:transparent")
win.setWindowFlags(QtCore.Qt.FramelessWindowHint)
win.setWindowTitle("My App")

plt.show()
</code>```

答:
You have to use the Qt flags, tested on Linux:

```<code>from PyQt5 import QtCore

import matplotlib

# make sure Tk backend is used
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt

# create a figure and some subplots
fig, ax = plt.subplots(figsize=(4, 2))
fig.patch.set_alpha(0.0)
ax.patch.set_alpha(0.0)

ax.plot([2, 3, 5, 1])
fig.tight_layout()

win = plt.gcf().canvas.manager.window
win.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
win.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
win.setStyleSheet("background:transparent")

plt.show()
</code>```

Body:
I need the whole plot window to be transparent so that a chrome window, for example, on my desktop could be seen through the plot, so that I can add points to it while seeing what's behind it.

https://stackoverflow.com/a/45505906/13650485

The answer I've listed above is EXACTLY what I want to do, except my interactive system doesn't work with TK.  I'd like to use Qt5Agg.  When I run the code above, the system won't accept it -- it says QT5 is currently running.  If I run it without QT already loaded, it creates a blank transparent window (yay!) but if I move it or click on the icon it turns opaque black without any plot. If I change tk to Qt5 it complains on lift.  If I remove the "win" code, it has no transparency(obviously).  I've tried adding everything I can think of to make the canvas transparent and I can change the color but not make it transparent.

import matplotlib
# make sure Tk backend is used
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

# create a figure and some subplots
fig, ax = plt.subplots(figsize=(4,2))
ax.plot([2,3,5,1])
fig.tight_layout()

win = plt.gcf().canvas.manager.window

win.lift()
win.attributes("-topmost", True)
win.attributes("-transparentcolor", "white")

plt.show()

When I made the changes suggested by: eyllanesc

I found within a vanilla Spyder 4.1.3 | Python 3.7.7 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10

In order to import QtCore I had to first

conda install pyqt

not enough, so then conda install pyqt5

and also conda update --all

When I did that, the code ran without errors. This is a better first result!, but I still only get the frozen mpl.fig window.  This time, however, it is white. . .  The console returns, but the mpl window hangs.  Run again, a new frozen window.  Restart and run again: same result.

I hope that this is a simple error; please teach this newby.

@eyllanesc

Revised: Python screen tracing application – needs a mostly transparent plot window.
I need the whole plot window to be transparent so that a chrome window, for example, on my desktop could be seen through the plot, so that I can add plot (x, y) points to it while seeing what's behind it.

Adding the command win.setWindowFlags(QtCore.Qt.FramelessWindowHint) did indeed make the window transparent, but it made the tool bar transparent, got rid of the title bar, and removed the ability to move or resize the window.  It also made it so that the graph area was not sensitive to the mouse unless I was over the line.  I added the facecolor attribute to the subplots command so I could see what was going on.   As long as I put a non-zero value for either the fig-alpha or the ax-alpha, the graph is sensitive to the mouse over the whole area.

I need to be able to move and resize the window and would like to have the toolbar be opaque or at least sensitive to the mouse over the whole toolbar.  Can you help with this?  Thanks for past help!

## Python Code Fragment by Helen for Windows 10
## to test sequence creating plot with transparent
## background (to be used to trace and record xy pairs)

from PyQt5 import QtCore
import matplotlib
matplotlib.use("Qt5Agg")  #define backend, must be before pyplot is imported
import matplotlib.pyplot as plt

# create a figure and a subplot
fig,ax = plt.subplots(figsize=(4, 2),facecolor=(1.,1.,0.,0.1)) #facecolor of figure

fig.patch.set_alpha(0.1)
ax.patch.set_alpha(0.1)

# plot some fixed points
ax.plot([2, 3, 5, 1])
fig.tight_layout()

#make window transparent to the desktop
win = plt.gcf().canvas.manager.window
win.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
win.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
win.setStyleSheet("background:transparent")
win.setWindowFlags(QtCore.Qt.FramelessWindowHint)
win.setWindowTitle("My App")

plt.show()

Body:
You have to use the Qt flags, tested on Linux:

from PyQt5 import QtCore

import matplotlib

# make sure Tk backend is used
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt

# create a figure and some subplots
fig, ax = plt.subplots(figsize=(4, 2))
fig.patch.set_alpha(0.0)
ax.patch.set_alpha(0.0)

ax.plot([2, 3, 5, 1])
fig.tight_layout()

win = plt.gcf().canvas.manager.window
win.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
win.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
win.setStyleSheet("background:transparent")

plt.show()


问:
Azure Data Factory: complex (JSON) state management
I need to handle some complex state with Azure Data Factory (ADF). AFAIK, the only mechanic that Azure provide you with - is SetVariable activity which accepts only single value.

What to do if I need something more complex? A JSON structure for instance

How can I perform the following steps:

Read some state from SQL database

Enrich the SQL-query results with ADF pipeline variables

Pass the enriched result as JSON payload to ADF's Webhook activity

Accept JSON as response to Webhook activity and store it into SQL database

答:
Set variable activity only supports following formats, which is exactly what you mentioned in your question.

I highly recommand you to refer my previous answer:Azure Data Factory - SQL to nested JSON. With that solution, you could get json string by executing sql in the copy activity SQL DB source dataset.

Then please pass the json string into your Web Activity as parameter and parse the json string in the Web Activity inside. I think this could solve your problem.


问:
Efficient MySQL table structure for rating system
This post is a follow-up of this answered question: Best method for storing a list of user IDs.

I took cletus and Mehrdad Afshari's epic advice of using a normalized database approach. Are the following tables properly set up for proper optimization? I'm kind of new to MySQL efficiency, so I want to make sure this is effective.

Also, when it comes to finding the average rating for a game and the total number of votes should I use the following two queries, respectively?

```<code>SELECT avg(vote) FROM votes WHERE uid = $uid AND gid = $gid;
SELECT count(uid) FROM votes WHERE uid = $uid AND gid = $gid;

CREATE TABLE IF NOT EXISTS `games` (
  `id` int(8) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(8) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `votes` (
  `uid` int(8) NOT NULL,
  `gid` int(8) NOT NULL,
  `vote` int(1) NOT NULL,
  KEY `uid` (`uid`,`gid`)
) ;
</code>```

答:
Looks good.

I would have used users_id & games_id instead of gid and uid which sounds like global id and unique id

ContentLicense: CC BY-SA 2.5

Body:
This post is a follow-up of this answered question: Best method for storing a list of user IDs.

I took cletus and Mehrdad Afshari's epic advice of using a normalized database approach. Are the following tables properly set up for proper optimization? I'm kind of new to MySQL efficiency, so I want to make sure this is effective.

Also, when it comes to finding the average rating for a game and the total number of votes should I use the following two queries, respectively?

SELECT avg(vote) FROM votes WHERE uid = $uid AND gid = $gid;
SELECT count(uid) FROM votes WHERE uid = $uid AND gid = $gid;

CREATE TABLE IF NOT EXISTS `games` (
  `id` int(8) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(8) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `votes` (
  `uid` int(8) NOT NULL,
  `gid` int(8) NOT NULL,
  `vote` int(1) NOT NULL,
  KEY `uid` (`uid`,`gid`)
) ;

OwnerDisplayName: Itay Moav


问:
Indented trace in C++
I want to develop indented trace for our large C++ code base that will be perticularly helpful for developers to find the issues. I want to have indented trace functionality. E.g Consider following code:-

```<code> void FunctionA()
{
     TR_ENTER("Function A");
     TR_PRINT("Dignostic message Function A");
     FunctionB(); // Call function B
}

 void FunctionB()
{
    TR_ENTER("Function B");
    TR_PRINT("Dignostic message Function B");
    FunctionC(); // Call function B
}

void FunctionC()
{
   TR_ENTER("Function C");
   TR_PRINT("Dignostic message Function C");
}
</code>```

As you can see the calls above are nested within each other. I want to generate trace log as shown below:

```<code>Function A - Start
Dignostic message Function A
     Function B - Start
     Dignostic message Function B
            Function C - Start
            Dignostic message Function C
            Function C - End
     Function B - End
Function A - End
</code>```

TR_ENTER and TR_PRINT are some macros that I have use as example. To say that the function start I have use TR_ENTER and for printing some dignostic messages I have used TR_PRINT.

As you can see traces for nested function call are indented within each other. May I know is there anything already available so that I could prevent myself to work on reinventing the wheel.

Thanks,
Omky

答:
There are a lot of logging libraries for C++ out there, in particular I can recommend Log4cxx. They will help you building and configuring the log message output of you application. To analyze the log files you will need an additional tool like Apache Chainsaw.

See as well Is there a log file analyzer for log4j files?

Title: Indented trace in C++

Body:
I want to develop indented trace for our large C++ code base that will be perticularly helpful for developers to find the issues. I want to have indented trace functionality. E.g Consider following code:-

 void FunctionA()
{
     TR_ENTER("Function A");
     TR_PRINT("Dignostic message Function A");
     FunctionB(); // Call function B
}

 void FunctionB()
{
    TR_ENTER("Function B");
    TR_PRINT("Dignostic message Function B");
    FunctionC(); // Call function B
}

void FunctionC()
{
   TR_ENTER("Function C");
   TR_PRINT("Dignostic message Function C");
}

As you can see the calls above are nested within each other. I want to generate trace log as shown below:

Function A - Start
Dignostic message Function A
     Function B - Start
     Dignostic message Function B
            Function C - Start
            Dignostic message Function C
            Function C - End
     Function B - End
Function A - End

TR_ENTER and TR_PRINT are some macros that I have use as example. To say that the function start I have use TR_ENTER and for printing some dignostic messages I have used TR_PRINT.

As you can see traces for nested function call are indented within each other. May I know is there anything already available so that I could prevent myself to work on reinventing the wheel.

Thanks,
Omky


问:
this.function vs this.fuction() Javascript/Typescript
New to Javascript/Typescript, why is the first set of code wrong? and why is the second one correct? Aren't we passing in a call to the function doSomething?

```<code><button onClick={this.doSomething}>Click</button>

function doSomething() {
        console.log('hi');
    }
</code>```

vs

```<code><button onClick={this.doSomething()}>Click</button>

function doSomething() {
        console.log('hi');
    }
</code>```

答:
In javascript, "()" is called to execute the function

```<code><button onClick={this.doSomething}>Click</button>
// not execute function doSomething

<button onClick={this.doSomething()}>Click</button>
// execute function doSomething
</code>```

Body:
New to Javascript/Typescript, why is the first set of code wrong? and why is the second one correct? Aren't we passing in a call to the function doSomething?

<button onClick={this.doSomething}>Click</button>

function doSomething() {
        console.log('hi');
    }

vs

<button onClick={this.doSomething()}>Click</button>

function doSomething() {
        console.log('hi');
    }

Body:
In javascript, "()" is called to execute the function

<button onClick={this.doSomething}>Click</button>
// not execute function doSomething

<button onClick={this.doSomething()}>Click</button>
// execute function doSomething


问:
Anzure Search ingestion events
I'd like to know if Azure Search offers any ability to trigger an Azure Function when a document gets indexed or inserted into Azure search or if there are any other events I can take advantage of.

I'd like to avoid a timed event which continuously scans Azure search for new documents.

答: If you're using an indexer, you can add a skillset with a WebApiSkill to invoke your Azure Function for each inserted document. However, there's no transactional consistency guarantees - a document for which your function will be invoked is not guaranteed to be successfully inserted into the index.  </p>

Title: Anzure Search ingestion events


问:
Class inheriting from several Interfaces having same method signature
1) How to solve this problem in Java?

2) What if only the return types are different in the interfaces?

答:
1) This is not a real problem as an interface does not define an implementation. In the example all three cases are going to call the same implementation.

2) There is no problem if return types are compatible (see covariant return types).Simply, you can change the return type if the new one is extending the one defined in the interface:

```<code>class A {
 ...
 List returnList();
}

class B extends A {
 ...
 ArrayList returnList(); // possible as an ArrayList is a List
}
</code>```

Body:
1) This is not a real problem as an interface does not define an implementation. In the example all three cases are going to call the same implementation.

2) There is no problem if return types are compatible (see covariant return types).Simply, you can change the return type if the new one is extending the one defined in the interface:

class A {
 ...
 List returnList();
}

class B extends A {
 ...
 ArrayList returnList(); // possible as an ArrayList is a List
}


问:
my tooltip in d3 won't show up in the right place
I trying to add a simple tooltip to my scatterplot, the thing is that it shows below the graph, I don't know if it is for the "div", but I've tried with svg and g and still won't show.
Is there any other way I can add my tooltip?</p>

```<code>const tooltip = d3.select("#CraftBeer")
                  .append("div")
                  .style("opacity", 0)
                  .attr("class", "tooltip")
                  .style("background-color", "white")
                  .style("border", "solid")
                  .style("border-width", "1px")
                  .style("border-radius", "5px")
                  .style("padding", "10px")

              const mouseover = function(d) {
                tooltip
                  .style("opacity", 1)
              }

              const mousemove = function(d) {
                tooltip
                  .html(d.beer + "<br/>" + "ABV:" + d.abv + "%" + "<br/>" + "IBU:" + d.ibu +"<br/>" + "SRM:" + d.srm)
                  .style("left", (d3.event.pageX+10)+"px") // It is important to put the +90: other wise the tooltip is exactly where the point is an it creates a weird effect
                  .style("top", (d3.event.pageY-10)+"px")
              }

              const mouseleave = function(d) {
                tooltip
                  .transition()
                  .duration(300)
                  .style("opacity", 0)
              }

    plot = g.selectAll("bottle")
                .data(data)
                .enter()
                .append("g")
                    .attr("transform", d => `translate(${xScale(d.abv)},${yScale(d.ibu)})`)
                    .style("fill", d => colors(d.srm))
                    .style("stroke", d => colors(d.srm))
                    .style("stroke-width", "13px")

    plot.append("g")
            .attr("transform", `scale(0.150) translate(-256,-256)`)
            .selectAll()
            .data(bottlePath)
            .enter()
            .append("path")
            .attr("d", d => d)

    plot.on("mouseover", mouseover)
        .on("mousemove", mousemove)
        .on("mouseleave", mouseleave)
</code>```

答:
Try putting the style for your tooltip before the html like

```<code>              const mousemove = function(d) {
                tooltip
                  .style("left", (d3.event.pageX+10)+"px") // It is important to put the +90: other wise the tooltip is exactly where the point is an it creates a weird effect
                  .style("top", (d3.event.pageY-10)+"px")
                  .html(d.beer + "<br/>" + "ABV:" + d.abv + "%" + "<br/>" + "IBU:" + d.ibu +"<br/>" + "SRM:" + d.srm)

              }
</code>```

Body:
I trying to add a simple tooltip to my scatterplot, the thing is that it shows below the graph, I don't know if it is for the "div", but I've tried with svg and g and still won't show.
Is there any other way I can add my tooltip?

const tooltip = d3.select("#CraftBeer")
                  .append("div")
                  .style("opacity", 0)
                  .attr("class", "tooltip")
                  .style("background-color", "white")
                  .style("border", "solid")
                  .style("border-width", "1px")
                  .style("border-radius", "5px")
                  .style("padding", "10px")

              const mouseover = function(d) {
                tooltip
                  .style("opacity", 1)
              }

              const mousemove = function(d) {
                tooltip
                  .html(d.beer + "
" + "ABV:" + d.abv + "%" + "
" + "IBU:" + d.ibu +"
" + "SRM:" + d.srm)
                  .style("left", (d3.event.pageX+10)+"px") // It is important to put the +90: other wise the tooltip is exactly where the point is an it creates a weird effect
                  .style("top", (d3.event.pageY-10)+"px")
              }

              const mouseleave = function(d) {
                tooltip
                  .transition()
                  .duration(300)
                  .style("opacity", 0)
              }

    plot = g.selectAll("bottle")
                .data(data)
                .enter()
                .append("g")
                    .attr("transform", d => `translate(${xScale(d.abv)},${yScale(d.ibu)})`)
                    .style("fill", d => colors(d.srm))
                    .style("stroke", d => colors(d.srm))
                    .style("stroke-width", "13px")

    plot.append("g")
            .attr("transform", `scale(0.150) translate(-256,-256)`)
            .selectAll()
            .data(bottlePath)
            .enter()
            .append("path")
            .attr("d", d => d)

    plot.on("mouseover", mouseover)
        .on("mousemove", mousemove)
        .on("mouseleave", mouseleave)

Body:
Try putting the style for your tooltip before the html like

              const mousemove = function(d) {
                tooltip
                  .style("left", (d3.event.pageX+10)+"px") // It is important to put the +90: other wise the tooltip is exactly where the point is an it creates a weird effect
                  .style("top", (d3.event.pageY-10)+"px")
                  .html(d.beer + "<br/>" + "ABV:" + d.abv + "%" + "<br/>" + "IBU:" + d.ibu +"<br/>" + "SRM:" + d.srm)

              }