问:
allowed-list of referrer header in nextjs
How are you?

I have a question regarding the header referrer.
In a pentest analysis to my app in nextjs I was told that it is allowing to pass a different header referrer to the allowed ones. For which I must implement a white list that does not allow access to resources if the referrer header is different.

I leave an image of the observation

Referrer header edited

Do you know how I could implement this validation from NextJs?

答:
I would ask that you front your app with a layer than implementing NextJS for referrer whitelisting, you could utilize a CDN or a Nginx proxy

For CDN's, using something like Cloudflare's referrer
whitelisting

Another option is to use nginx referrer policies

If these are not options, then you could build a custom nextjs server
https://nextjs.org/docs/advanced-features/custom-server and then look at the req object to make your responses conditional, i.e send to a 403 page.


来源: stackexchange

问:
Keep both forms on top
I have 2 forms (Parent & child). i want to keep both on top (Not topMost). The next fragment work's but the parent not firing any event. I found this "Click Event Not Firing - Cannot Change Focus - Cannot Close Form" althouhg this did not work.

The next fragment works for keep forms but parent doesn't not work:

```<code>public FormMain()
{
   InitializeComponent();
   this.Activated += FormMain_Activated;
}

private void FormMain_Activated(object sender, EventArgs e)
{
   ChildForm.Activate();
}
</code>```

I tried focus the parent form on "GotFocus" and "Activated" althought this doesn't work.

Note: For child form i have this fragment:

```<code>        protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            // turn on WS_EX_TOOLWINDOW style bit
            cp.ExStyle |= 0x80;
            return cp;
        }
    }
</code>```

答:
The behavior you're describing is that of an owned form; something like a floating tool panel in a paint program, that should minimize/restore when the main window it is associated with does a minimize/restore, but can be moved independently and be covered by otehr windows when the main paint program is also covered

To do that, you  can make the main form an owner of the tool panel form. If the main form is responsible for opening the tool panel:

```<code>toolPanel.Show(this);   //the code is in the main form so `this` refers to the current instance of the main form
</code>```

If some other form is responsible for showing both, it'd be more like toolPanel.Show(mainForm) - we pass to Show the form that we want to dedicate as the owner of the form we are showing

ContentLicense: CC BY-SA 4.0

Title: Keep both forms on top

Body:
I have 2 forms (Parent & child). i want to keep both on top (Not topMost). The next fragment work's but the parent not firing any event. I found this "Click Event Not Firing - Cannot Change Focus - Cannot Close Form" althouhg this did not work.

The next fragment works for keep forms but parent doesn't not work:

public FormMain()
{
   InitializeComponent();
   this.Activated += FormMain_Activated;
}

private void FormMain_Activated(object sender, EventArgs e)
{
   ChildForm.Activate();
}

I tried focus the parent form on "GotFocus" and "Activated" althought this doesn't work.

Note: For child form i have this fragment:

        protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            // turn on WS_EX_TOOLWINDOW style bit
            cp.ExStyle |= 0x80;
            return cp;
        }
    }

Body:
The behavior you're describing is that of an owned form; something like a floating tool panel in a paint program, that should minimize/restore when the main window it is associated with does a minimize/restore, but can be moved independently and be covered by otehr windows when the main paint program is also covered

To do that, you  can make the main form an owner of the tool panel form. If the main form is responsible for opening the tool panel:

toolPanel.Show(this);   //the code is in the main form so `this` refers to the current instance of the main form

If some other form is responsible for showing both, it'd be more like toolPanel.Show(mainForm) - we pass to Show the form that we want to dedicate as the owner of the form we are showing


问:
MT: Calculating METEOR Score of two different files
For an Machine Translation evaluation I need to calculate the METEOR score between the translation output file and the reference file.

I already found this question How can I implement meteor score when evaluating a model when using the meteor_score module from nltk?, but it was not helpful.

Is there any official Python package or Github repository for the calculation of the METEOR score you would recommend?

How to calculate the METEOR between the reference file and the output translation file?

答:
I found out you have to download METEOR from https://www.cs.cmu.edu/~alavie/METEOR/index.html#Download .

For calculating the METEOR Score you need Java as well.

Run the following command to compare the reference and the test file and to get the METEOR score:

```<code>java -Xmx2G -jar meteor-1.5.jar test-file reference-file -l de
</code>```

This page is well documented: https://www.cs.cmu.edu/~alavie/METEOR/README.html

Body:
I found out you have to download METEOR from https://www.cs.cmu.edu/~alavie/METEOR/index.html#Download .

For calculating the METEOR Score you need Java as well.

Run the following command to compare the reference and the test file and to get the METEOR score:

java -Xmx2G -jar meteor-1.5.jar test-file reference-file -l de

This page is well documented: https://www.cs.cmu.edu/~alavie/METEOR/README.html


问:
Adding metadata as annotation to correlation heat-map
I m trying to generate  a sample to sample correlation heat-map which I m able to do it.

Is it possible to add metadata to the correlation heat map just as we can do for normal heatmap?

My code

```<code>library(Hmisc)
library(pheatmap)

    df1 <- read.csv("figure1/TCGA_data/BEAT_AML/TCGA_AML/analysis/TCGA_expr_EF.txt",sep = "\t",header = T)

    dim(df1)
    names(df1)
    df1 <- df1[-c(1)]
    names(df1)
    data1 <- df1
    gen <- data1

    head(gen)
    dim(gen)

    gendat <- t(gen)
    gendat <- gen
    dim(gendat)
    macolor = colorRampPalette(c("navyblue","white","red"))(100)
    cor_5 <- rcorr(as.matrix(PCA_map_rlog[-c(1:2)]))

    cor_5 <- rcorr(as.matrix(gendat))
    M <- cor_5$r
    str(M)
    p_mat <- cor_5$P
    row_names <- rownames(M)

    head(M)

    plot_data_pheatmap <- pheatmap(M, color = rev(macolor),
                      clustering_method = "complete", fontsize_row = 8, fontsize_col = 8,show_colnames = FALSE,show_rownames = FALSE)
    dev.off()
</code>```

Metadata small subset

```<code>aa <- dput(head(b))
structure(list(name = structure(1:6, .Label = c("TCGA-AB-2803",
"TCGA-AB-2805", "TCGA-AB-2806", "TCGA-AB-2807", "TCGA-AB-2808",
"TCGA-AB-2810", "TCGA-AB-2811", "TCGA-AB-2812", "TCGA-AB-2813",
"TCGA-AB-2814", "TCGA-AB-2815", "TCGA-AB-2816", "TCGA-AB-2817",
"TCGA-AB-2818", "TCGA-AB-2819", "TCGA-AB-2820", "TCGA-AB-2821",
"TCGA-AB-2822", "TCGA-AB-2823", "TCGA-AB-2824", "TCGA-AB-2825",
"TCGA-AB-2826", "TCGA-AB-2828", "TCGA-AB-2830", "TCGA-AB-2832",
"TCGA-AB-2833", "TCGA-AB-2834", "TCGA-AB-2835", "TCGA-AB-2836",
"TCGA-AB-2837", "TCGA-AB-2838", "TCGA-AB-2839", "TCGA-AB-2840",
"TCGA-AB-2841", "TCGA-AB-2842", "TCGA-AB-2843", "TCGA-AB-2844",
"TCGA-AB-2845", "TCGA-AB-2846", "TCGA-AB-2847", "TCGA-AB-2848",
"TCGA-AB-2849", "TCGA-AB-2851", "TCGA-AB-2853", "TCGA-AB-2854",
"TCGA-AB-2855", "TCGA-AB-2856", "TCGA-AB-2857", "TCGA-AB-2858",
"TCGA-AB-2859", "TCGA-AB-2860", "TCGA-AB-2861", "TCGA-AB-2862",
"TCGA-AB-2863", "TCGA-AB-2865", "TCGA-AB-2866", "TCGA-AB-2867",
"TCGA-AB-2868", "TCGA-AB-2869", "TCGA-AB-2870", "TCGA-AB-2871",
"TCGA-AB-2872", "TCGA-AB-2873", "TCGA-AB-2874", "TCGA-AB-2875",
"TCGA-AB-2877", "TCGA-AB-2879", "TCGA-AB-2880", "TCGA-AB-2881",
"TCGA-AB-2882", "TCGA-AB-2884", "TCGA-AB-2885", "TCGA-AB-2886",
"TCGA-AB-2887", "TCGA-AB-2888", "TCGA-AB-2889", "TCGA-AB-2890",
"TCGA-AB-2891", "TCGA-AB-2895", "TCGA-AB-2896", "TCGA-AB-2897",
"TCGA-AB-2898", "TCGA-AB-2899", "TCGA-AB-2900", "TCGA-AB-2901",
"TCGA-AB-2903", "TCGA-AB-2904", "TCGA-AB-2908", "TCGA-AB-2909",
"TCGA-AB-2910", "TCGA-AB-2911", "TCGA-AB-2912", "TCGA-AB-2913",
"TCGA-AB-2914", "TCGA-AB-2915", "TCGA-AB-2916", "TCGA-AB-2917",
"TCGA-AB-2918", "TCGA-AB-2919", "TCGA-AB-2920", "TCGA-AB-2921",
"TCGA-AB-2924", "TCGA-AB-2925", "TCGA-AB-2927", "TCGA-AB-2928",
"TCGA-AB-2929", "TCGA-AB-2930", "TCGA-AB-2931", "TCGA-AB-2932",
"TCGA-AB-2933", "TCGA-AB-2934", "TCGA-AB-2935", "TCGA-AB-2936",
"TCGA-AB-2937", "TCGA-AB-2938", "TCGA-AB-2939", "TCGA-AB-2940",
"TCGA-AB-2941", "TCGA-AB-2942", "TCGA-AB-2943", "TCGA-AB-2944",
"TCGA-AB-2946", "TCGA-AB-2948", "TCGA-AB-2949", "TCGA-AB-2950",
"TCGA-AB-2952", "TCGA-AB-2954", "TCGA-AB-2955", "TCGA-AB-2956",
"TCGA-AB-2959", "TCGA-AB-2963", "TCGA-AB-2964", "TCGA-AB-2965",
"TCGA-AB-2966", "TCGA-AB-2967", "TCGA-AB-2969", "TCGA-AB-2970",
"TCGA-AB-2971", "TCGA-AB-2972", "TCGA-AB-2973", "TCGA-AB-2975",
"TCGA-AB-2976", "TCGA-AB-2977", "TCGA-AB-2978", "TCGA-AB-2979",
"TCGA-AB-2980", "TCGA-AB-2981", "TCGA-AB-2982", "TCGA-AB-2983",
"TCGA-AB-2984", "TCGA-AB-2985", "TCGA-AB-2986", "TCGA-AB-2987",
"TCGA-AB-2988", "TCGA-AB-2990", "TCGA-AB-2991", "TCGA-AB-2992",
"TCGA-AB-2993", "TCGA-AB-2994", "TCGA-AB-2995", "TCGA-AB-2996",
"TCGA-AB-2998", "TCGA-AB-2999", "TCGA-AB-3000", "TCGA-AB-3001",
"TCGA-AB-3002", "TCGA-AB-3005", "TCGA-AB-3006", "TCGA-AB-3007",
"TCGA-AB-3008", "TCGA-AB-3009", "TCGA-AB-3011", "TCGA-AB-3012"
), class = "factor"), FAB = structure(c(4L, 1L, 2L, 2L, 3L, 3L
), .Label = c("M0", "M1", "M2", "M3", "M4", "M5", "M6", "M7",
"nc"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
</code>```

I would like to add the FAB column as my annotation to the final correlation heatmap.

Any suggestion or help would be really appreciated

My expression TCGA_expr_EF.txt used and my metadata

答:
You can add colorbar annotation layers to the rows and columns in pheatmap() using annotation_row/annotation_col and annotation_colors arguments.

Your example was far from minimal so I used a small included dataset here.

Also as noted in the comments, your correlation values range from -1 to 1 so it's misleading to use a diverging colormap that is not centered at 0. I offer two possible solutions. First, you could center it at 0 using the breaks argument in pheatmap() which will emphasize that most of your values are actually quite similar and all highly mutually correlated. Second, you could use a sequential palette such as in my second example which will emphasize the differences between the samples.

library(Hmisc)
library(pheatmap)
library(tidyverse)
library(viridisLite)

# prep data
d <- mtcars %>%
  rownames_to_column("car") %>%
  mutate(car = abbreviate(car)) %>%
  column_to_rownames("car") %>%
  as.matrix()

# run correlation
c <- d %>%
  t() %>%
  rcorr(type = "pearson") %>%
  .[["r"]]

# create diverging colormap
macolor <- colorRampPalette(c("navyblue","white","red"))(100)

# prep sample annotations
samp_annot <- data.frame(row.names = rownames(d), cyl = factor(d[,2]))
# prep annotation colors
annot_col <- list(cyl = setNames(c("#E41A1C", "#377EB8", "#4DAF4A"), unique(samp_annot$cyl)))

# set divergent palette to center at 0 with breaks
c %>%
  pheatmap(
    mat = .,
    color = rev(macolor),
    breaks = seq(-1, 1, length.out = 101),
    clustering_method = "complete",
    annotation_row = samp_annot,
    annotation_col = samp_annot,
    annotation_colors = annot_col[1],
    show_colnames = FALSE,
    show_rownames = FALSE
  )
```
<p><img src="https://i.imgur.com/iBqyv3h.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code># use sequential palette
c %>%
  pheatmap(
    mat = .,
    color = viridis(100, option = "A"),
    clustering_method = "complete",
    annotation_row = samp_annot,
    annotation_col = samp_annot,
    annotation_colors = annot_col[1],
    show_colnames = FALSE,
    show_rownames = FALSE
  )
</code>```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I m trying to generate  a sample to sample correlation heat-map which I m able to do it.

Is it possible to add metadata to the correlation heat map just as we can do for normal heatmap?

My code

library(Hmisc)
library(pheatmap)

    df1 <- read.csv("figure1/TCGA_data/BEAT_AML/TCGA_AML/analysis/TCGA_expr_EF.txt",sep = "\t",header = T)

    dim(df1)
    names(df1)
    df1 <- df1[-c(1)]
    names(df1)
    data1 <- df1
    gen <- data1

    head(gen)
    dim(gen)

    gendat <- t(gen)
    gendat <- gen
    dim(gendat)
    macolor = colorRampPalette(c("navyblue","white","red"))(100)
    cor_5 <- rcorr(as.matrix(PCA_map_rlog[-c(1:2)]))

    cor_5 <- rcorr(as.matrix(gendat))
    M <- cor_5$r
    str(M)
    p_mat <- cor_5$P
    row_names <- rownames(M)

    head(M)

    plot_data_pheatmap <- pheatmap(M, color = rev(macolor),
                      clustering_method = "complete", fontsize_row = 8, fontsize_col = 8,show_colnames = FALSE,show_rownames = FALSE)
    dev.off()

Metadata small subset

aa <- dput(head(b))
structure(list(name = structure(1:6, .Label = c("TCGA-AB-2803",
"TCGA-AB-2805", "TCGA-AB-2806", "TCGA-AB-2807", "TCGA-AB-2808",
"TCGA-AB-2810", "TCGA-AB-2811", "TCGA-AB-2812", "TCGA-AB-2813",
"TCGA-AB-2814", "TCGA-AB-2815", "TCGA-AB-2816", "TCGA-AB-2817",
"TCGA-AB-2818", "TCGA-AB-2819", "TCGA-AB-2820", "TCGA-AB-2821",
"TCGA-AB-2822", "TCGA-AB-2823", "TCGA-AB-2824", "TCGA-AB-2825",
"TCGA-AB-2826", "TCGA-AB-2828", "TCGA-AB-2830", "TCGA-AB-2832",
"TCGA-AB-2833", "TCGA-AB-2834", "TCGA-AB-2835", "TCGA-AB-2836",
"TCGA-AB-2837", "TCGA-AB-2838", "TCGA-AB-2839", "TCGA-AB-2840",
"TCGA-AB-2841", "TCGA-AB-2842", "TCGA-AB-2843", "TCGA-AB-2844",
"TCGA-AB-2845", "TCGA-AB-2846", "TCGA-AB-2847", "TCGA-AB-2848",
"TCGA-AB-2849", "TCGA-AB-2851", "TCGA-AB-2853", "TCGA-AB-2854",
"TCGA-AB-2855", "TCGA-AB-2856", "TCGA-AB-2857", "TCGA-AB-2858",
"TCGA-AB-2859", "TCGA-AB-2860", "TCGA-AB-2861", "TCGA-AB-2862",
"TCGA-AB-2863", "TCGA-AB-2865", "TCGA-AB-2866", "TCGA-AB-2867",
"TCGA-AB-2868", "TCGA-AB-2869", "TCGA-AB-2870", "TCGA-AB-2871",
"TCGA-AB-2872", "TCGA-AB-2873", "TCGA-AB-2874", "TCGA-AB-2875",
"TCGA-AB-2877", "TCGA-AB-2879", "TCGA-AB-2880", "TCGA-AB-2881",
"TCGA-AB-2882", "TCGA-AB-2884", "TCGA-AB-2885", "TCGA-AB-2886",
"TCGA-AB-2887", "TCGA-AB-2888", "TCGA-AB-2889", "TCGA-AB-2890",
"TCGA-AB-2891", "TCGA-AB-2895", "TCGA-AB-2896", "TCGA-AB-2897",
"TCGA-AB-2898", "TCGA-AB-2899", "TCGA-AB-2900", "TCGA-AB-2901",
"TCGA-AB-2903", "TCGA-AB-2904", "TCGA-AB-2908", "TCGA-AB-2909",
"TCGA-AB-2910", "TCGA-AB-2911", "TCGA-AB-2912", "TCGA-AB-2913",
"TCGA-AB-2914", "TCGA-AB-2915", "TCGA-AB-2916", "TCGA-AB-2917",
"TCGA-AB-2918", "TCGA-AB-2919", "TCGA-AB-2920", "TCGA-AB-2921",
"TCGA-AB-2924", "TCGA-AB-2925", "TCGA-AB-2927", "TCGA-AB-2928",
"TCGA-AB-2929", "TCGA-AB-2930", "TCGA-AB-2931", "TCGA-AB-2932",
"TCGA-AB-2933", "TCGA-AB-2934", "TCGA-AB-2935", "TCGA-AB-2936",
"TCGA-AB-2937", "TCGA-AB-2938", "TCGA-AB-2939", "TCGA-AB-2940",
"TCGA-AB-2941", "TCGA-AB-2942", "TCGA-AB-2943", "TCGA-AB-2944",
"TCGA-AB-2946", "TCGA-AB-2948", "TCGA-AB-2949", "TCGA-AB-2950",
"TCGA-AB-2952", "TCGA-AB-2954", "TCGA-AB-2955", "TCGA-AB-2956",
"TCGA-AB-2959", "TCGA-AB-2963", "TCGA-AB-2964", "TCGA-AB-2965",
"TCGA-AB-2966", "TCGA-AB-2967", "TCGA-AB-2969", "TCGA-AB-2970",
"TCGA-AB-2971", "TCGA-AB-2972", "TCGA-AB-2973", "TCGA-AB-2975",
"TCGA-AB-2976", "TCGA-AB-2977", "TCGA-AB-2978", "TCGA-AB-2979",
"TCGA-AB-2980", "TCGA-AB-2981", "TCGA-AB-2982", "TCGA-AB-2983",
"TCGA-AB-2984", "TCGA-AB-2985", "TCGA-AB-2986", "TCGA-AB-2987",
"TCGA-AB-2988", "TCGA-AB-2990", "TCGA-AB-2991", "TCGA-AB-2992",
"TCGA-AB-2993", "TCGA-AB-2994", "TCGA-AB-2995", "TCGA-AB-2996",
"TCGA-AB-2998", "TCGA-AB-2999", "TCGA-AB-3000", "TCGA-AB-3001",
"TCGA-AB-3002", "TCGA-AB-3005", "TCGA-AB-3006", "TCGA-AB-3007",
"TCGA-AB-3008", "TCGA-AB-3009", "TCGA-AB-3011", "TCGA-AB-3012"
), class = "factor"), FAB = structure(c(4L, 1L, 2L, 2L, 3L, 3L
), .Label = c("M0", "M1", "M2", "M3", "M4", "M5", "M6", "M7",
"nc"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")

I would like to add the FAB column as my annotation to the final correlation heatmap.

Any suggestion or help would be really appreciated

My expression TCGA_expr_EF.txt used and my metadata

Body:
You can add colorbar annotation layers to the rows and columns in pheatmap() using annotation_row/annotation_col and annotation_colors arguments.

Your example was far from minimal so I used a small included dataset here.

Also as noted in the comments, your correlation values range from -1 to 1 so it's misleading to use a diverging colormap that is not centered at 0. I offer two possible solutions. First, you could center it at 0 using the breaks argument in pheatmap() which will emphasize that most of your values are actually quite similar and all highly mutually correlated. Second, you could use a sequential palette such as in my second example which will emphasize the differences between the samples.

library(Hmisc)
library(pheatmap)
library(tidyverse)
library(viridisLite)

# prep data
d <- mtcars %>%
  rownames_to_column("car") %>%
  mutate(car = abbreviate(car)) %>%
  column_to_rownames("car") %>%
  as.matrix()

# run correlation
c <- d %>%
  t() %>%
  rcorr(type = "pearson") %>%
  .[["r"]]

# create diverging colormap
macolor <- colorRampPalette(c("navyblue","white","red"))(100)

# prep sample annotations
samp_annot <- data.frame(row.names = rownames(d), cyl = factor(d[,2]))
# prep annotation colors
annot_col <- list(cyl = setNames(c("#E41A1C", "#377EB8", "#4DAF4A"), unique(samp_annot$cyl)))

# set divergent palette to center at 0 with breaks
c %>%
  pheatmap(
    mat = .,
    color = rev(macolor),
    breaks = seq(-1, 1, length.out = 101),
    clustering_method = "complete",
    annotation_row = samp_annot,
    annotation_col = samp_annot,
    annotation_colors = annot_col[1],
    show_colnames = FALSE,
    show_rownames = FALSE
  )

# use sequential palette
c %>%
  pheatmap(
    mat = .,
    color = viridis(100, option = "A"),
    clustering_method = "complete",
    annotation_row = samp_annot,
    annotation_col = samp_annot,
    annotation_colors = annot_col[1],
    show_colnames = FALSE,
    show_rownames = FALSE
  )

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Sqlite3.interfaceError: Incorrect number of bindiga supplies: the current statement uses 3, and there is 1 supplied
Please i encounter this error while running my app, how do i go about it.

CODE:

db= get_db()
db.executemany('insert into users(name,email,massage) values(?,?,?)', [name,email,massage])

答: The executemany method expects a list of sequences (eg lists, tuples) as the argument. Changing the argument from [name,email,massage] to [[name,email,massage]] will cure the problem. The posted syntax will work if executemany is replaced by execute method. It is unclear from context which correction is appropriate.


问:
how can I stop the [UtcDateTime cache_ok ]warn? When I run airflow dag
when I run airflow server :
My version is airflow lastest(2.2).when I run the program,the dag log

```<code>"SAWarning: TypeDecorator UtcDateTime(timezone=True) will not produce a cache key because the ``cache_ok`` attribute is not set to True.  This can have significant performance implications including some performance degradations in comparison to prior SQLAlchemy versions.  Set this attribute to True if this type object's state is safe to use in a cache key, or False to disable this warning. (Background on this error at: https://sqlalche.me/e/14/cprf)
  return session.query(DagRun)"
====
the scheduler  log:
/airflow/jobs/scheduler_job.py:944 SAWarning: TypeDecorator UtcDateTime(timezone=True) will not produce a cache key because the ``cache_ok`` attribute is not set to True.
===
</code>```

I had added "cache_ok = true" to airflow.cfg,or "scheduler_job.py" Class,but not slove it

答:
This is due to change in SQLAlchemy 1.4 (see release notes)

If you get this warning it means that you did not install Airflow from constraints (see docs) as in constraints for Airflow 2.2.3 it has SQLAlchemy==1.3.24

As for future versions Airflow 2.2.4 limits the lib version to <1.4 to as you can see from this PR

Body:
when I run airflow server :
My version is airflow lastest(2.2).when I run the program,the dag log

"SAWarning: TypeDecorator UtcDateTime(timezone=True) will not produce a cache key because the ``cache_ok`` attribute is not set to True.  This can have significant performance implications including some performance degradations in comparison to prior SQLAlchemy versions.  Set this attribute to True if this type object's state is safe to use in a cache key, or False to disable this warning. (Background on this error at: https://sqlalche.me/e/14/cprf)
  return session.query(DagRun)"
====
the scheduler  log:
/airflow/jobs/scheduler_job.py:944 SAWarning: TypeDecorator UtcDateTime(timezone=True) will not produce a cache key because the ``cache_ok`` attribute is not set to True.
===

I had added "cache_ok = true" to airflow.cfg,or "scheduler_job.py" Class,but not slove it


问:
Nested Json Object Into Array
I'm trying to access a nested json array

```<code>        var jsonResponse:Object = JSON.decode(response);
        var foo:Object = JSON.decode(jsonResponse.nested);
        var bar:Array = foo as Array;
</code>```

When i inspect foo - its an object with about 50 children objects.

I can read the properties of the children objects.

However, when i cast foo as an Array it comes back null.

I'd prefer to not iterate over each object and push it into an array.

Any advice?

答:
If you have an object, you indeed cannot cast it to an Array. You either need to modify the JSON string (if you have access to it), or iterate over the properties as an object:

```<code>for (var n:String in foo) {
    var value = foo[n];
    trace(value);
}
</code>```

Or if you really want to use an array, you need to create it manually:

```<code>var bar:Array = [];
for (var n:String in foo) {
    var value = foo[n];
    bar.push(value);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Nested Json Object Into Array

Body:
I'm trying to access a nested json array

        var jsonResponse:Object = JSON.decode(response);
        var foo:Object = JSON.decode(jsonResponse.nested);
        var bar:Array = foo as Array;

When i inspect foo - its an object with about 50 children objects.

I can read the properties of the children objects.

However, when i cast foo as an Array it comes back null.

I'd prefer to not iterate over each object and push it into an array.

Any advice?

Body:
If you have an object, you indeed cannot cast it to an Array. You either need to modify the JSON string (if you have access to it), or iterate over the properties as an object:

for (var n:String in foo) {
    var value = foo[n];
    trace(value);
}

Or if you really want to use an array, you need to create it manually:

var bar:Array = [];
for (var n:String in foo) {
    var value = foo[n];
    bar.push(value);
}


问:
Is this Possible to give String data type as Number in JavaScript
Can i give string data type as Number
For example

```<code>var a = "abc"
//Some Code
console.log(typeof a)  //number
</code>```

I want to play with "typeof"  i want to print string as a number
WITHOUT  changing it to number

答:
JavaScript doesn't provide any means of overriding the typeof operator, so you can't do that.

In fact, JavaScript doesn't have operator overloading at all (and is extremely unlikely ever to get it). There are a couple of games you can play with toString and valueOf on object instances, but they don't really provide overloading, and don't relate to typeof (and your string is a primitive string, not an object, so...).

Body:
Can i give string data type as Number
For example

var a = "abc"
//Some Code
console.log(typeof a)  //number

I want to play with "typeof"  i want to print string as a number
WITHOUT  changing it to number


问:
Using Android Voice Access to interact with Xamarin elements which don't show text
I have Xamarin buttons and CollectionView items which don't show text strings, and I'm working to support Android Voice Access being able to interact with those elements. Voice Access works fine with controls that do show text strings, but I've not found a way to interact with the controls that don't show text. I've set appropriate AutomationProperties.Name properties on the controls, but Voice Access doesn't interact with the controls when I speak those AutomationProperties.Name properties.

What can I set on the controls to have Voice Access work with controls, when the controls don't show text?

答:
A snippet of code might help generate more answers but without seeing the code, you might need android:importantForAccessibility="yes" or android:focusable="true" and possibly android:clickable="true"

See also What is the difference between Android focusable and importantForAccessibility when using TalkBack?


问:
Passing integers to JSX attributes

return <textarea className="tox-input" rows=2 ></textarea>;
```
<p>I want to pass <code>rows=2</code> to this tag. However, this results in the following error.</p>
```Parsing error: JSX value should be either an expression or a quoted JSX text.
```

After a bit of research, I couldn't find a way to solve this. Please could someone tell me the proper way to do it in JSX?

Note: Using rows={2} doesn't give an error, but it only shows one row.

答:
Use curly brace:

```<code>return <textarea className="tox-input" rows={2} ></textarea>;
</code>```

It will pass integer.

Playground area

Title: Passing integers to JSX attributes

Body:
return <textarea className="tox-input" rows=2 ></textarea>;

I want to pass rows=2 to this tag. However, this results in the following error.

Parsing error: JSX value should be either an expression or a quoted JSX text.

After a bit of research, I couldn't find a way to solve this. Please could someone tell me the proper way to do it in JSX?

Note: Using rows={2} doesn't give an error, but it only shows one row.

Body:
Use curly brace:

return <textarea className="tox-input" rows={2} ></textarea>;

It will pass integer.

Playground area


答:
No, you can't effectively overload typeof (or any of the other JavaScript operators) like that. If an expression is a string, its typeof will always give you string. If an expression is a number, its typeof will always give you number. There's no way to change that.

(You can create objects with new Number and new String, which will then give you object instead, but those constructors should never be used, because then you'll have objects, not primitives, which will behave in unexpected ways)

Title: Is this Possible to give String data type as Number in JavaScript


问:
This animation code is working fine but it is showing errors in vs code
CSS
This animation code is working fine but it  is showing errors in vs code..

```<code> -moz-animation: spinoffPulse 10s infinite linear;
    -webkit-animation: spinoffPulse 10s infinite linear;
 @-moz-keyframes spinoffPulse {
        0% { -moz-transform:rotate(0deg); }
        100% { -moz-transform:rotate(360deg);  }
    }
    @-webkit-keyframes spinoffPulse {
        0% { -webkit-transform:rotate(0deg); }
        100% { -webkit-transform:rotate(360deg); }
    }
</code>```

Vs code showing error in above animation code but it is working fine in output...Please Answer what is the problem in this code...

```<code>html {
  --circle-width: 300px;
}

.circle {
  aspect-ratio: 1;
  width: var(--circleWidth);
  background-color: black;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  padding: .5rem;

-moz-animation: spinoffPulse 10s infinite linear;
-webkit-animation: spinoffPulse 10s infinite linear;

}

@-moz-keyframes spinoffPulse {
    0% { -moz-transform:rotate(0deg); }
    100% { -moz-transform:rotate(360deg);  }
}
@-webkit-keyframes spinoffPulse {
    0% { -webkit-transform:rotate(0deg); }
    100% { -webkit-transform:rotate(360deg); }
}

#addNumBtn {
  position: absolute;
  top: 0;
  left: 0;
}

.numStyle {
  font-family: "roboto", sans-serif;
}
</code>```

答:
try this code.  I hope this is true</p>
```<code>html {
  --circle-width: 300px;
}

.circle {
  aspect-ratio: 1;
  width: var(--circleWidth);
  background-color: black;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  padding: .5rem;

animation: spinoffPulse 10s infinite linear;
-moz-animation: spinoffPulse 10s infinite linear;
-webkit-animation: spinoffPulse 10s infinite linear;

}
@-moz-keyframes spinoffPulse {
    0% { -moz-transform:rotate(0deg); }
    100% { -moz-transform:rotate(360deg);  }
}

@keyframes spinoffPulse {
    0% { transform:rotate(0deg); }
    100% { transform:rotate(360deg);  }
}

@-webkit-keyframes spinoffPulse {
    0% { -webkit-transform:rotate(0deg); }
    100% { -webkit-transform:rotate(360deg); }
}

#addNumBtn {
  position: absolute;
  top: 0;
  left: 0;
}

.numStyle {
  font-family: "roboto", sans-serif;
}
</code>```

Body:
CSS
This animation code is working fine but it  is showing errors in vs code..

 -moz-animation: spinoffPulse 10s infinite linear;
    -webkit-animation: spinoffPulse 10s infinite linear;
 @-moz-keyframes spinoffPulse {
        0% { -moz-transform:rotate(0deg); }
        100% { -moz-transform:rotate(360deg);  }
    }
    @-webkit-keyframes spinoffPulse {
        0% { -webkit-transform:rotate(0deg); }
        100% { -webkit-transform:rotate(360deg); }
    }

Vs code showing error in above animation code but it is working fine in output...Please Answer what is the problem in this code...

html {
  --circle-width: 300px;
}

.circle {
  aspect-ratio: 1;
  width: var(--circleWidth);
  background-color: black;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  padding: .5rem;

-moz-animation: spinoffPulse 10s infinite linear;
-webkit-animation: spinoffPulse 10s infinite linear;

}

@-moz-keyframes spinoffPulse {
    0% { -moz-transform:rotate(0deg); }
    100% { -moz-transform:rotate(360deg);  }
}
@-webkit-keyframes spinoffPulse {
    0% { -webkit-transform:rotate(0deg); }
    100% { -webkit-transform:rotate(360deg); }
}

#addNumBtn {
  position: absolute;
  top: 0;
  left: 0;
}

.numStyle {
  font-family: "roboto", sans-serif;
}

Body:
try this code.  I hope this is true

html {
  --circle-width: 300px;
}

.circle {
  aspect-ratio: 1;
  width: var(--circleWidth);
  background-color: black;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  padding: .5rem;

animation: spinoffPulse 10s infinite linear;
-moz-animation: spinoffPulse 10s infinite linear;
-webkit-animation: spinoffPulse 10s infinite linear;

}
@-moz-keyframes spinoffPulse {
    0% { -moz-transform:rotate(0deg); }
    100% { -moz-transform:rotate(360deg);  }
}

@keyframes spinoffPulse {
    0% { transform:rotate(0deg); }
    100% { transform:rotate(360deg);  }
}

@-webkit-keyframes spinoffPulse {
    0% { -webkit-transform:rotate(0deg); }
    100% { -webkit-transform:rotate(360deg); }
}

#addNumBtn {
  position: absolute;
  top: 0;
  left: 0;
}

.numStyle {
  font-family: "roboto", sans-serif;
}


问:
Deserializing an unknown enum
Why does this code not deserialize the messages correctly?

The first message received is expected to fail, because the data field = {}, but after that the data field matches the Trade structure which is part of the flattened enum Data.

What am I doing wrong?

Here is the output:

```<code>***> {"event":"bts:subscription_succeeded","channel":"live_trades_btcusd","data":{}}
===> Error("no variant of enum Data found in flattened data", line: 1, column: 79)
***> {"data":{"id":220315257,"timestamp":"1644180636","amount":0.03208,"amount_str":"0.03208000","price":41586.11,"price_str":"41586.11","type":0,"microtimestamp":"1644180636419000","buy_order_id":1455495830577152,"sell_order_id":1455495778422789},"channel":"live_trades_btcusd","event":"trade"}
===> Error("no variant of enum Data found in flattened data", line: 1, column: 290)
***> {"data":{"id":220315276,"timestamp":"1644180648","amount":0.02037389,"amount_str":"0.02037389","price":41586.11,"price_str":"41586.11","type":1,"microtimestamp":"1644180648235000","buy_order_id":1455495864238080,"sell_order_id":1455495878971395},"channel":"live_trades_btcusd","event":"trade"}
</code>```
```<code>use serde::{Deserialize, Serialize};
use serde_json::json;
use tungstenite::{connect, Message};
use url::Url;

#[derive(Serialize, Deserialize, Debug)]
enum Data {
    None,
    Trade(Trade),
}

#[derive(Serialize, Deserialize, Debug)]
struct Msg {
    channel: String,
    event: String,

    #[serde(flatten)]
    data: Data,
}

#[derive(Serialize, Deserialize, Debug)]
struct Trade {
    id: u32,
    amount: f32,
    amount_str: String,
    buy_order_id: u64,
    microtimestamp: String,
    price: f32,
    price_str: String,
    sell_order_id: u64,
    timestamp: String,
    #[serde(rename = "type")]
    _type: u8,
}

        let result: Result<Msg, serde_json::Error> = serde_json::from_str(msg.to_text().unwrap());

        let _value = match result {
            Ok(msg) => {
                println!("---> {:?}", msg);
            }
            Err(err) => {
                println!("===> {:?}", err);
                continue;
            }
        };

</code>```

https://pastebin.com/JZqPkmWC

答:
I solved it by both removing the #[serde(flatten)] and also adding #[serde(untagged)]. Thanks for the help!

```<code>#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Data {
    Trade(Trade),
    Order(Order),
    None {},
}

#[derive(Serialize, Deserialize, Debug)]
struct Msg {
    channel: String,
    event: String,
    data: Data,
}
</code>```

Title: Deserializing an unknown enum

Body:
Why does this code not deserialize the messages correctly?

The first message received is expected to fail, because the data field = {}, but after that the data field matches the Trade structure which is part of the flattened enum Data.

What am I doing wrong?

Here is the output:

***> {"event":"bts:subscription_succeeded","channel":"live_trades_btcusd","data":{}}
===> Error("no variant of enum Data found in flattened data", line: 1, column: 79)
***> {"data":{"id":220315257,"timestamp":"1644180636","amount":0.03208,"amount_str":"0.03208000","price":41586.11,"price_str":"41586.11","type":0,"microtimestamp":"1644180636419000","buy_order_id":1455495830577152,"sell_order_id":1455495778422789},"channel":"live_trades_btcusd","event":"trade"}
===> Error("no variant of enum Data found in flattened data", line: 1, column: 290)
***> {"data":{"id":220315276,"timestamp":"1644180648","amount":0.02037389,"amount_str":"0.02037389","price":41586.11,"price_str":"41586.11","type":1,"microtimestamp":"1644180648235000","buy_order_id":1455495864238080,"sell_order_id":1455495878971395},"channel":"live_trades_btcusd","event":"trade"}

use serde::{Deserialize, Serialize};
use serde_json::json;
use tungstenite::{connect, Message};
use url::Url;

#[derive(Serialize, Deserialize, Debug)]
enum Data {
    None,
    Trade(Trade),
}

#[derive(Serialize, Deserialize, Debug)]
struct Msg {
    channel: String,
    event: String,

    #[serde(flatten)]
    data: Data,
}

#[derive(Serialize, Deserialize, Debug)]
struct Trade {
    id: u32,
    amount: f32,
    amount_str: String,
    buy_order_id: u64,
    microtimestamp: String,
    price: f32,
    price_str: String,
    sell_order_id: u64,
    timestamp: String,
    #[serde(rename = "type")]
    _type: u8,
}

        let result: Result<Msg, serde_json::Error> = serde_json::from_str(msg.to_text().unwrap());

        let _value = match result {
            Ok(msg) => {
                println!("---> {:?}", msg);
            }
            Err(err) => {
                println!("===> {:?}", err);
                continue;
            }
        };

https://pastebin.com/JZqPkmWC

Body:
I solved it by both removing the #[serde(flatten)] and also adding #[serde(untagged)]. Thanks for the help!

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Data {
    Trade(Trade),
    Order(Order),
    None {},
}

#[derive(Serialize, Deserialize, Debug)]
struct Msg {
    channel: String,
    event: String,
    data: Data,
}


问:
Ruby on Rails Routing Question
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

```<code>map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i
</code>```

答:
You can simply create a non-resourceful route:

```<code>get 'event/:id/promotion/:unique_code' => 'event#promotion', :as => 'event_promotion'
</code>```

and the url will be event/32/promotion/AEBCDE with the event_id being 32 and promotion code as 'AEBCDE'

Title: Ruby on Rails Routing Question

Body:
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i

Body:
You can simply create a non-resourceful route:

get 'event/:id/promotion/:unique_code' => 'event#promotion', :as => 'event_promotion'

and the url will be event/32/promotion/AEBCDE with the event_id being 32 and promotion code as 'AEBCDE'


问:
Convert createReducer to switch case reducer
Currently I am using createReducer (https://redux-toolkit.js.org/api/createreducer), but now I am looking forward to convert it into switch case reducer (https://redux.js.org/usage/structuring-reducers/refactoring-reducer-example).
I've tried to convert it, but somehow things are going wrong and I am not sure what's the correct way to handle nested object through switch case reducer

My code with createReducer

```<code>export let sampleReducer = createReducer(initialState, {

  [ACTIONS.ADD_USER]: (state, action) => {
    if (state.user[action.info]) {
      state.user[action.info].details = action.details;
    }
  }
});

export default sampleReducer;
</code>```

Above code is working fine, but when i convert it into switch case, I am not getting the expected response.

New code

```<code>export const sampleReducer = (
  state: sampleState = initialState,
  action
) => {
  switch (action.type) {

    case ACTIONS.ADD_USER:
      if (state.user[action.info]) {
        return {
          ...state
          user: {
            [action.info]: {
              details: action.details
            }

          },
        };
      }

    default:
      return state;
  }
};

export default sampleReducer;
</code>```

Please let me know if new way of writing reducer is correct or not.

答:
Please don't do this!  We want people to use RTK's APIs, and not switch-case functions!

In fact, you shouldn't even be using createReducer in most cases.  The "right" answer here is to use RTK's createSlice API, which will generate the action creators and action types for you:

const sampleSlice = createSlice({
  name: 'sample'
  initialState,
  reducers: {
    userAdded: (state, action) => {
      if (state.user[action.info]) {
        state.user[action.info].details = action.details;
      }
    }
  }
});

export const { userAdded } = sampleSlice.actions;
export default sampleSlice.reducer;
```

Some of our docs pages are older and haven't been updated to show the latest APIs and patterns, but you should be using RTK for everything.

Additionally, the concepts shown in pages like the "Structuring Reducers" section are valid no matter how you actually write the code.

Body:
Currently I am using createReducer (https://redux-toolkit.js.org/api/createreducer), but now I am looking forward to convert it into switch case reducer (https://redux.js.org/usage/structuring-reducers/refactoring-reducer-example).
I've tried to convert it, but somehow things are going wrong and I am not sure what's the correct way to handle nested object through switch case reducer

My code with createReducer

export let sampleReducer = createReducer(initialState, {

  [ACTIONS.ADD_USER]: (state, action) => {
    if (state.user[action.info]) {
      state.user[action.info].details = action.details;
    }
  }
});

export default sampleReducer;

Above code is working fine, but when i convert it into switch case, I am not getting the expected response.

New code

export const sampleReducer = (
  state: sampleState = initialState,
  action
) => {
  switch (action.type) {

    case ACTIONS.ADD_USER:
      if (state.user[action.info]) {
        return {
          ...state
          user: {
            [action.info]: {
              details: action.details
            }

          },
        };
      }

    default:
      return state;
  }
};

export default sampleReducer;

Please let me know if new way of writing reducer is correct or not.

Body:
Please don't do this!  We want people to use RTK's APIs, and not switch-case functions!

In fact, you shouldn't even be using createReducer in most cases.  The "right" answer here is to use RTK's createSlice API, which will generate the action creators and action types for you:

const sampleSlice = createSlice({
  name: 'sample'
  initialState,
  reducers: {
    userAdded: (state, action) => {
      if (state.user[action.info]) {
        state.user[action.info].details = action.details;
      }
    }
  }
});

export const { userAdded } = sampleSlice.actions;
export default sampleSlice.reducer;

Some of our docs pages are older and haven't been updated to show the latest APIs and patterns, but you should be using RTK for everything.

Additionally, the concepts shown in pages like the "Structuring Reducers" section are valid no matter how you actually write the code.


问:
Argparse: Required arguments listed under "optional arguments"?
I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the displayed usage/help text does not indicate that there is a non-optional argument, which I find very confusing. How can I get python to indicate that an argument is not optional?

Here is the code:

```<code>import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Foo')
    parser.add_argument('-i','--input', help='Input file name', required=True)
    parser.add_argument('-o','--output', help='Output file name', default="stdout")
    args = parser.parse_args()
    print ("Input file: %s" % args.input )
    print ("Output file: %s" % args.output )
</code>```

When running above code without providing the required argument, I get the following output:

```<code>usage: foo.py [-h] -i INPUT [-o OUTPUT]

Foo

optional arguments:
    -h, --help            show this help message and exit
    -i INPUT, --input INPUT
                          Input file name
    -o OUTPUT, --output OUTPUT
                          Output file name
</code>```

答:
The required arguments are usually "positional" arguments when using argparse.

```<code>    parser = argparse.ArgumentParser(description="Foo")
    parser.add_argument("username")
    parser.add_argument("password")
</code>```

This will add two positional arguments which are required.

Body:
I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the displayed usage/help text does not indicate that there is a non-optional argument, which I find very confusing. How can I get python to indicate that an argument is not optional?

Here is the code:

import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Foo')
    parser.add_argument('-i','--input', help='Input file name', required=True)
    parser.add_argument('-o','--output', help='Output file name', default="stdout")
    args = parser.parse_args()
    print ("Input file: %s" % args.input )
    print ("Output file: %s" % args.output )

When running above code without providing the required argument, I get the following output:

usage: foo.py [-h] -i INPUT [-o OUTPUT]

Foo

optional arguments:
    -h, --help            show this help message and exit
    -i INPUT, --input INPUT
                          Input file name
    -o OUTPUT, --output OUTPUT
                          Output file name

Body:
The required arguments are usually "positional" arguments when using argparse.

    parser = argparse.ArgumentParser(description="Foo")
    parser.add_argument("username")
    parser.add_argument("password")

This will add two positional arguments which are required.


问:
Iterate through a list and click element (Cucumber/Java)
I have 20 buttons on a single page each one of these buttons has the similar ID of id='gvFobs_DXSelBtn**' where the ** represents the position number of the button so id='gvFobs_DXSelBtn01' for position one and id='gvFobs_DXSelBtn20' for position 20.
I don't want to create a WebElement for each position. I am trying to find a way to list them iterate through each position until I reach the desired position and then click.

Does anyone have any idea on how I can approach this?

答:
I have 20 buttons on a single page each one of these buttons has the similar ID...I don't want to create a WebElement for each position

You will still need to create WebElement instances for each button. Obtaining a list of WebElement objects is not the problem. The problem is what happens after invoking click(). According to the WebElement API

Click this element. If this causes a new page to load, you should discard all references to this element and any further operations performed on this element will throw a StaleElementReferenceException.

This is true for this component and any other WebElement reference obtained before the page reload. This is because after the click event, the entire DOM is invalidated and all WebElement references are considered stale (old) at that time.

What does this mean to you? It means that, if any of those buttons triggers a page reload, this approach won't work. It also mean that even if this solution works in this particular case, it is not guaranteed that it will work on every case and that you should use this approach judiciously.

I strongly recommend against it. The safest way to approach is to have steps to click each button independently.


问:
appending last node in drag and drop
I am using the following code:

```<code>function deleteImage2($item)
{
    $item.fadeOut(function()
    {
        var $list = $('ul',$albumcover).length ? $('ul',$albumcover) : $('<ul class="gallery ui-helper-reset"/>').appendTo($albumcover);
        $item.appendTo($list).fadeIn();
    });
}
</code>```

"albumcover" is name of DIV and this code is working fine, but I need to append last node, how can I modify this query?

Kind Regards

答:
```<code>function deleteImage2($item)
{
    $item.fadeOut(function()
    {
        var $list = ($('ul',$albumcover).length ? $('ul:last',$albumcover) : $('<ul class="gallery ui-helper-reset"/>')).appendTo($albumcover);
        $item.appendTo($list).fadeIn();
    });
}
</code>```

add :last in your selector to select only last item

ContentLicense: CC BY-SA 2.5

Title: appending last node in drag and drop

Body:
I am using the following code:

function deleteImage2($item)
{
    $item.fadeOut(function()
    {
        var $list = $('ul',$albumcover).length ? $('ul',$albumcover) : $('
').appendTo($albumcover);
        $item.appendTo($list).fadeIn();
    });
}

"albumcover" is name of DIV and this code is working fine, but I need to append last node, how can I modify this query?

Kind Regards

Body:
function deleteImage2($item)
{
    $item.fadeOut(function()
    {
        var $list = ($('ul',$albumcover).length ? $('ul:last',$albumcover) : $('<ul class="gallery ui-helper-reset"/>')).appendTo($albumcover);
        $item.appendTo($list).fadeIn();
    });
}

add :last in your selector to select only last item


问:
bounded sum or difference of arrays in numpy
I want to add or subtract two arrays in numpy but the result has to be bounded for each element. If I restrict the typ (i.e. uint8) any exeeding sum produces an overflow (i.e. start from zero again) and any exeeding difference an underflow (i.e. start from 255 again). This is not what I want, i.e. I want to stop at 0/255 (in my example).

Is there any way to do this without accessing each element?

Thank you in advance.

答:
simplified one-liners using np.where as suggested by Aelius, without extra variable and extra type convertions

Bounded add:

```<code>summ = np.where(np.add(a,b, dtype = np.int16)>255,255,a+b)
</code>```

Bounded subtract:

```<code>subb = np.where(np.subtract(a,b, dtype = np.int16)<0,0,a-b)
</code>```

Example:

```<code>import numpy as np
a = np.arange(118,135,dtype = np.uint8)
b = a.copy()

summ = np.where(np.add(a,b, dtype = np.int16)>255,255,a+b)
>>> print(summ)
[236 238 240 242 244 246 248 250 252 254 255 255 255 255 255 255 255]

subb = np.where(np.subtract(a,b[::-1], dtype = np.int16)<0,0,a-b[::-1])
>>> print(subb)
[ 0  0  0  0  0  0  0  0  0  2  4  6  8 10 12 14 16]
</code>```

Body:
simplified one-liners using np.where as suggested by Aelius, without extra variable and extra type convertions

Bounded add:

summ = np.where(np.add(a,b, dtype = np.int16)>255,255,a+b)

Bounded subtract:

subb = np.where(np.subtract(a,b, dtype = np.int16)<0,0,a-b)

Example:

import numpy as np
a = np.arange(118,135,dtype = np.uint8)
b = a.copy()

summ = np.where(np.add(a,b, dtype = np.int16)>255,255,a+b)
>>> print(summ)
[236 238 240 242 244 246 248 250 252 254 255 255 255 255 255 255 255]

subb = np.where(np.subtract(a,b[::-1], dtype = np.int16)<0,0,a-b[::-1])
>>> print(subb)
[ 0  0  0  0  0  0  0  0  0  2  4  6  8 10 12 14 16]


问:
How to save a function result that is always the same to reduce time
I have a function that takes about a minute to be executed, and I want to save the result and somehow check if I have the result stored to avoid executing the whole function everytime.
I was told that the pickle library can help me, but I've never used it, and I don't know if it can be helpful in this situation.

The result format is two lists

```<code>x=[27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125, ...]
y=['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC', ...]
</code>```

Edit:
I want to save the result in a file and check if the result is stored to get it from the file instead of executing the function

答:
You could create a decorator to wrap your existing function, so that each time you call it with the same parameters, it bypasses the function call and returns the existing value.

from functools import wraps

def memoize(f):
    cache = {}
    @wraps(f)
    def wrapper(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return wrapper

@memoize
def func(x, y, z):
    #long expensive calculation
    return x+y+z
```

Body:
I have a function that takes about a minute to be executed, and I want to save the result and somehow check if I have the result stored to avoid executing the whole function everytime.
I was told that the pickle library can help me, but I've never used it, and I don't know if it can be helpful in this situation.

The result format is two lists

x=[27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125, ...]
y=['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC', ...]

Edit:
I want to save the result in a file and check if the result is stored to get it from the file instead of executing the function


问:
sort a singly linked list formed of 1, 2 and 0s by swapping the nodes through one traversal in C
I'm trying to solve the question that I need to sort a given linked list which values consist of 1, 2 and 0 by traversing the list only once and I need to swap the nodes not values.
my code is:

```<code>    #define max 3

void sortList(node **headRef)
{
    if(*headRef==NULL){
        return;
    }
    node* head[max];
    node*tail[max];
    node* curr=*headRef;
    int i;
    for(i=0; i<max; i++){
        head[i]=tail[i]=NULL;
    }
    while(curr!=NULL){
        i=curr->data;
        if(head[i]==NULL){
            head[i]=tail[i]=curr;
        }
        else{
            tail[i]=tail[i]->next=curr;
        }
        curr=curr->next;
    }
    for(int i=0, curr=(*headRef)=NULL; i<max; i++){
        if(head[i]!=NULL){
            if(*headRef==NULL){
                *headRef=head[i];
            }
            else{
                curr = curr->next =head[i];
            }
            curr=tail[i];
        }

    }
    curr->next=NULL;
}
</code>```

but it keep giving me an error and I don't know how to solve it if anyone can help me please.

答:
Your problem is this:

```<code>for(int i=0, curr=(*headRef)=NULL; i<max; i++)
             ^^^^^^^ here ^^^^^^^
</code>```

And you solve it by better-understanding the features of the language you're using before you use them. The optional declaration + initialization part of a for-loop allows you to not only initialize, but also declare variables (and in this case, shadow/hide existing variables). The above will declare two loop-scope int variables: i and curr, initializing the first to 0, and the second to the expression result of (*headRef)=NULL, which for near-all C implementations, will be equivalent to (void*)0. But now curr is an int, and the previous declaration of curr as a node pointer is hidden. Therefore, this:

```<code>curr = curr->next =head[i];
</code>```

is now nonsense.

Change your code to this:

```<code>curr=(*headRef)=NULL;
for(int i=0; i<max; i++)
</code>```

and it should work.

Body:
I'm trying to solve the question that I need to sort a given linked list which values consist of 1, 2 and 0 by traversing the list only once and I need to swap the nodes not values.
my code is:

    #define max 3

void sortList(node **headRef)
{
    if(*headRef==NULL){
        return;
    }
    node* head[max];
    node*tail[max];
    node* curr=*headRef;
    int i;
    for(i=0; i<max; i++){
        head[i]=tail[i]=NULL;
    }
    while(curr!=NULL){
        i=curr->data;
        if(head[i]==NULL){
            head[i]=tail[i]=curr;
        }
        else{
            tail[i]=tail[i]->next=curr;
        }
        curr=curr->next;
    }
    for(int i=0, curr=(*headRef)=NULL; i<max; i++){
        if(head[i]!=NULL){
            if(*headRef==NULL){
                *headRef=head[i];
            }
            else{
                curr = curr->next =head[i];
            }
            curr=tail[i];
        }

    }
    curr->next=NULL;
}

but it keep giving me an error and I don't know how to solve it if anyone can help me please.

Body:
Your problem is this:

for(int i=0, curr=(*headRef)=NULL; i<max; i++)
             ^^^^^^^ here ^^^^^^^

And you solve it by better-understanding the features of the language you're using before you use them. The optional declaration + initialization part of a for-loop allows you to not only initialize, but also declare variables (and in this case, shadow/hide existing variables). The above will declare two loop-scope int variables: i and curr, initializing the first to 0, and the second to the expression result of (*headRef)=NULL, which for near-all C implementations, will be equivalent to (void*)0. But now curr is an int, and the previous declaration of curr as a node pointer is hidden. Therefore, this:

curr = curr->next =head[i];

is now nonsense.

Change your code to this:

curr=(*headRef)=NULL;
for(int i=0; i<max; i++)

and it should work.


答:
NOTE: These routes are for Rails 3.  I probably should have asked what version you were using first :-)

Is Promotion a join table between Events and Promoters?  If that's the case you could simply use the Promotion resource to track both.

If that's not the case, multiple params in a route is a simple matter handled in several ways.

You could nest resources, e.g.

```<code>resources :events do
  resources :promotions
end

# which would result in urls like /events/:event_id/promotions/:id
</code>```

Or you could map them yourself like

```<code>get "/events/:event_id/promos/:promoter_code", :to => "events#show"

# Which would manually map the route to events_controller#show, passing along your
# event id and a unique promoter code.  Just an example, but you get the idea.
</code>```

Title: Ruby on Rails Routing Question

Body:
NOTE: These routes are for Rails 3.  I probably should have asked what version you were using first :-)

Is Promotion a join table between Events and Promoters?  If that's the case you could simply use the Promotion resource to track both.

If that's not the case, multiple params in a route is a simple matter handled in several ways.

You could nest resources, e.g.

resources :events do
  resources :promotions
end

# which would result in urls like /events/:event_id/promotions/:id

Or you could map them yourself like

get "/events/:event_id/promos/:promoter_code", :to => "events#show"

# Which would manually map the route to events_controller#show, passing along your
# event id and a unique promoter code.  Just an example, but you get the idea.


问:
Import XML file in R without opening tag
I'm making a script in R that downloads, extracts the data straight from a web address and imports it into R automatically. The problem is that the file imported in XML format does not contain the opening tag. Is it possible to open an XML file without the opening tag or automatically, with R, include an opening tag before importing the file in R, without doing this manually? The file I'm trying to import is '20220207_Pedidos_xml_2015.xml' available in https://dadosabertos-download.cgu.gov.br/FalaBR/Arquivos_FalaBR_Filtrado/Arquivos_xml_2015.zip

```<code>library(XML)
txt = readLines("F:/Meu repositório/logo dail/20220206_Pedidos_xml_2015.xml", encoding = 'UTF-16LE')
xml = xmlTreeParse(txt, useInternalNodes=TRUE)
</code>```

Error:

```<code>> xml = xmlTreeParse(txt, useInternalNodes=TRUE)
Start tag expected, '<' not found
Error: 1: Start tag expected, '<' not found
</code>```

答:
The file you identified looks perfectly well-formed to me. Oxygen opens it without complaint (except for warnings saying do you really want to open such a large XML file).

I suspect you've misdiagnosed the problem. For example, are you sure the encoding is UTF-16LE (I haven't checked).

Body:
I'm making a script in R that downloads, extracts the data straight from a web address and imports it into R automatically. The problem is that the file imported in XML format does not contain the opening tag. Is it possible to open an XML file without the opening tag or automatically, with R, include an opening tag before importing the file in R, without doing this manually? The file I'm trying to import is '20220207_Pedidos_xml_2015.xml' available in https://dadosabertos-download.cgu.gov.br/FalaBR/Arquivos_FalaBR_Filtrado/Arquivos_xml_2015.zip

library(XML)
txt = readLines("F:/Meu repositório/logo dail/20220206_Pedidos_xml_2015.xml", encoding = 'UTF-16LE')
xml = xmlTreeParse(txt, useInternalNodes=TRUE)

Error:

> xml = xmlTreeParse(txt, useInternalNodes=TRUE)
Start tag expected, '<' not found
Error: 1: Start tag expected, '<' not found


问:
Google Cloud PubSub Lite subscription in C#
I'm writing a software with C# language and I need to create a subscription to a Pub/Sub Lite in Google Cloud.
I understood that I can't user the Google.Cloud.PubSub.V1 nuget package because it doesn't work with the Lite version.
I found Google.Apis.PubsubLite.V1 nuget package but I haven't found an example of how I can create a subscription and read data from the Pub/Sub Lite.
How I can do that?</p>

答:
You can create a Lite subscription with the Cloud Console, the Google Cloud CLI, or the Pub/Sub Lite API following these next couple of steps:

Go to the Lite Subscriptions page.

Click Create Lite subscription.

Enter a Lite subscription ID.

Choose a Lite topic to receive messages from.

Choose Deliver messages immediately or Deliver messages after stored.

Choose a type of Starting offset.

Click Create.

Also if you want to read from a subscription using a pull, you can try the example code in this asynchronous pull method, but note that it might need some changes as you are using the pubsublite library instead of the pubsub library and some things might change between libraries.


问:
In Kubernetes, are podAffinity and podAntiAffinity weights compared to each other? Or idependently? What about podAffinity and nodeAffinity?
In Kubernetes, are podAffinity and podAntiAffinity weights compared to each other? Or independently? What about podAffinity and nodeAffinity? Would podAntiAffinity outweight the podAffinity in the below example? And what if nodeAffinity was added to the mix as well.

```<code> affinity:
  podAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 50
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app.kubernetes.io/name
            operator: In
            values:
            - test-1
        topologyKey: kubernetes.io/hostname

  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 100
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app.kubernetes.io/name
            operator: In
            values:
            - test-2
        topologyKey: kubernetes.io/hostname
</code>```

答:
All affinity settings for both pods and nodes are weighed the same way if you don't overwrite the default individual weight of 1.

During execution the occurrence of affinity conditions on a node is multiplied by the weight of the condition.

```<code>pod a has an affinity to b
pod a has an anti-affinity to c

new pod of type "a" to be scheduled
---
node1 runs 3 "b" pods and 1 "c" pod --> affinity score: 2 (3 "b" pods - 1 "c" pod)
node2 runs 1 "b" pod --> affinity score 1: 1 (1 "b" pod)
</code>```

Based on the affinity calculation the pod will be scheduled on node1 despite it already running pod "c" as 3 "b" pods outweigh 1 "c" pod.

In your example the anti-affinity would outweigh the affinity settings if there is a 1:1 ratio of test-1 to test-2 on a node. With a 2:1 ratio of test-1 to test-2 on a node the (anti-)affinities would cancel each other out.

Source

Body:
In Kubernetes, are podAffinity and podAntiAffinity weights compared to each other? Or independently? What about podAffinity and nodeAffinity? Would podAntiAffinity outweight the podAffinity in the below example? And what if nodeAffinity was added to the mix as well.

 affinity:
  podAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 50
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app.kubernetes.io/name
            operator: In
            values:
            - test-1
        topologyKey: kubernetes.io/hostname

  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 100
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app.kubernetes.io/name
            operator: In
            values:
            - test-2
        topologyKey: kubernetes.io/hostname

Body:
All affinity settings for both pods and nodes are weighed the same way if you don't overwrite the default individual weight of 1.

During execution the occurrence of affinity conditions on a node is multiplied by the weight of the condition.

pod a has an affinity to b
pod a has an anti-affinity to c

new pod of type "a" to be scheduled
---
node1 runs 3 "b" pods and 1 "c" pod --> affinity score: 2 (3 "b" pods - 1 "c" pod)
node2 runs 1 "b" pod --> affinity score 1: 1 (1 "b" pod)

Based on the affinity calculation the pod will be scheduled on node1 despite it already running pod "c" as 3 "b" pods outweigh 1 "c" pod.

In your example the anti-affinity would outweigh the affinity settings if there is a 1:1 ratio of test-1 to test-2 on a node. With a 2:1 ratio of test-1 to test-2 on a node the (anti-)affinities would cancel each other out.

Source


问:
I have to determine if model has more than 4 objects or less
If Model has more than 4 than everything works fine. but if there is less than 4 .count() returns 0

```<code>posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count()
            print(posts_num)
            if posts_num >= 4:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4]
            else:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:posts_num]
            current_user = self.request.user.id

    context["page_author_post"] = page_author_post
</code>```

答:
You don't have to use the slicing using [:posts_num] in else condition. It is already is in the else condition, which means posts_num will always be less than 4 (i.e, 1 or 2 or 3).

Your code would be like:

```<code>posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count()
            print(posts_num)
            if posts_num >= 4:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4]
            else:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date') # observe the change here
            current_user = self.request.user.id

    context["page_author_post"] = page_author_post
</code>```

Body:
If Model has more than 4 than everything works fine. but if there is less than 4 .count() returns 0

posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count()
            print(posts_num)
            if posts_num >= 4:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4]
            else:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:posts_num]
            current_user = self.request.user.id

    context["page_author_post"] = page_author_post

Body:
You don't have to use the slicing using [:posts_num] in else condition. It is already is in the else condition, which means posts_num will always be less than 4 (i.e, 1 or 2 or 3).

Your code would be like:

posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count()
            print(posts_num)
            if posts_num >= 4:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4]
            else:
                page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date') # observe the change here
            current_user = self.request.user.id

    context["page_author_post"] = page_author_post


答: Using rows={2} is the right call. Look for any css rule that limits the max height of the textarea or a parent element that does this.</p>

Title: Passing integers to JSX attributes

Body:
return <textarea className="tox-input" rows=2 ></textarea>;

I want to pass rows=2 to this tag. However, this results in the following error.

Parsing error: JSX value should be either an expression or a quoted JSX text.

After a bit of research, I couldn't find a way to solve this. Please could someone tell me the proper way to do it in JSX?

Note: Using rows={2} doesn't give an error, but it only shows one row.


问:
How could " possibly be the returned value for a new user
I have a form that I am trying to implement that creates a new user in the database. For some reason when it executes the controller function its returning " for the email address and returns me back to the view with a UserManager validation error. But I dont possibly see how it could be returning " when I can see its posting the email from the view.

```<code>    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Identity;
    using Rabbit.Application.Models;
    using System.Threading.Tasks;
    using Rabbit.Application.Identity.Models;

    namespace Rabbit.Application.Identity.Controllers
    {

        public class AdminController : Controller
        {
            private UserManager<ApplicationUser> _userManager;

            public AdminController(UserManager<ApplicationUser> usrMgr)
            {
                _userManager = usrMgr;
            }

            public IActionResult Index()
            {
                return View(_userManager.Users);
            }

            public ViewResult Create() => View();

            [HttpPost]
            public async Task<IActionResult> Create(User input)
            {
                if (ModelState.IsValid)
                {
                    var appUser = new ApplicationUser
                    {
                        UserName = input.Name,
                        FirstName = input.FirstName,
                        LastName = input.LastName,
                        Email = input.Email,

                    };

                    var result = await _userManager.CreateAsync(appUser, input.Password);
                    if (result.Succeeded)
                        return RedirectToAction("Index");
                    else
                    {
                        foreach (var error in result.Errors)
                            //if (error.Code == "DuplicateUserName") continue;
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                return View(input);
            }
        }
    }
</code>```

View

```<code>@using Rabbit.Application.Models
@model User
  @section Scripts {
    <partial name="_ValidationScriptsPartial"/>
}
@{
    ViewData["Title"] = "Create";
}
<h1 class="bg-info text-white">Create User</h1>
<a asp-controller="Admin" asp-action="Index" class="btn btn-secondary">Back</a>
<div asp-validation-summary="All" class="text-danger"></div>

<form asp-controller="Admin" asp-action="Create" method="post">

                  <div class="form-group">
                        <div class="input-group input-group-alternative mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">
                                    <i class="ni ni-circle-08"></i>
                                </span>
                            </div>
                            <input asp-for="Email" type="text" class="form-control" placeholder="Email" autocomplete="email" />

                        </div>
                        <span asp-validation-for="Email" class="invalid-feedback" style="display: block"></span>
                    </div>
                 <div class="form-group">
                        <div class="input-group input-group-alternative mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">
                                    <i class="ni ni-circle-08"></i>
                                </span>
                            </div>
                            <input asp-for="Password" class="form-control" placeholder="Password" />

                        </div>
                        <span asp-validation-for="Password" class="invalid-feedback" style="display: block"></span>
                    </div>

    <button type="submit" class="btn btn-primary">Create</button>
    </form>
</code>```

答:
Not sure what was causing " to be entered but I recoded the routing through the controller and everything started working normally. I believe it was trying to load the post method and bypass the initial call for Create()=> View();
This was likely due to being new and not fully understanding routing and was receiving bogus results that would likely be very difficult to track down. Once I took a step back to learn more about how the controller and model work in conjunction with the view from a routing aspect I was able to get everything I was doing working correctly.

Body:
I have a form that I am trying to implement that creates a new user in the database. For some reason when it executes the controller function its returning " for the email address and returns me back to the view with a UserManager validation error. But I dont possibly see how it could be returning " when I can see its posting the email from the view.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Identity;
    using Rabbit.Application.Models;
    using System.Threading.Tasks;
    using Rabbit.Application.Identity.Models;

    namespace Rabbit.Application.Identity.Controllers
    {

        public class AdminController : Controller
        {
            private UserManager<ApplicationUser> _userManager;

            public AdminController(UserManager<ApplicationUser> usrMgr)
            {
                _userManager = usrMgr;
            }

            public IActionResult Index()
            {
                return View(_userManager.Users);
            }

            public ViewResult Create() => View();

            [HttpPost]
            public async Task<IActionResult> Create(User input)
            {
                if (ModelState.IsValid)
                {
                    var appUser = new ApplicationUser
                    {
                        UserName = input.Name,
                        FirstName = input.FirstName,
                        LastName = input.LastName,
                        Email = input.Email,

                    };

                    var result = await _userManager.CreateAsync(appUser, input.Password);
                    if (result.Succeeded)
                        return RedirectToAction("Index");
                    else
                    {
                        foreach (var error in result.Errors)
                            //if (error.Code == "DuplicateUserName") continue;
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                return View(input);
            }
        }
    }

View

@using Rabbit.Application.Models
@model User
  @section Scripts {
    <partial name="_ValidationScriptsPartial"/>
}
@{
    ViewData["Title"] = "Create";
}

Create User

Back

<form asp-controller="Admin" asp-action="Create" method="post">

                            <input asp-for="Email" type="text" class="form-control" placeholder="Email" autocomplete="email" />

                            <input asp-for="Password" class="form-control" placeholder="Password" />

    <button type="submit" class="btn btn-primary">Create</button>
    </form>


问:
How much footprint does C++ exception handling add
This issue is important especially for embedded development. Exception handling adds some footprint to generated binary output. On the other hand, without exceptions the errors need to be handled some other way, which requires additional code, which eventually also increases binary size.

I'm interested in your experiences, especially:

What is average footprint added by your compiler for the exception handling (if you have such measurements)?

Is the exception handling really more expensive (many say that), in terms of binary output size, than other error handling strategies?

What error handling strategy would you suggest for embedded development?

Please take my questions only as guidance. Any input is welcome.

Addendum:  Does any one have a concrete method/script/tool that, for a specific C++ object/executable, will show the percentage of the loaded memory footprint that is occupied by compiler-generated code and data structures dedicated to exception handling?

答:
Define 'embedded'.  On an 8-bit processor I would not certainly not work with exceptions (I would certainly not work with C++ on an 8-bit processor).  If you're working with a PC104 type board that is powerful enough to have been someone's desktop a few years back then you might get away with it.  But I have to ask - why are there exceptions?  Usually in embedded applications anything like an exception occurring is unthinkable - why didn't that problem get sorted out in testing?

For instance, is this in a medical device?  Sloppy software in medical devices has killed people.  It is unacceptable for anything unplanned to occur, period.  All failure modes must be accounted for and, as Joel Spolsky said, exceptions are like GOTO statements except you don't know where they're called from.  So when you handle your exception, what failed and what state is your device in?  Due to your exception is your radiation therapy machine stuck at FULL and is cooking someone alive (this has happened IRL)?  At just what point did the exception happen in your 10,000+ lines of code.  Sure you may be able to cut that down to perhaps 100 lines of code but do you know the significance of each of those lines causing an exception is?

Without more information I would say do NOT plan for exceptions in your embedded system.  If you add them then be prepared to plan the failure modes of EVERY LINE OF CODE that could cause an exception.  If you're making a medical device then people die if you don't.  If you're making a portable DVD player, well, you've made a bad portable DVD player.  Which is it?

OwnerDisplayName: o-l-o

OwnerDisplayName: Stephen Friederichs


问:
Resolving rotation about an arbitary axis into rotation about X, Y and Z axis
I am currently trying to implement a virtual arcball in OpenGL utilizing GLUT library.
As of now I am calculating the axis of rotation and angle of rotation by doing standard arcball computation on old and new coordinates of the mouse. But I want to obtain the angle theta1, theta2, theta3 , such that rotation of the object about X axis by theta1 , about Y axis by theta2 and about Z axis by theta3 would yield the same effect as before.</p>

答:
A better way to do the job is to convert the spatial rotation about an axis passing through origin to unit quartenions. Unit quartenions can easily be converted into euler angles without any ambiguity. More information on conversion can be found here http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles.

Thanks for all the help!


问:
Unable to connect to mysql using jdbc in docker
I have the following docker-compose:

```<code>version: '3.1'
services:
  db:
    container_name: db
    image: mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=world
    volumes:
      - ./mysql-db/:/docker-entrypoint-initdb.d
    networks:
      - my-network
  app:
    depends_on:
      - db
    container_name: app
    build: App/
    networks:
      - my-network
networks:
  my-network:
    driver: bridge
</code>```

This builds the mysql image and uses a local file to create the database. I am able to connect to the database through a database client on my host machine. I know the db is running and working with those credentials on port 3306.

App/Dockerfile:

```<code># Build stage
FROM maven:latest AS build
COPY src /app/src
COPY pom.xml /app
# need to assemble to package in plugins
RUN mvn -f /app/pom.xml clean compile assembly:single

# Package stage
FROM openjdk:latest
COPY --from=build /app/target/seMethods-1.0-jar-with-dependencies.jar /usr/local/lib/build.jar
ENTRYPOINT ["java", "-jar", "/usr/local/lib/build.jar"]
</code>```

This builds the jar file using maven.

App/src/App.java

// sql imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class App
{
  public static void main( String[] args )
  {
    try {
      String dbUrl = "jdbc:mysql://db:3306/world";
      Connection con = DriverManager.getConnection(dbUrl,"root","password");

      String testStatement = "SELECT * FROM city;";
      PreparedStatement preparedTest = con.prepareStatement(testStatement);
      ResultSet rs = preparedTest.executeQuery();

      while(rs.next()){
        System.out.println(rs.getRow());
      }

    } catch (Exception e) {
      // handle any errors
      System.out.println(String.format("Error: %s", e));
    }
  }
}
```
<p>When my docker-compose runs, the containers are created although my app stops with the following:</p>
```Error: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
```

How can I connect my db container to app?

答:
Solved.

When creating the db image, the init file used to generate the inital database took a few seconds to complete. Adding a Thread.sleep() hotfix to the start of my java app allowed the database tables to be created and then I am able to connect.

Body:
I have the following docker-compose:

version: '3.1'
services:
  db:
    container_name: db
    image: mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=world
    volumes:
      - ./mysql-db/:/docker-entrypoint-initdb.d
    networks:
      - my-network
  app:
    depends_on:
      - db
    container_name: app
    build: App/
    networks:
      - my-network
networks:
  my-network:
    driver: bridge

This builds the mysql image and uses a local file to create the database. I am able to connect to the database through a database client on my host machine. I know the db is running and working with those credentials on port 3306.

App/Dockerfile:

# Build stage
FROM maven:latest AS build
COPY src /app/src
COPY pom.xml /app
# need to assemble to package in plugins
RUN mvn -f /app/pom.xml clean compile assembly:single

# Package stage
FROM openjdk:latest
COPY --from=build /app/target/seMethods-1.0-jar-with-dependencies.jar /usr/local/lib/build.jar
ENTRYPOINT ["java", "-jar", "/usr/local/lib/build.jar"]

This builds the jar file using maven.

App/src/App.java

// sql imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class App
{
  public static void main( String[] args )
  {
    try {
      String dbUrl = "jdbc:mysql://db:3306/world";
      Connection con = DriverManager.getConnection(dbUrl,"root","password");

      String testStatement = "SELECT * FROM city;";
      PreparedStatement preparedTest = con.prepareStatement(testStatement);
      ResultSet rs = preparedTest.executeQuery();

      while(rs.next()){
        System.out.println(rs.getRow());
      }

    } catch (Exception e) {
      // handle any errors
      System.out.println(String.format("Error: %s", e));
    }
  }
}

When my docker-compose runs, the containers are created although my app stops with the following:

Error: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

How can I connect my db container to app?


问:
C comparison between -1 and 65535/4294967295/18446744073709551615
I have a misunderstanding about the following statements:

```<code>printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);
</code>```

The output is:

```<code>0
0
0
1
</code>```

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

答:
This is due to how integer constants are treated.

For decimal constants with no suffix, the compiler checks the value to see if it will fit into the following types, in this order:

int

long int

long long int

The compiler gives you a warning because the value 18446744073709551615 will not fit into any of those types.  What happens next is dictated by section 6.4.4.1p6 of the C standard:

If an integer constant cannot be represented by any type in its list,
it may have an extended integer type, if the extended integer type can
represent its value. If all of the types in the list for the constant
are signed, the extended integer type shall be signed. If all of the
types in the list for the constant are unsigned, the extended integer
type shall be unsigned. If the list contains both signed and unsigned
types, the extended integer type may be signed or unsigned. If an
integer constant cannot be represented by any type in its list and has
no extended integer type, then the integer constant has no type

And since 18446744073709551615 doesn't fit into one of the above types, the compiler will attempt to fit the value into a signed extended type if one exists.  GCC in particular supports a type called __int128 , so assuming you're using GCC then the constant has that type.

Then for the comparison -1 == 18446744073709551615, the left side of the comparison is converted to type __int128 which it can do without a change of value, and the result is false.

In the case of the constant 18446744073709551615UL, the suffix gives it type unsigned long and the value does fit into that type.  Then for the comparison -1 == 18446744073709551615UL, -1 is converted to type unsigned long.  By the rules of converting an out-of-range signed type to an unsigned type, the int value -1 is converted to the unsigned long value 18446744073709551615 and the comparison is true.

The warning generated by gcc is misleading in that it suggests that the constant is unsigned when it actually is not.  This may be a reference to C89 behavior where this constant would in fact have type unsigned long.   If the -std=c89 flag is passed to gcc, you'll get another warning in addition to the first:  warning: this decimal constant is unsigned only in ISO C90.  The results will also differ because of this, with the third call to printf outputting 1.

Body:
I have a misunderstanding about the following statements:

printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);

The output is:

0
0
0
1

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks


问:
Python "protected" attributes
How do I access a private attribute of a parent class from a subclass (without making it public)?</p>

答:
Code modified from geeksforgeeks

```<code># program to illustrate protected
# data members in a class

# Defining a class
class Geek:
    # private
    __name = "R2J"
    # protected data members
    _roll = 1706256
    def __init__(self, value):
        value1 = value
        self.value2 = value
    # public member function
    def displayNameAndRoll(self):

        # accessing protected data members
        print("Name: ", self.__name)
        print("Roll: ", self._roll)

# creating objects of the class
obj = Geek(1)
obj.__name = 'abc'
obj._roll = 12345

# calling public member
# functions of the class
obj.displayNameAndRoll()
</code>```

Note that I can modifies without setter the protected attribute, but not the private.

```<code>Name:  R2J
Roll:  12345
</code>```

OBS: running in python 3.8

Title: Python "protected" attributes

Body:
Code modified from geeksforgeeks

# program to illustrate protected
# data members in a class

# Defining a class
class Geek:
    # private
    __name = "R2J"
    # protected data members
    _roll = 1706256
    def __init__(self, value):
        value1 = value
        self.value2 = value
    # public member function
    def displayNameAndRoll(self):

        # accessing protected data members
        print("Name: ", self.__name)
        print("Roll: ", self._roll)

# creating objects of the class
obj = Geek(1)
obj.__name = 'abc'
obj._roll = 12345

# calling public member
# functions of the class
obj.displayNameAndRoll()

Note that I can modifies without setter the protected attribute, but not the private.

Name:  R2J
Roll:  12345

OBS: running in python 3.8


问:
Mixing Azure AD and Azure AD B2C Authentication within same reactjs app and aspnet core web api
How do we mix Azure AD and Azure AD B2C in same app? I am building an app which should be accessible to employees and customers. My requirement is to authenticate internal users(like employees) with Azure AD and external users(customers) with Azure AD B2C.

What do I know so far.
I can build two web apis(with just differing Startup.cs), the same can be done at reactjs as well - This is not ideal

Code in index.js of react app

```<code>import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from './config';
const msalInstance = new PublicClientApplication(msalConfig);

ReactDOM.render(
  <Fragment>
    <StrictMode>
      <MsalProvider instance={msalInstance}>
        <Provider store={store}>
          <App />
        </Provider>
      </MsalProvider>
    </StrictMode>
  </Fragment>,
  document.getElementById('root')
);
</code>```

Current Code in Startup.cs os aspnet core api

```<code>// 'AzureAd' and 'AzureAdB2C' is configured in appsettings.json
services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");
// + services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAdB2C"); <---- Would this work?
services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
</code>```

答:
Federate Azure AD to Azure AD B2C.
Users can then click a button on AAD B2C login page to login with their AAD account. Your app just needs to understand AAD B2C as a login provider. Much simpler.

https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-azure-ad-single-tenant?pivots=b2c-custom-policy

Body:
How do we mix Azure AD and Azure AD B2C in same app? I am building an app which should be accessible to employees and customers. My requirement is to authenticate internal users(like employees) with Azure AD and external users(customers) with Azure AD B2C.

What do I know so far.
I can build two web apis(with just differing Startup.cs), the same can be done at reactjs as well - This is not ideal

Code in index.js of react app

import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from './config';
const msalInstance = new PublicClientApplication(msalConfig);

ReactDOM.render(
  <Fragment>
    <StrictMode>
      <MsalProvider instance={msalInstance}>
        <Provider store={store}>
          <App />
        </Provider>
      </MsalProvider>
    </StrictMode>
  </Fragment>,
  document.getElementById('root')
);

Current Code in Startup.cs os aspnet core api

// 'AzureAd' and 'AzureAdB2C' is configured in appsettings.json
services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");
// + services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAdB2C"); <---- Would this work?
services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();


问:
Unknown column in fieldlist error when joining tables
can someone please help me fix this query. Whenever I run it I keep getting the unknown fieldlist error.</p>
```<code>SELECT
 busline.line_id,
 plz.city AS startpoint,
 plz.city AS endpoint
FROM
 busline
INNER JOIN
 plz as sp ON buslinie.startstation = sp.plz_id
INNER JOIN
 plz as ep ON buslinie.endstation = ep.plz_id
</code>```

答:
```<code>SELECT
 bl.line_id,
 sp.city AS startpoint,
 ep.city AS endpoint
FROM
 busline bl
INNER JOIN
 plz as sp ON bl.startstation = sp.plz_id
INNER JOIN
 plz as ep ON bl.endstation = ep.plz_id
</code>```

Body:
can someone please help me fix this query. Whenever I run it I keep getting the unknown fieldlist error.

SELECT
 busline.line_id,
 plz.city AS startpoint,
 plz.city AS endpoint
FROM
 busline
INNER JOIN
 plz as sp ON buslinie.startstation = sp.plz_id
INNER JOIN
 plz as ep ON buslinie.endstation = ep.plz_id


问:
How to seperate Array in Haskell
i just learn about haskell
but i've problem about Type Data, ihave type data like below

```<code>[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]
</code>```

my question is how to seperate to =

```<code>Name  Address  Score Pass
-------------------------
name1 Address1 80    Y
name2 Address2 60    N
</code>```

i've try

```<code>printArray :: [Test] -> IO()
printArray [Test x y z]  = do
                                putStr x
                                putStr (" " ++ y)
                                putStr (" " ++ show z)
                                if z >= 70 then putStrLn " Y"
                                else putStrLn " N"
</code>```

but when i executed i got error : Non-exhaustive patterns in function printArray

Thanks in advance

答:
This is wrong. You pattern-match the singleton list containing just one element [Test x y z].</p>
```<code>printArray :: [Test] -> IO ()
printArray []  = pure ()
printArray (Test x y z : xs)  = do
  putStr x
  putStr (" " ++ y)
  putStr (" " ++ show z)
  if z >= 60
    then putStrLn " Y"
    else putStrLn " N"
  printArray xs
</code>```

Title: How to seperate Array in Haskell

Body:
i just learn about haskell
but i've problem about Type Data, ihave type data like below

[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]

my question is how to seperate to =

Name  Address  Score Pass
-------------------------
name1 Address1 80    Y
name2 Address2 60    N

i've try

printArray :: [Test] -> IO()
printArray [Test x y z]  = do
                                putStr x
                                putStr (" " ++ y)
                                putStr (" " ++ show z)
                                if z >= 70 then putStrLn " Y"
                                else putStrLn " N"

but when i executed i got error : Non-exhaustive patterns in function printArray

Thanks in advance

Body:
This is wrong. You pattern-match the singleton list containing just one element [Test x y z].

printArray :: [Test] -> IO ()
printArray []  = pure ()
printArray (Test x y z : xs)  = do
  putStr x
  putStr (" " ++ y)
  putStr (" " ++ show z)
  if z >= 60
    then putStrLn " Y"
    else putStrLn " N"
  printArray xs


问:
Filling the NaN values in the column dataframe based on condition python pandas
I am trying to update my dataframe column value based on the condition but when i check my data frame its value is not getting updated.

```<code>for i in titanic['Survived'].unique():
meanAge = titanic.Age[titanic['Survived'] == i].mean()
meanAge = "{:.1f}".format(meanAge)
df = titanic['Survived'] == i
df1 = titanic.Age[df];
df1.fillna(meanAge, inplace=True)
#print (df1) the value seems to be updated here
</code>```

but print(titanic still shows NAN values.

答:
The reason is that most likely df1 is a copied object from the dataframe, and it does not reference the titanic dataframe.

It will probably help you to do like below (just replace the condition with one that includes NaN values). So instead of calling the method fillna just use the assignment operator with the proper index.

```<code>titanic.Age[titanic['Survived'] == i] = meanAge
</code>```

If you don't have memory constraints is better to think about dataframes as immutable.

Instead of updating in place, try to make a copy of the original and update the new one.

Body:
I am trying to update my dataframe column value based on the condition but when i check my data frame its value is not getting updated.

for i in titanic['Survived'].unique():
meanAge = titanic.Age[titanic['Survived'] == i].mean()
meanAge = "{:.1f}".format(meanAge)
df = titanic['Survived'] == i
df1 = titanic.Age[df];
df1.fillna(meanAge, inplace=True)
#print (df1) the value seems to be updated here

but print(titanic still shows NAN values.

Body:
The reason is that most likely df1 is a copied object from the dataframe, and it does not reference the titanic dataframe.

It will probably help you to do like below (just replace the condition with one that includes NaN values). So instead of calling the method fillna just use the assignment operator with the proper index.

titanic.Age[titanic['Survived'] == i] = meanAge

If you don't have memory constraints is better to think about dataframes as immutable.

Instead of updating in place, try to make a copy of the original and update the new one.