text:
Q: Differentiating between plots in a grouped barplot using ggpattern I've been trying to differentiate between the patient and the medic values of my grouped barplot using ggpattern. I have been trying to have one bar shaded and the other blank but it has not worked out. I keep getting this output:
This is the code I used:
<hpvcom %>% select(HPV.Result, Result) %>%
group_by(HPV.Result, Result) %>%
summarise(sum_result = n()) %>%
ggplot(mapping = aes(x = Result, y = sum_result, fill = Result)) +
ggpattern::geom_bar_pattern(stat="identity", position = position_dodge(preserve = "single"),  fill = "white",
                            colour          = 'black',
                            pattern_density = 0.35,
                            pattern_fill    = 'black',
                            pattern_colour  = 'black', alpha= 1) +
scale_y_log10()+
geom_text(mapping = aes(label = paste0( "n:",sum_result)), position = position_dodge(width = 0.9), cex = 3.5, vjust = 1.5, color = "yellow") +
scale_x_discrete(labels = c("Medic", "Patient")) +
theme_classic2()+
theme(panel.grid = element_blank()) +
theme_pubr() +
facet_wrap(~ HPV.Result, scales = "free") +
xlab("") +
ylab("")+
theme(plot.title = element_text(hjust = 0.5))+
theme(legend.position = "none")>

This is the data:
<> copy_to(dput(hpvcom))
structure(list(HPV.Result = c("HPV 16 Positive", "HPV 16 Positive",
"HPV 16 Positive", "HPV 16 Positive", "HPV 16 Positive", "HPV 18 Positive",
"HPV 18 Positive", "HPV 18 Positive", "HPV 18 Positive", "HPV 18 Positive",
"HPV 18 Positive", "HPV 18 Positive", "HPV 18 Positive", "HPV 18 Positive",
"HPV 18 & OHR Positive", "HPV 18 & OHR Positive", "HPV 18 & OHR Positive",
"HPV 18 & OHR Positive", "HPV 18 & OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive", "HPV OHR Positive",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "HPV Negative", "HPV Negative",
"HPV Negative", "HPV Negative", "Invalid Result", "Invalid Result",
"Invalid Result", "Invalid Result", "Invalid Result", "Invalid Result",
"Invalid Result", "Invalid Result", "Invalid Result", "Invalid Result",
"Invalid Result", "Invalid Result", "Invalid Result", "Invalid Result",
"Invalid Result", "Invalid Result", "Invalid Result", "Invalid Result",
"Invalid Result", "Invalid Result"), Result = c("Patients_Result",
"Patients_Result", "Patients_Result", "Medics_Result", "Medics_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Medics_Result", "Medics_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Patients_Result", "Patients_Result", "Patients_Result",
"Patients_Result", "Medics_Result", "Medics_Result", "Medics_Result",
"Medics_Result"), Result.1 = c(0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L,
0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 1L)), class = "data.frame", row.names = c(NA, -426L))>

Any help with this would be appreciated!

A: You just need to add pattern in geom_bar_pattern

pattern = rep(c('none','stripe'),6),

Pattern is the key part of geom_bar_pattern. You can choose from 'stripe' (default), 'crosshatch', 'point', 'circle', 'none'. And the length of pattern needs to be either one or the same as the data.


text:
Q: Rails and Kaminari pagination with certain priority per page I have complex query that I wrote partly as MySQL database view and partly as ActiveRecord logic in Rails. Each record has it's own priority from 0-4 where 4 is top priority.
I'm using Kaminari for pagination and I'm wondering if there's a way to show per page sets of records with some extra rules:

*

*Show all #4 priority rows on first page

*Take per_page number and show priority 3 with this formula: 0.3*per_page

*Then do the same with priority 2

*Then if all 3 steps didn't produced 100% of per_page show the rest with priority 0 and 1

How could I achieve result by using Rails. Or is it better to implement it directly in SQL?
Here is sample of my db view:
select *
from (
        select
            s.id as source_id,
            'Spree::Store' as source_type,
            (case when (s.created_at >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND s.created_at < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY)
            then
                'new'
            else
                'old'
            end) as sub_type,
            1 as priority,
            s.created_at as created_at,
            s.updated_at as updated_at,
            null as owner_id
        from spree_stores as s
        where s.image_id is not NULL and s.is_hidden = false

    union

    select
        e.id as source_id,
        'Event' as source_type,
        (case
        when (e.status = 1 and e.is_featured is false)
        then
            'live'
        when (e.is_featured = true)
        then
            'featured'
        else
            case when (e.created_at >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND e.created_at < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY)
            then
                'new'
            else
                'old'
            end
        end) as sub_type,
        (case
        when (e.status = 1 or e.is_featured is true)
        then
            3
        else
            1
        end) as priority,
        e.created_at as created_at,
        e.updated_at as updated_at,
        null as owner_id
    from events as e
    where e.status >= 1 and e.expires_at >= curdate()

    union
    select
        o.id as source_id,
        'Spree::Order' as source_type,
        (case when (o.created_at >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND o.created_at < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY)
        then
            'new'
        else
            'old'
        end) as sub_type,
        1 as priority,
        o.created_at as created_at,
        o.updated_at as updated_at,
        o.user_id as owner_id
    from spree_orders as o
    where o.user_id is not NULL and o.share is true and o.state = 'complete' and o.completed_at is not NULL
    union
    select
        p.id as source_id,
        'Spree::Product' as source_type,
        (case when (p.created_at >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND p.created_at < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY)
        then
            'new'
        else
            'old'
        end) as sub_type,
        1 as priority,
        p.created_at as created_at,
        p.updated_at as updated_at,
        null as owner_id
    from spree_products as p
    join spree_variants as sv on (sv.product_id = p.id and sv.is_master = true)
    join spree_assets as sa on (sa.viewable_id = sv.id and sa.viewable_type = 'Spree::Variant')
    where p.deleted_at is NULL
    group by p.id
  ) a
  order by priority desc, created_at desc;

This is the result I'm getting (only few lines not all 200 results):

A: This sounds like more complex logic than Kaminari is built for and probably worth doing it yourself. Kaminari is certainly convenient for knocking out a quick pagination UI, but it really doesn't add a huge amount of value compared to rolling your own solution. You might be able to hack it to fit your needs, but that's probably more headache than just doing it yourself.
I'm also a little skeptical the complex algorithm you're wanting is really going to benefit users. Only you know that for sure, but you might want to consider a simple "score" or "rank" column and then just use Kaminari with a query sorted by score desc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I deploy Complex Machine Learning Predictors? So after I have spent a few days cleaning my data, preproceasing, and experimenting with a few different models (e.g. in R Studio) how do I realistically deploy the solution.
Its straightforward if the model is a simple Model e.g Decision Tree, Logistic regression, as the model is obvious and the R Predictor model deployed into an commercial R Server with http endpoints etc.
My question is, what about complex pre processing ( e.g. PCA transforms, RBF kernels, or Random forests of 100 trees.) just as in the Validation phase, I would presume I would have to deploy R Scripts to preprocess, and PCA or apply RBF pre processing scripts etc to my deployment server ?
Does this mean for RBF I have to host all the original Training  data set alongside my SVM predictor ? RBF transform being a function of Training set or at least the support vectors.
And for Random Forest, I assume I have to upload all 500 or so Trees, as part of a very big model.

A: First, export your R solution (data pre-processing steps and the model) into PMML data format using either the combo of pmml and pmmlTransformations packages, or the r2pmml package. Second, deploy the PMML solution using Openscoring REST web service, JPMML-Spark, or whatever else PMML integration that fits your deployment needs.
PMML has no problem representing PCA, SVM with RBF kernel, tree ensembles, etc.

A: A pure R vanilla solution for this problem. Most of the ensemble method provide utility to dump/save the learnt model. Learning is very time consuming and iterative process that should be done once. Post learning save/dump your R object. In the deployment have only scoring code. Scoring code will do all the data transformations and later on scoring.
For normal preprocessing you can reuse R code which was used in training. For complex processing like PCA again save the final model and just score/run data over saved PCA R object. Lastly post preprocessing score/run your data on learnt model and get final results.


text:
Q: Pandas changes numbers when reading from Excel I'm using pandas to read an Excel file which contains earthquake data from the last 10 years. However, the numbers (more specifically the decimal part) seems to change when I read into Python.
The first line has the column "EQ_PRIMARY" = 9.1 in Excel. When I try to output it in Python, I get 9.0999999999999996. This is not a big deal, but I really wanted it to output correctly without using formatting or something like that. What could be the problem?
This is how I'm reading/analyzing the dataset now:
import pandas as pd
data = pd.read_excel("Earthquakes.xls",sheet_name="earthquakes")
data["EQ_PRIMARY"].max()

And the output is

9.0999999999999996

A: Edit: I was wrong and I'm sorry. Don't read the rest of my comment.

Pandas doesn't change the number. Your code output correctly returns the number in your excel file. You can check the actual number by clicking the following button in the home tab in MS Excel
Use the round method if you want to get your number rounded up.

A: I think this is a duplicate question, please see question below:
Pandas read csv file with float values results in weird rounding and decimal digits
The solution was using float_precision='round_trip':-
pd.read_csv(source_file, float_precision='round_trip')


text:
Q: Can't add to an NSMutableArray with addObject method I am having an issue with the addObject method of an NSMutableArrayObject. Here's the code I'm using right now:
- (void)addBirdSightingWithName:(NSString *)name location:(NSString *)location {
    BirdSighting *bird;
    NSDate *today = [NSDate date];
    bird = [[BirdSighting alloc] initWithName:name location:location date:today];
    [self.masterBirdSightingList addObject:bird];
    NSLog(@"Elements: %d", [self.masterBirdSightingList count]);
}

When this code runs, the NSLog call prints the value 0 to the console. I don't know what could be causing this.
EDIT:
I have looked deeper into the code, and I have discovered that the problem is that my BirdSightingDataController is never initialized. Now my question is: Where can I place the init for my BirdSightingDataController? In the viewDidLoad?
Thanks to everyone for the help.

A: Did you allocate memory to masterBirdSightingList?
self.masterBirdSightingList = [[NSMutableArray alloc] init];

A: In almost every case where cellForRowAtIndexPath: is not called is because numberOfRowsInSection: returns 0.
Place a log there and make sure you return more than one item and you should be able to see your cells. If you need further help please post the code in your:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

A: Check your property accessor.  Are you sure it's returning the correct object?  Make sure the name of the property matches the instance variable or you've specified it correctly (For example: @synthesize masterBirdSightingList = _masterBirdSightingList;.  If the property accessor doesn't match the iVar, it will return nil.  Of course, if you're manually implementing the accessor check your code there.  If you're not, you could also try manually implementing it to make sure.
To do a quick check, remove the self.masterBirdSightingList and replace it with masterBirdSightingList (assuming that's the iVar name) to access the iVar directly and see what happens.


text:
Q: Extracting algo/pseudocode from python code I'm looking to implement the pLSI algorithm in R. I found this python code, but I am stuck in a few places, like line #8 for termID, value in docTermDic[docID].iteritems():. In this case I don't understand how to implement both termID & value inside a for loop, and what docTermDic[docID].iteritems() is.
Is there any tool available using which I can extract the algo or the pseudocode so as to enable me to code it up myself?

A: Related answers:
What is the difference between dict.items() and dict.iteritems()?
Why do you have to call .iteritems() when iterating over a dictionary in python?
A simple Google search tells you that iteritems() gives you an iterator for a dict:check this

A:
Is there any tool available using which I can extract the algo or the pseudocode so as to enable me to code it up myself?

Well, python is designed to look like some kind of pseudocode. It looks like what you're asking is something that will scan your brain in order to find what you don't understand and explain it you. I suppose it doesn't exist.
For the specific part of the question about dictionaries :
for termID, value in docTermDic[docID].iteritems() :

this will iterate through all pairs (key,value) in the dict, and affect both key and value. You can't do it in every language. If your language can't do this, just do something like :
for termID in docTermDic[docID].keys() :
    value = docTermDic[docID][termID]

iterate through all keys, and affect the value as first instruction.


text:
Q: iOS - set MAXIMUM touchCount I'm taking a UITapGestureRecognizer in order to turn a comic-book page. When I take the tap, I send:
    [comicScrollView setContentOffset:CGPointMake(nextPageCGPoint) animated:YES];

-- in other words, on a tap event I animate the content offset of a scroll view, to show the next page in the scroll view.
The problem is, I want to NOT let another tap gesture affect the contentOffset unless the animation has finished. The problem is, in practice, I've found this very difficult -- I've tried setting an "isAnimating" Boolean to YES before setting the content offset, then setting it to NO with a callback; I've tried setting an animation:completion: -- but each time a tap comes in, tapCount increments.
the following:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    NSLog(@"%d", [touch tapCount]);
}

continually increments tapCount as often as I tap it, and if I put this into that method:
if ([touch tapCount] > 1) { [gestureRecognizer setEnabled:NO]; }

it doesn't disable the gesture recognizer until after the tapCount has finished incrementing & then reset to zero.
Please help! I can't figure out how to stop tapCount from incrementing past 1.

A: [UIView beginAnimations:@"AnimateIn" context:nil];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration: 0.7f];

//Add this
[UIView setAnimationDelegate:self];

[UIView setAnimationDidStopSelector:@selector(loadingViewDisappear:finished:context:)];
loadingView.frame = CGRectMake(rect.origin.x, rect.origin.y - 80, rect.size.width, rect.size.height);
[UIView commitAnimations];

- (void)loadingViewDisappear:(NSString *)animationID finished:(NSNumber *) finished context:(void *) context {
    NSLog( (finished ? @"YES!" : @"NO!" ) );
    if ([animationID isEqualToString:@"AnimateIn"] && finished) {
        //do something here
    }
}

A: I didn't want to use the [UIView beginAnimations:] method, so experimented again with the new way using blocks. I tried this before & don't know what I did differently this time, but the result was favorable.
I found that when I used this method to set the contentOffset of the scrollview, even though my tapCount is still incrementing as long as I keep tapping like a madman, the pages are now animating with the desired behavior, not erratically. As if it's not letting me "tack another animation on." Which is exactly the behavior I want.
-(void)singleTap:(UITapGestureRecognizer*)tapRecognizer {

    CGPoint tapLocation = [tapRecognizer locationInView:self.view];

    //a tap on the right side turns to the next page:
    if (tapLocation.x > self.view.frame.size.width/2) {
        [UIView animateWithDuration:.3 animations:^{
            [comicScrollView setContentOffset:nextPagePoint];
        }completion:^(BOOL finished){
            NSLog(@"finished");
        }];
    }
}


text:
Q: jQuery removeAttribute Error in FF I have written a jQuery script to glow and then fade out similar to the glow and fade here on stack overflow. The only issue I have is when i call the removeAttribute('filter') to fix the cleartype font for IE, it errors out in Firefox, thus stopping other scripts from working.
When I comment out the line, everything works except in IE the cleartype is ugly.
Here is my method...
function flash(selector) {
  $(selector)
    .css('opacity', 0)
    .animate({ backgroundColor: 'khaki', opacity: 1.0 }, 800)
    .animate({ backgroundColor: '#ffffff' }, 350, function() {
      this.style.removeAttribute('filter');
    });
}

Any thoughts, ideas and such and such?
Thanks!

A: Hmmm... does jQuery's removeAttr fail as well?
...
.animate({ backgroundColor: '#ffffff' }, 350, function() {
  $(this).removeAttr('filter');
};


text:
Q: Flask listens only on 127.0.0.1 ignoring host parameter I'm using Flask on Windows 7. Flask and related versions are below:
Flask==0.10.1
Werkzeug==0.9.3

Accessing the app from the same computer is OK using http://127.0.0.1:5000
However from another computer in LAN the access fails: http://192.168.101.103:5000
I start the app with these parameters:
#app.py
if __name__ == '__main__':
    app.run( host='0.0.0.0:5000')

One thing I don't understand is, when I start netcat on the same computer, where Flask is currently listening on the same port, it works, and netcat is even accessible from another computer:
>c:\Python27\python manage.py runserver
>
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

works ...
>nc -l -p 5000

works on the same computer, same port ???
GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: de-DE
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0;

Accept-Encoding: gzip, deflate
Host: 192.168.101.103:5000
DNT: 1
Connection: Keep-Alive

even accepting connection from another computer ???
So beside the obvious question, how to get Flask serving for LAN, I'm curious, how could two processes of one machine listen on the same port?
Thank you!

A: The port goes in it's own parameter:
app.run(
    host="0.0.0.0",
    port=5000
)


text:
Q: Using XML to obtain current date I'm in an XML class that has this piece of extra credit.
We are testing the date a class is added to a schedule to make sure it is on or after 9/1/1964 and before or on today's current date.
XLST Code:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:simpleType name="DateAddedType">
        <xs:restriction base="xs:dateTime">
            <xs:minInclusive value="1964-09-01T00:00:00" />

            <xs:maxInclusive value="Date.NowT00:00:00"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="DepartmentType">
        <xs:restriction base="xs:string">
            <xs:pattern value ="[A-z]{2,5}&?" />
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name ="DeptType2">
        <xs:restriction base="xs:string">
            <xs:pattern value ="[A-Z][A-Z]|[A-Z][A-Z][A-Z&]|[A-Z][A-Z][A-Z][A-Z&]" />
        </xs:restriction>
    </xs:simpleType>

<xs:element name="Courses">
    <xs:complexType>
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="Course">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="Department" type="DepartmentType" />
                        <xs:element name="CourseNumber" type="xs:string" />
                        <xs:element name="Title" type="xs:string" />
                        <xs:element name="Description" type="xs:string" />
                        <xs:element name="Credits" type="xs:unsignedByte" />
                        <xs:element minOccurs="0" name="Prerequisites" type="xs:string" />
                            <xs:element name="DateAdded" type="DateAddedType" />
                        <xs:element minOccurs="0" maxOccurs="unbounded" name="Schedule">
                                    <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="Season" type="xs:string" />
                                                <xs:element name="Year" type="xs:string" />
                                                <xs:element name="ItemNumber" type="xs:string" />
                                    <xs:element name="Department" type="DepartmentType" />
                                    <xs:element name="CourseNumber" type="xs:string" />
                                    <xs:element name="Section" type="xs:string" />
                                    <xs:element name="Room" type="xs:string" />
                                    <xs:element name="MeetingDays" type="xs:string" />
                                    <xs:element name="StartTime" type="xs:dateTime" />
                                    <xs:element name="EndTime" type="xs:dateTime" />
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

The XML Code:
<?xml version="1.0" encoding="UTF-8"?>
<Courses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:noNamespaceSchemaLocation="Courses.xsd">
    <Course>
        <Department>CIS</Department>
        <CourseNumber>141</CourseNumber>
        <Title>intro to access</Title>
        <Description>db stuff</Description>
        <Credits>5</Credits>
        <Prerequisites>108, 123</Prerequisites>
        <DateAdded>2011-07-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cap</Department>
        <CourseNumber>102</CourseNumber>
        <Title>Nutrition for the Food Service Professional</Title>
        <Description>Nutrition for the Food Service Professional</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cap</Department>
        <CourseNumber>103</CourseNumber>
        <Title>Applied Food Service Sanitation</Title>
        <Description>Applied Food Service Sanitation</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cap</Department>
        <CourseNumber>104</CourseNumber>
        <Title>Supervision in the Hospitality Industry</Title>
        <Description>Supervision in the Hospitality Industry</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cis</Department>
        <CourseNumber>145</CourseNumber>
        <Title>Introduction to access</Title>
        <Description>Intro to access</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
        <Schedule>
            <Season>Fall</Season>
            <Year>2009</Year>
            <ItemNumber>0000</ItemNumber>
            <Department>cis</Department>
            <CourseNumber>145</CourseNumber>

b

            <Room>34107</Room>
            <MeetingDays>daily</MeetingDays>
            <StartTime>1899-12-30T08:00:00</StartTime>
            <EndTime>1899-12-30T08:50:00</EndTime>
        </Schedule>
        <Schedule>
            <Season>Winter</Season>
            <Year>2010</Year>
            <ItemNumber>1000</ItemNumber>
            <Department>cis</Department>
            <CourseNumber>145</CourseNumber>

d

            <Room>34106</Room>
            <MeetingDays>daily</MeetingDays>
            <StartTime>1899-12-30T10:00:00</StartTime>
            <EndTime>1899-12-30T10:50:00</EndTime>
        </Schedule>
    </Course>
    <Course>
        <Department>cis</Department>
        <CourseNumber>160</CourseNumber>
        <Title>Introduction to Programming</Title>
        <Description>Introduction to practices of programming</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
        <Schedule>
            <Season>Winter</Season>
            <Year>2010</Year>
            <ItemNumber>1200</ItemNumber>
            <Department>cis</Department>
            <CourseNumber>160</CourseNumber>

e

            <Room>34107</Room>
            <MeetingDays>daily</MeetingDays>
            <StartTime>1899-12-30T11:00:00</StartTime>
            <EndTime>1899-12-30T11:50:00</EndTime>
        </Schedule>
    </Course>
    <Course>
        <Department>cis</Department>
        <CourseNumber>245</CourseNumber>
        <Title>Applications in Access</Title>
        <Description>Developing applications in access</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
        <Schedule>
            <Season>Winter</Season>
            <Year>2010</Year>
            <ItemNumber>1100</ItemNumber>
            <Department>cis</Department>
            <CourseNumber>245</CourseNumber>

c

            <Room>34128</Room>
            <MeetingDays>daily</MeetingDays>
            <StartTime>1899-12-30T09:00:00</StartTime>
            <EndTime>1899-12-30T09:50:00</EndTime>
        </Schedule>
    </Course>
    <Course>
        <Department>cis</Department>
        <CourseNumber>266</CourseNumber>
        <Title>VB.Net Applications</Title>
        <Description>Applications in vb.net</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
        <Schedule>
            <Season>Spring</Season>
            <Year>2010</Year>
            <ItemNumber>3525</ItemNumber>
            <Department>cis</Department>
            <CourseNumber>266</CourseNumber>

c

            <Room>34107</Room>
            <MeetingDays>daily</MeetingDays>
            <StartTime>1899-12-30T09:00:00</StartTime>
            <EndTime>1899-12-30T09:50:00</EndTime>
        </Schedule>
    </Course>
    <Course>
        <Department>cna</Department>
        <CourseNumber>250</CourseNumber>
        <Title>Routing and Switching</Title>
        <Description>Introduction to Routing and Switching to design, build, and maintain small to medium-size networks.</Description>
        <Credits>5</Credits>
        <Prerequisites>cna-145</Prerequisites>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cna</Department>
        <CourseNumber>260</CourseNumber>
        <Title>Windows Scripting</Title>
        <Description>Windows Scripting</Description>
        <Credits>5</Credits>
        <DateAdded>2001-01-01T00:00:00</DateAdded>
    </Course>
    <Course>
        <Department>cs</Department>
        <CourseNumber>142</CourseNumber>
        <Title>Object Oriented Programming I</Title>
        <Description>Object Oriented Programming I</Description>
        <Credits>5</Credits>
        <Prerequisites>cis-160, cis-168</Prerequisites>
        <DateAdded>2001-03-01T00:00:00</DateAdded>
    </Course>
</Courses>

The dateAdded field is the one being tested.  Equivelant to [DateAdded >= 9/1/1964 AND DateAdded <= Today]  By utilizing the MinInclusive to test for the date in 1964, and we are to utilize maxInclusive for Today's date, but we are told to use a DTD to manipulate the schema.  Yes, it is silly to do, but since it can be done, the instructor wants us to do it that way.
However, he has not gone over how to do an XML file that validates through a XSLT file that uses a DTD file.  We've done a XML with DTD, and XML with XSLT, but not all three.

A: In XSD 1.0, there is no way of parameterizing the schema. Documents are either valid or they are not. They can't be valid today and invalid tomorrow. So there's no way of doing what you are looking for.
You can do it in XSD 1.1 using assertions: <xs:assert test="$value le current-date()"/>


text:
Q: Accessing singleton model properties in another controller I have a controller from which I am setting a property of my model
$model = Mage::getSingleton('foo/bar');
$model->setData('name', 'somename');
echo $model->getData('name');

This outputs the value somename in the same Action
If i try to access this property in another controller Action it is not getting the value
$model = Mage::getSingleton('foo/bar');
echo $model->getData('name');

I have created a block for my second controller Action and trying to access same property. But its not getting the value.
Model class is as follows (please ignore class name)
class Z_Foo_Model_Bar extends Varien_Object
{
    protected $_cacheTag = true;
    protected $_name = true;

    public function _construct()
    {
        parent::_construct();

    }
    public function setName($val=''){
        $this->name = $val;

    }
    public function getName(){
        return $this->name;
    }

    public function getTest(){
        return 'one';
    }
}

I have a block method as follows
public function testsingle(){
        $model = Mage::getSingleton('foo/bar');
        echo $model->getTest();
        echo $model->getData('name');

    }

I am calling this method from my phtml file in second controller's block view file
$this->testsingle();

Still I am not getting the output 'somename' which is exptected
Reference here from SO Alan's answer

A: You have a slight conceptual gap in your understanding of magic setters/getters /getData() method in Magento and the singleton design pattern.
It seems like you expect the model to persist across different requests to two different controllers. However, the singleton pattern makes the object available/persistent only for the same request. Look at the definition of Mage::getSingleton() function to see how the singleton pattern works in Magento.
When you do $someModel->getData('param1'), Magento actually looks for the 'param1' key in _data property of your model object.
In your case when you do $someModel->setData('param1','value1'); You are setting it equivalent of something like:
$someModel->_data['param1'] = 'value1';
Your usage of the magic setter and getter is also not in line with Magento way of doing it. You don't need to write  magic getters and setters in Magento since they are already in place for you.


text:
Q: Why would you ever use heap allocation for objects you will reference through an std::vector? I'm going through some code from this article about ECS-systems in game programming  and trying to understand it, and something I'm seeing a lot is using heap memory in places where it seems like there is no benefit in doing so. Take this as an example:
class ECS
{
public:
    void someFunction()
    {
        archetypes.push_back(new Archetype);
    }
    ~ECS()
    {
        for(Archetype* a : archetypes_)
        {
            delete a;
        }
    }
private:
    std::vector<Archetype*> archetypes_;
};

This is the only way that the archetypes are manipulated in memory in the code. There is also no polymorphism involved here whatsoever. The archetypes being on the heap here has seemingly no impact on the code other than the fact that the archetypes are referenced by pointers.
Why would you ever choose to use allocated memory for this? I see this often in code and it seems to me like using heap memory just because it feels like the right thing to do, and not actually considering if it's the appropriate place for it. std::vector already uses heap memory behind the scenes so why not just copy a stack variable into the vector when we want to add a new archetype, and let the vector handle the allocation?
class ECS
{
public:
    void someFunction()
    {
        archetypes.push_back(Archetype());
    }
private:
    std::vector<Archetype> archetypes_;
};

Or are there valid reasons for using heap memory in cases like this?

A: The obbious reason would be that you don't want the data items to be moved/copied when the vector grows,
There may be several reasons for that, one is that the types are expensive (or even impossible) to move/copy, another is that you don't want pointers to the individual archetypes to be invalidated by changes to the vector,


text:
Q: std::vector emplace and std::vector emplace back with pair I have this code:
std::vector<std::pair<const std::string, int>> vec;

vec.emplace_back("a", 1); //success
vec.emplace(vec.end(), "b", 2); //compile error

vec.emplace_back(std::make_pair<const std::string, int>("c", 3));  //success
vec.emplace(vec.end(),
     std::make_pair<const std::string, int>("d", 4)); //compile error

Can you explain me why?

A: Other than std::vector::emplace_back, std::vector::emplace requires the element type meet the requirement of MoveAssignable, but std::pair<const std::string, int> has const std::string as its first element then doesn't satisfy that.

Type requirements

*

*T (the container's element type) must meet the requirements of MoveAssignable, MoveInsertable and EmplaceConstructible.


text:
Q: How to check the TEMPLATE_DEBUG flag in a django template? Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?
I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.
For sure, I can add this flag to the context but I would like to know if there is a better way to do that.

A: Assuming you haven't set TEMPLATE_CONTEXT_PROCESSORS to some other value in settings.py, Django will automatically load the debug context preprocessor (as noted here). This means that you will have access to a variable called debug in your templates if settings.DEBUG is true and your local machine's IP address (which can simply be 127.0.0.1) is set in the variable settings.INTERNAL_IPS (which is described here). settings.INTERNAL_IPS is a tuple or list of IP addresses that Django should recognize as "internal".

A: If modifying INTERNAL_IPS is not possible/suitable, you can do this with a context processor:
in myapp/context_processors.py:
from django.conf import settings

def debug(context):
  return {'DEBUG': settings.DEBUG}

in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.debug',
)

Then in my templates, simply:
 {% if DEBUG %} .header { background:#f00; } {% endif %}

A: If you haven't already, it always helps to see if/how others have dealt with same issue on djangosnippets. The most recent snippet working with analytics tag is 1656:
http://www.djangosnippets.org/snippets/1656/
What is nice about this solution is that it allows you to keep your GOOGLE_ANALYTICS_CODE = xxxxxx in local_settings.py in the case rest of your source is public, your key remains private. In addition it goes an extra step to not use analytics for logged in users.

Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users.
Use {% googleanalyticsjs %} in your templates.
You must set something like
GOOGLE_ANALYTICS_CODE = "UA-1234567-1"

in your settings file.
Assumes 'user' in your template variables is request.user, which it will be if you use:
return render_to_response('template.html',{ }, context_instance=RequestContext(request))

(Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)

from django import template
import settings
register = template.Library()

class ShowGoogleAnalyticsJS(template.Node):
  def render(self, context):
      code =  getattr(settings, "GOOGLE_ANALYTICS_CODE", False)
      if not code:
          return "<!-- Goggle Analytics not included because you haven't set the settings.GOOGLE_ANALYTICS_CODE variable! -->"

      if 'user' in context and context['user'] and context['user'].is_staff:
          return "<!-- Goggle Analytics not included because you are a staff user! -->"

      if settings.DEBUG:
          return "<!-- Goggle Analytics not included because you are in Debug mode! -->"

      return """
      <script type="text/javascript">
          var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
          document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'
            type='text/javascript'%3E%3C/script%3E"));
      </script>
      <script type="text/javascript">
          try {
          var pageTracker = _gat._getTracker('""" + str(code) + """');
          pageTracker._trackPageview();
      } catch(err) {}</script>
      """

def googleanalyticsjs(parser, token):
  return ShowGoogleAnalyticsJS()

show_common_data = register.tag(googleanalyticsjs)

A: {% if debug %} can do the trick but only if you pass RequestContext instead of Context. Additionally, debug is not a boolean flag, its a function that when evaluated while DEBUG = True return some debugging information. This can be unnecessary overhead for your template.
Personally, I do this trick instead.
{% if request.META.HTTP_HOST == "127.0.0.1:8000" %}

This will always work but instead of relying on both DEBUG flag and INTERNAL_IP, it just work for the hard coded IP.

A: Django 1.9+
settings.py:
INTERNAL_IPS = (
    '127.0.0.1',
)

Templates:
{% if debug %}

https://docs.djangoproject.com/en/dev/ref/settings/#internal-ips says:

A list of IP addresses, as strings, that:

*

*Allow the debug() context processor to add some variables to the template context.

The debug context processor is in the default settings.py.

A: You will need to add the DEBUG flag to your context_processors.
There may not even be an alternative way. At least, none that I know of.


text:
Q: Transfer OpenCV image from Python to JavaScript using Django Channels I am working on a Django app with channels. I am sending strings from Python to JS successfully. What I want next is to send image processed using opencv and stream in browser using django channels.
How and in what format do I send image from Python to JS such that it can be displayed in a part of a browser with other elements?
I tried converting opencv image into base64 but can't figure out how to use that string in JavaScript.


text:
Q: Orbeon form in chinese returned with question marks I'm using ORBEON 2018.2.3.201905172253 PE within SAP Commerce (Hybris) on a Tomcat 7.0. When Hybris hits the Orbeon app to create a new form and get the inline HTML in Chinese, I'm getting question marks instead of Chinese characters.
URL: http://localhost:9001/orbeon/fr/yforms/myform/new?orbeon-embeddable=true&fr-language=zh-Hans
Method: GET
Headers:
[
   {
      "key":"hybris-Username",
      "value":"-"
   },
   {
      "key":"hybris-Group",
      "value":"-"
   },
   {
      "key":"hybris-Roles",
      "value":"-"
   },
   {
      "key":"Orbeon-Client",
      "value":"portlet"
   },
   {
      "key":"hybris-Proxy-09e4ff02-4715-4547-8f81-30082598eec9",
      "value":"37bb0017-2675-4617-945d-6693bdae8eb9"
   },
   {
      "key":"Content-Type",
      "value":"text/html;charset=UTF-8"
   }
]
I've found there's a known issue in Tomcat 7 for Chinese characters:
https://books.google.co.nz/books?id=kNVe8lzTec0C&pg=PA166&lpg=PA166&dq=webapp+http+request+chinese+question+marks&source=bl&ots=F11m7FJGYD&sig=ACfU3U1fufLJggVpnu4iUFT9SUJ6SdhqmA&hl=en&sa=X&ved=2ahUKEwjJq5L-_8njAhVi7nMBHXnMD0sQ6AEwAnoECAkQAQ#v=onepage&q=webapp%20http%20request%20chinese%20question%20marks&f=false
And apparently, Orbeon includes a way to set the character encoding to UTF-8 using the oxf.xforms.renderer.default-encoding param in the web.xml file:
https://doc.orbeon.com/xforms/filter
I already tried that in my web.xml and got the same results from the Orbeon app. I even executed the same request using Postman to check if it's an integration problem with my Hybris storefront, but the results were the same.
This is an excerpt of my web.xml:
    <filter>
        <filter-name>orbeon-xforms-filter</filter-name>
        <filter-class>org.orbeon.oxf.servlet.OrbeonXFormsFilter</filter-class>
        <!-- Uncomment this for the separate WAR deployment -->

        <init-param>
            <param-name>oxf.xforms.renderer.context</param-name>
            <param-value>/orbeon</param-value>
        </init-param>
        <init-param>
            <param-name>oxf.xforms.renderer.default-encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!-- End separate WAR deployment -->
    </filter>
    <filter-mapping>
        <filter-name>orbeon-xforms-filter</filter-name>
        <url-pattern>/xforms-jsp/*</url-pattern>
        <!--Servlet 2.4 configuration allowing the filter to run upon forward in addition to request-->
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

Changing the url-pattern of the filter to "/orbeon/fr/yforms/*" broke the whole thing and I couldn't even render the form in English.
When debugging the request in Java I tried setting the Character Encoding of the HttpRequest object to UTF-8. Same results.
I've also tried these without good results:

• Set the URIEncoding attribute on the  element in server.xml to URIEncoding="UTF-8".
• Set the useBodyEncodingForURI attribute on the  element in server.xml to true.

Related to this:
Orbeon form localization using current site's session language
The answer to that thread explains how I'm localizing my forms.
THE WEIRDEST THING IS that the response of that URL DOES include some characters in Chinese: the label of the dropdown language selector. All other labels are question marks. Super weird!
I'd like to know how to fix this behaviour either changing my Tomat config or my Orbeon app config.
Thanks,
David

A: Well, as expected the problem was not related to Orbeon.
In my Spring Controller, the method that was getting my form from the database was annotated with a @ResponseBody. The String being returned by the Controller was in a perfect state containing the proper Chinese characters, but the response object was then intercepted by a Spring converter.
@RequestMapping(method = RequestMethod.GET, value = ...")
    @ResponseBody
    public String getFormDefinition(@PathVariable final String aaa, @PathVariable final String aaa,
            @RequestParam(value = "document", required = false) final String aaa, final HttpServletResponse response)
                    throws ServletException, IOException, YFormServiceException
    {
        return "html content";
    }

When there's a @ResponseBody annotation, the response is processed by Spring's message-converters. The default converters are listed here: https://www.baeldung.com/spring-httpmessageconverter-rest
One of those converters is the magical StringHttpMessageConverter. If you check its source code, you can see it uses ISO-8859-1 as a default charset. Every response processed by these converter is going to be encoded using ISO-8859-1, which does not support Chinese characters.
The Fix:
In my web spring config file I added:
<mvc:annotation-driven>

      <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
         <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
         <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
         <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
         </bean>
         <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
         <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
      </mvc:message-converters>

    </mvc:annotation-driven>

With register-defaults="false" you say to Spring not to use any of the default converters, but use the provided list below.  When defining StringHttpMessageConverter, I specify UTF-8 (which supports Chinese characters) as the default encoding.
Et voila


text:
Q: Sending formdata for file upload using ajax I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.
<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>

But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.
HTML
<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">

Jquery
$("form#uploadForm").submit(function (event) {
          //disable the default form submission
          event.preventDefault();
          var formData = $(this).serialize();
          console.log(formData);
          $.ajax({
              url: '/tab10/uploadImage',
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              contentType: false,
              processData: false,
              success: function () {
                  alert('Form Submitted!');
              },
              error: function(){
                  alert("error in ajax form submission");
              }
          });
          return false;
      });

Below is the code i am using for saving the image.
exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
  res.status = 500;
  res.message = err;
  // return res.status(500).send(err);
  return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};

When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.

A: I think you have  to  create FormData, after you  can  append  the  file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>
 $("form#uploadForm").submit(function (event) {
      //disable the default form submission
      event.preventDefault();
      var formData = new FormData();
      formData.append('file',$('#uploadFile')[0].files[0]);
      $.ajax({
          url: '/tab10/uploadImage',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          success: function () {
              alert('Form Submitted!');
          },
          error: function(){
              alert("error in ajax form submission");
          }
      });

  });

A: use
$("#uploadForm").submit(function () {
      var formData = new FormData(this);
      $.ajax({
          url: '/tab10/uploadImage',
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          success: function () {
              alert('Form Submitted!');
          },
          error: function(){
              alert("error in ajax form submission");
          }
      });
      return false;
  });

A: Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
     type: "POST",
      enctype:"multipart/form-data",
       url: "/tab10/uploadImage",
       data: fileContent,
       processData: false,
       contentType: false,
       success: function(response) {
        }
});


text:
Q: C# cryptosystem .NET API interface with C I am looking to implement the C# Cryptosystem .NET api with C code, so i am wondering what a possible at best route would be?
I have currently begun looking at this link below.
http://libtom.org/?page=features&whatfile=crypt
I am wondering if it would be possible to use my own public and private keys for decoding(in C) already encrypted data(done in C#) with this library?
Anyone got some advice on past experience with this type of procedure?


text:
Q: Xcode 11 SPM authentication failed because no credentials provided I started using Swift package manager and when I add repository with https (https://github.com/Alamofire/Alamofire.git) address authentication always fails when I try to login with my github account
Xcode authentication fail
But if I'm using git@github.com:Alamofire/Alamofire.git it will get added successfully. I tried regenerating new key, deleted .ssh directory but nothing makes https work and I still get xcode authentication failed because no credentials were provided error. I could use locally ssh url but in CI I need one with https.

A: Building off of two previous answers, I solved this by doing what Abrahanfer did, setting Clone using to SSH in Xcode Preferences -> Account.
Then I used the SSH url of the repo, for example: git@github.com:AppPear/SwiftUI-PullToRefresh.git

A: you can use ssh URLs instead of https, e.g. git@github.com:ORG_NAME/REPO_NAME.git

A: I double clicked the error message Error while fetching remote repository: git@github.com:ORG/REPO-NAME.git or the The server SSH fingerprint failed to verify
in Xcode's Report Navigator which then a popup appeared asking if I wanted to trust the host. After clicking that I was able to add the Swift Package using SSH.
Selecting HTTPS or SSH in the Xcode Preferences did not fix for me because Xcode seems to automatically handle SSH GitHub URLs in the SPM flow.

A: what worked for me was both @SimonasDaniliauskas answer and @Abrahanfer answer
Basically in the command line I had to run:
git config --global --unset-all url.git@github.com:.insteadof

And in Xcode I had to go to Xcode > Preferences  and switch my GitHub to use SSH
Btw, if you don't have ssh setup, follow this medium post or these GitHub directions. If you need change your ssh keys follow this YouTube tutorial

A: In my case with Xcode 11.3.1 I had the same problem and I solved changing de auth method to SSH from HTTPS in Github account preferences on Xcode.

A: It was a problem with git config. In .gitconfig file it was set to
[url "git@github.com:"]
    insteadOf = https://github.com/

After removing this section https worked correctly
EDIT: as mentioned in comments you can easily access your gitconfig in terminal with command: git config --global --edit

A: If you are facing this and your .gitconfig has below, and you want to keep it!
[url "git@github.com:"]
  insteadOf = https://github.com/

just add below two lines after above two lines in your .gitconfig
[url "https://github.com/apple"]
  insteadOf = https://github.com/apple

Duplicate above two lines and replace /apple with any other /user or /org where you might want to download your packages from

A: Try removing it and adding it again. If that won't work, remove your GitHub account from Xcode. Usually, git via ssh works better. What CI are you using?

A: For me, it seems more like a red herring (maybe a fellow developer accidentally checked in this small change related to swift package in project setting). I went to project setting, removed it from under "Swift Packages". It seems okay after that.

A: I keep having this issue in Xcode 12.0.1 (12A7300).
My GitHub credentials seemed to not work, even though I applied all the suggestions above.
The way I fixed it (for now, at least) was to switch to SSH only authentication.

A: I managed to get HTTPS working fine with CI. The solution, with bitrise, is to use 'Authenticate host with netrc', then Xcode will find private HTTPS repos properly. I am sure other CI platforms (or your own) can setup the same solution.

A: Adding repo via source tree and checking out repo through Xcode use some other tool, then adding same repo via SPM. Try creating SSH key via rsa key algorithm instead of ed255189 key algorithm. SPM tool comfortably work with rsa.
Note: rsa key authentication is slower than ed25519 key authentication.

A: I followed the other anwsers here with no success. Eventually it turned out that the package was added to XCode with my username inside the https domain, like that:
https://yarden_k@bitbucket.org/private/package/path.git

so I had to adjust the accepted answer the same way (I added those lines to .gitconfig file):
[url "git@bitbucket.org:"]
    insteadOf = https://yarden_k@bitbucket.org/

And viola! It finally worked. Was a real headache to figure this one out.

A: Me too facing this problem
Check your repo access is correct and you have proper access for PUSH the code
They only gave me READ access, After facing this issue I'll informed to respective person and get WRITE access


text:
Q: $t(\lfloor\frac{n}{2}\rfloor)+t(\lceil\frac{n}{2}\rceil)+n=n(\lfloor\log n\rfloor+3)-2^{\lfloor\log n\rfloor +1}$ Given the following recurrence relation:
$t(1) = 1$
$t(n) = t(\lfloor \frac{n}{2} \rfloor) + t(\lceil \frac{n}{2} \rceil) + n$
How would a proof for the solution $t(n) = n (\lfloor \log n \rfloor + 3) - 2^{\lfloor \log n \rfloor + 1}$ look?
I suppose this should be proven by induction.
The base case would be $t(1) = 1 = 3 - 2 = 1 \cdot (\log 1 + 3) - 2^{\log 1 + 1}$
Next consider two cases. The case $n$ is even and $n$ is odd...
Is that correct? And if yes, how would you choose $n$? $n=2k$ and $n=2k+1$?

A: Hint:
If you take the $2k$ and $2k+1$ approach, your recurrence becomes
$$t(2k)=2t(k)+2k$$
$$t(2k+1)=t(k)+t(k+1)+2k+1$$
while your inductive hypothesis becomes
$$t(2k)=2k(\lfloor\log k\rfloor+4)-2^{\lfloor\log k\rfloor +2}$$
$$t(2k+1)=(2k+1)(\lfloor\log k\rfloor+4)-2^{\lfloor\log k\rfloor +2}$$
and the inductive step looks reasonably simple, with some care needed when $k$ is one less than a power of two.  I might start by checking the cases when $k=1$, i.e. $n=2,3$


text:
Q: How to handle all DBNulls without checking for them every time (with a generated DataSet)? My original question was, as @nicholas correctly pointed, a little misleading, because this case is a little specific.
So here's the real problem:
I created Windows Form Application with DataGridView control and a DataSource generated from a table in my production database.
The goal of my program is to view the table, optionally edit comment columns and to export the table data to a XML file, which schema is strictly defined both with XSD and other independent constraints I cannot change.
It is especially important that I must not insert some fields into my XML output file if some values are not defined.
It's explicitly said I must not insert empty tags for those fields. That's the reason I need null values. To insert XML tags only where the value is given. That's why I need DBNull values, not any other default values.
The generated DataSet contains getters which throw an exception on accessing DBNull values. I cannot change generated code, it's a rule, you don't change generated code, especially the code which could (and would) be overwritten.
I solved this problem by surrounding each assignment of a nullable field with a "try/catch" block. If the generated getter throws an exception, my nullable field of my XML object will keep it's default null value, which is my expected behavior.
Later - my XML constructor will skip those fields while generating XML output.
But one problem remains: why does it have to be so ugly? What if I had a hundred nullable fields? Would I have to write a hundred "try/catch" blocks? It seems like a bug in the whole Microsoft mechanism to me. Or maybe there's a simple and elegant solution to this?
--
Here's the original content, to understand where the first answers came from:

Please, I do know I could check each field for DBNull, but there must
  be a automatic way for programmers. It would be the most stupid thing
  in whole .NET/C# - having to write "if" or "try/catch" statement for
  each column of my huge table! I've tried to use "foreach" on my table
  row type, but it didn't work. The exceptions are thrown at the very
  beginning of "foreach" body, it seems if I even try to touch DBNull,
  the exception is thrown. If I put my whole code block inside
  "try/catch" - it won't work because it will skip all fields behind
  first DBNull.
There must be a way to do it without putting a couple of dozens fugly
  checks in my code. So, what is the magic trick for the rows with
  DBNulls?

A: Write an extension:
public static T GetValue<T>(this IDataRecord @this, string name, T defaultValue = default(T))
{
    int ordinal = @this.GetOrdinal(name));
    return @this.GetValue<T>(ordinal, defaultValue);
}

public static T GetValue<T>(this IDataRecord @this, int ordinal, T defaultValue = default(T))
{
    return @this.IsDBNull(ordinal) ? defaultValue : (T)@this.GetValue(ordinal);
}

Use it like so:
connstr = @"Data Source=.\sqlexpress;Integrated Security=SSPI;Initial Catalog=Test;";

string sql = "select WidgetId, WidgetName, WidgetValue, CreatedDt, ModifiedDt from dbo.widgets";

using (connection = new SqlConnection(connstr))
{
    connection.Open();
    using (command = new SqlCommand(sql, connection))
    using (IDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.Write(reader.GetValue<int>("WidgetId").ToString());
            Console.Write("\t");
            Console.Write(reader.GetValue<string>("WidgetName"));
            Console.Write("\t");
            Console.Write(reader.GetValue<int>("WidgetValue"));
            Console.Write("\t");
            Console.Write(reader.GetValue<DateTime>("CreatedDt"));
            Console.Write("\t");
            Console.Write(reader.GetValue<DateTime>("ModifiedDt"));
            Console.Write("\n");
        }
    }
}

Results:
1       Widget 1        0       7/17/2012 6:13:26 AM    1/1/0001 12:00:00 AM
2       Widget 2        0       7/17/2012 6:13:26 AM    1/1/0001 12:00:00 AM
3       Widget 3        0       7/17/2012 6:13:26 AM    1/1/0001 12:00:00 AM

A: Remove the DbNull values prior to retrieving them from the server by modifying your SQL select query to call IsNull (or in the case of an Access back-end Nz). Definition here.
string sql = "select WidgetId, IsNull(WidgetName,""), " +
             "IsNull(WidgetValue,0), CreatedDt, ModifiedDt from dbo.widgets";

Assuming you have some kind of appropriate default value or use a sentinel value for catching the nulls later on.


text:
Q: How Can I Retrieve The Earliest Date and Status Per Each Distinct ID I have been trying to write a query to perfect this instance but cant seem to do the trick because I am still receiving duplicated. Hoping I can get help how to fix this issue.
SELECT DISTINCT
1.Client
1.ID
1.Thing
1.Status
MIN(1.StatusDate) as 'statdate'

FROM
SAMPLE 1

WHERE
[]

GROUP BY
1.Client
1.ID
1.Thing
1.status

My output is as follows
Client   Id   Thing   Status   Statdate
CompanyA  123   Thing1   Approved   12/9/2019
CompanyA  123   Thing1   Denied   12/6/2019

So although the query is doing what I asked and showing the mininmum status date per status, I want only the first status date. I have about 30k rows to filter through so whatever does not run overload the query and have it not run. Any help would be appreciated

A: Use window functions:
SELECT s.*
FROM (SELECT s.*,
             ROW_NUMBER() OVER (PARTITION BY id ORDER BY statdate) as seqnum
      FROM SAMPLE s
      WHERE []
     ) s
WHERE seqnum = 1;

This returns the first row for each id.

A: Use whichever of these you feel more comfortable with/understand:
SELECT
  *
FROM
  (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY statusdate) as rn
    FROM sample
    WHERE ...
  ) x
WHERE rn = 1

The way that one works is to number all rows sequentially in order of StatusDate, restarting the numbering from 1 every time ID changes. If you thus collect all the number 1's togetyher you have your set of "first records"
Or can coordinate a MIN:
SELECT
  *
FROM
  sample s
  INNER JOIN
  (SELECT ID, MIN(statusDate) as minDate FROM sample WHERE ... GROUP BY ID) mins
  ON s.ID = mins.ID and s.StatusDate = mins.MinDate
WHERE
  ...

This one prepares a list of all the ID and the min date, then joins it back to the main table. You thus get all the data back that was lost during the grouping operation; you cannot simultaneously "keep data" and "throw away data" during a group; if you group by more than just ID, you get more groups (as you have found). If you only group by ID you lose the other columns. There isn't any way to say "GROUP BY id, AND take the MIN date, AND also take all the other data from the same row as the min date" without doing a "group by id, take min date, then join this data set back to the main dataset to get the other data for that min date". If you try and do it all in a single grouping you'll fail because you either have to group by more columns, or use aggregating functions for the other data in the SELECT, which mixes your data up; when groups are done, the concept of "other data from the same row" is gone
Be aware that this can return duplicate rows if two records have identical min dates. The ROW_NUMBER form doesn't return duplicated records but if two records have the same minimum StatusDate then which one you'll get is random. To force a specific one, ORDER BY more stuff so you can be sure which will end up with 1