text:
Q: scheme constructors and accessors USING SCHEME:
I am working on a question in my assignment that asks the follows:

A toy data structure specifies the name of a toy, a description, the acquisition price, and the recommended sales price. Create
  constructors and accessors for the toy structure, ensuring that you do
  not use Racket's builtin structs [1 marks]. Using only your accessors
  to get at the data in your structure, define a function that sorts a
  list of toy structures by the difference between the two prices [2
  marks].

Is the question asking to create my own toy data structure with constructors that has the name of the toy,description, and acquisition price and accessors to get the variables of toy like name or description?
if so, how do i do this?
is there a keyword like struct in scheme?

A:
Is the question asking to create my own toy data structure with constructors that has the name of the toy,description, and acquisition price and accessors to get the variables of toy like name or description? if so, how do i do this?

Yes, that's exactly what the assignment says. Hint: a simple list will do, store each field in a position and the accessors will return the element at the position. For instance, if we store the name in the first position, then the accessor will return the car of the list, and so on.

Is there a keyword like struct in scheme?

Yes, oddly enough in Racket is called struct (it's a macro, not a keyword). Also in R7RS (or in SRFI-9) we have record types. But the assignment specifically states that you must not use this!


text:
Q: Drawing an arrow over a tabular with tikzmark I'm trying to get lines to trace diagonally along the entries in a tabular using tikz and tikzmark but tikz isn't drawing on top of the text in the tabular. How can I fix this? I would like to keep using an appropriate mathy structure like tabular, not change to something pgf-specific, just draw a line on top, like the one that's used to prove countability of the rationals like here: https://plus.maths.org/issue47/features/macgregor/diagram3.gif but preferrably with an arrow head at the end. What's a good way to do that?
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{comment}
\usepackage{tikz}

\begin{document}

\begin{tabular}{c c c c c c}
$(1,1)$ & $(1,2)$ & $(1,3)$ & $(1,4)$ & $(1,5)$ & $\cdots$ \\
$(2,1)$ & $(2,2)$ & $(2,3)$ & $(2,4)$ & $(2,5)$ & $\cdots$ \\
$(3,1)$ & $(3,2)$ & $(3,3)$ & $(3,4)$ & $(3,5)$ & $\cdots$ \\
$(4,1)$ & $(4,2)$ & $(4,3)$ & $(4,4)$ & $(4,5)$ & $\cdots$ \\
$(5,1)$ & $(5,2)$ & $(5,3)$ & $(5,4)$ & $(5,5)$ & $\cdots$ \\
$\vdots$ & $\vdots$ & $\vdots$ & $\vdots$ & $\vdots$ & $\ddots$ \\
\end{tabular}

\newcommand {\tikzmark}[2]{%
    \tikz[overlay,remember picture] \node (#1) {#2};
}

\begin{tabular}{c c c c c c}
\tikzmark{1-1}{$(1,1)$} & \tikzmark{1-2}{$(1,2)$} & \tikzmark{1-3}{$(1,3)$} & \tikzmark{1-4}{$(1,4)$} & \tikzmark{1-5}{$(1,5)$} & $\cdots$ \\
\tikzmark{2-1}{$(2,1)$} & $(2,2)$ & $(2,3)$ & $(2,4)$ & $(2,5)$ & $\cdots$ \\
\tikzmark{3-1}{$(3,1)$} & $(3,2)$ & $(3,3)$ & $(3,4)$ & $(3,5)$ & $\cdots$ \\
\tikzmark{4-1}{$(4,1)$} & $(4,2)$ & $(4,3)$ & $(4,4)$ & $(4,5)$ & $\cdots$ \\
\tikzmark{5-1}{$(5,1)$} & $(5,2)$ & $(5,3)$ & $(5,4)$ & $(5,5)$ & $\cdots$ \\
$\vdots$ & $\vdots$ & $\vdots$ & $\vdots$ & $\vdots$ & $\ddots$ \\
\end{tabular}

\tikz[overlay,remember picture]
\draw [->,overlay,remember picture,xshift=20ex] (1-1) -- (2-1) -- (1-2) -- (1-3) -- (3-1) -- (4-1) -- (1-4) -- (1-5);

\end{document}

A: In your code, the lines just connect your nodes (x,y). To connect the lines, you have to draw them center to center:
\draw [->,overlay,remember picture,xshift=20ex] (1-1.center) -- (2-1.center) -- (1-2.center) -- (1-3.center) -- (3-1.center) -- (4-1.center) -- (1-4.center) -- (1-5.center);

The result would be:
It's not that nice aligned. If you don't have a specific reason to use tabular, i would recommend array here:
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{comment}
\usepackage{tikz}

\newcommand {\tikzmark}[2]{%
    \tikz[overlay,remember picture] \node (#1) {#2};}
\begin{document}
\[
\begin{array}{*6{c}}
(1,1) & (1,2) & (1,3) & (1,4) & (1,5) & \cdots \\
(2,1) & (2,2) & (2,3) & (2,4) & (2,5) & \cdots \\
(3,1) & (3,2) & (3,3) & (3,4) & (3,5) & \cdots \\
(4,1) & (4,2) & (4,3) & (4,4) & (4,5) & \cdots \\
(5,1) & (5,2) & (5,3) & (5,4) & (5,5) & \cdots \\
\vdots & \vdots & \vdots & \vdots & \vdots & \ddots \\
\end{array}
\]

\[
\begin{array}{*6{c}}
\tikzmark{1-1}{(1,1)} & \tikzmark{1-2}{(1,2)} & \tikzmark{1-3}{(1,3)} & \tikzmark{1-4}{(1,4)} & \tikzmark{1-5}{(1,5)} & \cdots \\
\tikzmark{2-1}{(2,1)} & \tikzmark{2-2}{(2,2)} & \tikzmark{2-3}{(2,3)} & (2,4) & (2,5) & \cdots \\
\tikzmark{3-1}{(3,1)} & \tikzmark{3-2}{(3,2)} & (3,3) & (3,4) & (3,5) & \cdots \\
\tikzmark{4-1}{(4,1)} & (4,2) & (4,3) & (4,4) & (4,5) & \cdots \\
\tikzmark{5-1}{(5,1)} & (5,2) & (5,3) & (5,4) & (5,5) & \cdots \\
\vdots & \vdots & \vdots & \vdots & \vdots & \ddots \\
\end{array}
\]

\tikz[overlay,remember picture]
\draw[->,overlay,remember picture] (1-1.center) -- (2-1.center) -- (1-2.center) -- (1-3.center) -- (2-2.center) -- (3-1.center) -- (4-1.center) -- (3-2.center) -- (2-3.center) -- (1-4.center) -- (1-5.center);

\end{document}

The result is much nicer:

Sadly it does not solve the problem of the unequally spaced entries completly. I Think that has something todo with making some entries nodes while some are not, but I'm not sure of that.

A: Since you want some math environment I would recommend array or matrix (from amsmath). The line can be drawn as a plot between the coordinates. I also did a slight change in \tikzmark command to get a better overview when writing the matrix.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{comment}
\usepackage{tikz}

\newcommand{\tikzmark}[2]{\tikz[remember picture] \node (#1-#2) {$(#1,#2)$};}
%%
\begin{document}

\begin{displaymath}
  \begin{matrix}
    \tikzmark{1}{1} & \tikzmark{1}{2} & \tikzmark{1}{3} & \tikzmark{1}{4} & \tikzmark{1}{5} & \cdots\\
    \tikzmark{2}{1} & \tikzmark{2}{2} & \tikzmark{2}{3} & \tikzmark{2}{4} & \tikzmark{2}{5} & \cdots\\
    \tikzmark{3}{1} & \tikzmark{3}{2} & \tikzmark{3}{3} & \tikzmark{3}{4} & \tikzmark{3}{5} & \cdots\\
    \tikzmark{4}{1} & \tikzmark{4}{2} & \tikzmark{4}{3} & \tikzmark{4}{4} & \tikzmark{4}{5} & \cdots\\
    \tikzmark{5}{1} & \tikzmark{5}{2} & \tikzmark{5}{3} & \tikzmark{5}{4} & \tikzmark{5}{5} & \cdots\\
    \vdots & \vdots & \vdots & \vdots & \vdots & \ddots
  \end{matrix}
\end{displaymath}

\begin{tikzpicture}[overlay,remember picture]
  \draw[->] plot coordinates {(1-1) (2-1) (1-2) (1-3) (3-1) (4-1) (1-4) (1-5) (5-1)};
\end{tikzpicture}

\end{document}

A: With {NiceArray} of nicematrix. That environment is similar to the classical {array} (of array) but creates PGF/Tikz nodes under the cells, rows and colummns. It's possible to use these nodes to draw whatever rule you want with Tikz in the \CodeAfter of the environment.
\documentclass{article}
\usepackage{nicematrix,tikz}

\begin{document}

\renewcommand{\arraystretch}{1.4}
$\begin{NiceMatrix}
(1,1)  & (1,2)  & (1,3)  & (1,4)  & (1,5)  & \dots  \\
(2,1)  & (2,2)  & (2,3)  & (2,4)  & (2,5)  & \dots  \\
(3,1)  & (3,2)  & (3,3)  & (3,4)  & (3,5)  & \dots  \\
(4,1)  & (4,2)  & (4,3)  & (4,4)  & (4,5)  & \dots  \\
(5,1)  & (5,2)  & (5,3)  & (5,4)  & (5,5)  & \dots  \\
\vdots & \vdots & \vdots & \vdots & \vdots & \ddots \\
\CodeAfter
  \tikz \draw [->]
                 (1-1.center)
              -- (2-1.center)
              -- (1-2.center)
              -- (1-3.center)
              -- (3-1.center)
              -- (4-1.center)
              -- (1-4.center)
              -- (1-5.center)
              -- (5-1.center) ;
\end{NiceMatrix}$

\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).

A: The alignment issue pointed out by SeverinBang is due to the overlay option for horizontal alignment, and the node anchor for vertical alignment.
You can see the effect of overlay in the original code of the question by drawing the box created by tikzmark command with fbox:
\newcommand {\tikzmark}[2]{%
    \setlength{\fboxsep}{0pt}\fbox{\tikz[overlay,remember picture] \node (#1) {#2};}
}

The cells with tikzmark have zero width and zero height, and that null box is what is aligned with cells with normal text. If the overlay option is removed:
\newcommand {\tikzmark}[2]{%
    \setlength{\fboxsep}{0pt}\fbox{\tikz[remember picture] \node (#1) {#2};}
}

Now tikz command creates a box that is taken into account by the tabular environment. The horizontal alignment is not perfect because the definition of tikzmark command includes a carriage return at the end which is equivalent to a space (you can remove it with a %). In addition, the box created by node has a margin of 0.33em with respect the contents of the node by default. This distance can be modified by inner sep option:
\newcommand {\tikzmark}[2]{%
    \setlength{\fboxsep}{0pt}{\tikz[remember picture] \node[inner sep=0pt] (#1) {#2};}%
}

The vertical alignment depends on the alignment of the box created by tikz with the baseline of surrounding text. Without any special options, the box created by tikz is positioned just over the baseline of the surrounding text (it has a zero depth).

You can change that with the baseline option, that defines at which point in the tikz picture will be anchored the baseline:
\newcommand {\tikzmark}[2]{%
    \setlength{\fboxsep}{0pt}\fbox{\tikz[remember picture, baseline=(#1.base)] \node[inner sep=0pt] (#1) {#2};}%
}

Finally, if the line must connect the node centers, you can use the solution proposed by StefanH, or define two nodes on tikzmark command: one for reference, and one for the text,
\newcommand {\tikzmark}[2]{%
    \tikz[remember picture, baseline=(A.base)] \draw coordinate (#1) node[inner sep=0pt] (A) {#2};%
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Feynman-Kac for jump-diffusion I'm looking for a more general Feynman-Kac formula that works in the case of jump-diffusion processes.
I know that, given a pure diffusion process like
$$dS_t=\mu_tdt+\sigma_tdW_t,$$ if $u(t,s)$ satisfies the PDE
$$f_t(t,s)+\mu_tf_s(t,s)+\frac{\sigma_t^2}{2}f_{ss}(t,s)-V(s)f(t,s)=0$$ with terminal condition $f(T,s)=H(S_T)$
then $u$ is of the form $$u(t,s)=\mathbb{E}\big[e^{-\int_t^T{V(S_x)dx}}H(S_T)|S_t=s\big].$$
Is it possible to extend such a result when the process dynamics are given by
$$dS_t=\mu_tdt+\sigma_tdW_t+\gamma_tdN_t$$ with $N$ a Poisson process independent fom $W$?

A: Hi it is possible to get some Feynman-Kac formula in this case. The proof only use the martingale property and Itô's formula for jump-diffusion processes.
So let's have $X$ s.t. (I took the compensated version of your sde):
$dX_t=[\mu(t,X_t)+\lambda(t)\gamma(t,X_t)]dt + \sigma(t,X_t)dW_t+ \gamma(t,X_{t-})d\tilde{N}_t$ where $\tilde{N}_t$ is a compensated Poisson process of intensity $\lambda(t)$.
Please notice the explicit dependence in $t$ and $X_t$ of the above equation that is necessary to have Markov property for the solution which is necessary for the Feynman-Kac theorem to apply.
Now let's us be given $F(t,X_t)=e^{-\int_s^t V(X_r)dr}u(t,X_t)=e^{-IV(s,t)}.u(t,X_t)$ and apply Itô to this formula. You get :
$$dY_t=dF(t,X_t)=e^{-IV(s,t)}\Big(\big(\partial_t u(t,X_t)+\lambda(t)[u(t,X_t+\gamma(t,X_t))-u(t,X_t)]+\mu(t,X_t)\partial_x u(t,X_t)+\frac{\sigma^2(t,X_t)\partial_{xx}u(t,X_t)}{2}-V(t,X_t).u(t,X_t)\big)dt+ (u(t,X_t+\gamma(t,X_t))-u(t,X_t))d\tilde{N}_t+(\sigma(t,X_t)\partial_{x}u(t,X_t))dW_t\Big)$$
Now if the $dt$ term is null then $Y_t$ is martingale and for $t=T$ :
$$Y_s=F(s,X_s=x)=E[Y_T|X_s=x]=E[e^{-\int_s^T V(X_r)dr}H(X_T)|X_s=x]$$
So in this case the PIDE that solves the Feynman-Kac formula is :
$$\partial_t u(t,X_t)+\mu(t,x)\partial_x u(t,x)+\frac{\sigma^2(t,x)}{2}\partial_{xx}u(t,x)+\lambda(t)[u(t,x+\gamma(t,x))-u(t,x)]=V(t,x)u(t,x) $$
With final condition $u(T,x)=H(x)$
Best regards


text:
Q: How to summarize the top n values across multiple columns row wise? In my dataframe, I have multiple columns with student grades. I want to sum the "Quiz" columns (e.g., Quiz1, Quiz2). However, I only want to sum the top 2 values, and ignore the others. I want to create a new column with the total (i.e., the sum of the top 2 values).
One issue is that some students have grades that tie for the top 2 grades in a given row. For example, Aaron has a high score of 42, but then there are two scores that tie for the second highest (i.e., 36).
Data
df <-
  structure(
  list(
    Student = c("Aaron", "James", "Charlotte", "Katie", "Olivia",
                "Timothy", "Grant", "Chloe", "Judy", "Justin"),
    ID = c(30016, 87311, 61755, 55323, 94839, 38209, 34096,
           98432, 19487, 94029),
    Quiz1 = c(31, 25, 41, 10, 35, 19, 27, 42, 15, 20),
    Quiz2 = c(42, 33, 34, 22, 23, 38, 48, 49, 23, 30),
    Quiz3 = c(36, 36, 34, 32, 43, 38, 44, 42, 42, 37),
    Quiz4 = c(36, 43, 39, 46, 40, 38, 43, 35, 41, 41)
  ),
  row.names = c(NA, -10L),
  class = c("tbl_df", "tbl", "data.frame")
)

I know that I can use pivot_longer to do this, which allows me to arrange by group, then take the top 2 values for each student. This works fine, but I would like a more efficient way with tidyverse, rather than having to pivot back and forth.
What I Tried
library(tidyverse)

df %>%
  pivot_longer(-c(Student, ID)) %>%
  group_by(Student, ID) %>%
  arrange(desc(value), .by_group = TRUE) %>%
  slice_head(n = 2) %>%
  pivot_wider(names_from = name, values_from = value) %>%
  ungroup() %>%
  mutate(Total = rowSums(select(., starts_with("Quiz")), na.rm = TRUE))

I also know that if I wanted to sum all the columns on each row, then I could use rowSums, as I made use of above. However, I am unsure how to do rowSums of just the top 2 values in the 4 quiz columns.
Expected Output
# A tibble: 10 × 7
   Student      ID Quiz2 Quiz3 Quiz1 Quiz4 Total
   <chr>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Aaron     30016    42    36    NA    NA    78
 2 Charlotte 61755    NA    NA    41    39    80
 3 Chloe     98432    49    NA    42    NA    91
 4 Grant     34096    48    44    NA    NA    92
 5 James     87311    NA    36    NA    43    79
 6 Judy      19487    NA    42    NA    41    83
 7 Justin    94029    NA    37    NA    41    78
 8 Katie     55323    NA    32    NA    46    78
 9 Olivia    94839    NA    43    NA    40    83
10 Timothy   38209    38    38    NA    NA    76

A: Based on this StackOverflow answer.
library(tidyverse)

df <-
  structure(
    list(
      Student = c("Aaron", "James", "Charlotte", "Katie", "Olivia",
                  "Timothy", "Grant", "Chloe", "Judy", "Justin"),
      ID = c(30016, 87311, 61755, 55323, 94839, 38209, 34096,
             98432, 19487, 94029),
      Quiz1 = c(31, 25, 41, 10, 35, 19, 27, 42, 15, 20),
      Quiz2 = c(42, 33, 34, 22, 23, 38, 48, 49, 23, 30),
      Quiz3 = c(36, 36, 34, 32, 43, 38, 44, 42, 42, 37),
      Quiz4 = c(36, 43, 39, 46, 40, 38, 43, 35, 41, 41)
    ),
    row.names = c(NA, -10L),
    class = c("tbl_df", "tbl", "data.frame")
  )

df %>%
  rowwise() %>%
  mutate(Quiz_Total = sum(sort(c(Quiz1,Quiz2,Quiz3,Quiz4), decreasing = TRUE)[1:2])) %>%
  ungroup()
#> # A tibble: 10 × 7
#>    Student      ID Quiz1 Quiz2 Quiz3 Quiz4 Quiz_Total
#>    <chr>     <dbl> <dbl> <dbl> <dbl> <dbl>      <dbl>
#>  1 Aaron     30016    31    42    36    36         78
#>  2 James     87311    25    33    36    43         79
#>  3 Charlotte 61755    41    34    34    39         80
#>  4 Katie     55323    10    22    32    46         78
#>  5 Olivia    94839    35    23    43    40         83
#>  6 Timothy   38209    19    38    38    38         76
#>  7 Grant     34096    27    48    44    43         92
#>  8 Chloe     98432    42    49    42    35         91
#>  9 Judy      19487    15    23    42    41         83
#> 10 Justin    94029    20    30    37    41         78

A: with base R - select just the quiz result columns and you can treat it like a matrix. apply sort in decreasing order, subsetting first two elements, and then use colSums.
df$Total <- colSums(apply(df[grepl("Quiz", names(df))], 1, function(x) sort(x, decreasing = TRUE)[1:2]))

df
#> # A tibble: 10 × 7
#>    Student      ID Quiz1 Quiz2 Quiz3 Quiz4 Total
#>    <chr>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1 Aaron     30016    31    42    36    36    78
#>  2 James     87311    25    33    36    43    79
#>  3 Charlotte 61755    41    34    34    39    80
#>  4 Katie     55323    10    22    32    46    78
#>  5 Olivia    94839    35    23    43    40    83
#>  6 Timothy   38209    19    38    38    38    76
#>  7 Grant     34096    27    48    44    43    92
#>  8 Chloe     98432    42    49    42    35    91
#>  9 Judy      19487    15    23    42    41    83
#> 10 Justin    94029    20    30    37    41    78

A: You do not have to do pivot_wider. Note that the longer format is the tidy format. Just do pivot_longer and left_join:
df %>%
  left_join(pivot_longer(., -c(Student, ID)) %>%
  group_by(Student, ID) %>%
  summarise(Total = sum(sort(value, TRUE)[1:2]), .groups = 'drop'))

# A tibble: 10 x 7
   Student      ID Quiz1 Quiz2 Quiz3 Quiz4 Total
   <chr>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Aaron     30016    31    42    36    36    78
 2 James     87311    25    33    36    43    79
 3 Charlotte 61755    41    34    34    39    80
 4 Katie     55323    10    22    32    46    78
 5 Olivia    94839    35    23    43    40    83
 6 Timothy   38209    19    38    38    38    76
 7 Grant     34096    27    48    44    43    92
 8 Chloe     98432    42    49    42    35    91
 9 Judy      19487    15    23    42    41    83
10 Justin    94029    20    30    37    41    78

A: Yet another solution, based on tidyverse:
library(tidyverse)

df %>%
  rowwise %>%
  mutate(Quiz = list(c_across(starts_with("Quiz")) *
   if_else(rank(c_across(starts_with("Quiz")),ties.method="last")>=3,1,NA_real_)),
    across(matches("\\d$"), ~ NULL), total = sum(Quiz, na.rm = T)) %>%
  unnest_wider(Quiz, names_sep = "")

#> # A tibble: 10 × 7
#>    Student      ID Quiz1 Quiz2 Quiz3 Quiz4 total
#>    <chr>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1 Aaron     30016    NA    42    36    NA    78
#>  2 James     87311    NA    NA    36    43    79
#>  3 Charlotte 61755    41    NA    NA    39    80
#>  4 Katie     55323    NA    NA    32    46    78
#>  5 Olivia    94839    NA    NA    43    40    83
#>  6 Timothy   38209    NA    38    38    NA    76
#>  7 Grant     34096    NA    48    44    NA    92
#>  8 Chloe     98432    42    49    NA    NA    91
#>  9 Judy      19487    NA    NA    42    41    83
#> 10 Justin    94029    NA    NA    37    41    78

A: (A bit messy) Base R Solution:
# Store the names of quiz columns as a vector: quiz_colnames => character vector
quiz_colnames <- grep("Quiz\\d+", names(df), value = TRUE)

# Store the names of the non-quiz columns as a vector: non_quiz_colnames => character vector
non_quiz_colnames <- names(df)[!(names(df) %in% quiz_colnames)]

# Store an Idx based on the ID: Idx => integer vector:
Idx <- with(df, as.integer(factor(ID, levels = unique(ID))))

# Split-Apply-Combine to calculate the top 2 quizes: res => data.frame
res <- data.frame(
  do.call(
    rbind,
    lapply(
      with(
        df,
        split(
          df,
          Idx
        )
      ),
      function(x){
        # Extract the top 2 quiz vectors: top_2_quizes => named integer vector
        top_2_quizes <- head(sort(unlist(x[,quiz_colnames]), decreasing = TRUE), 2)
        # Calculate the quiz columns not used: remainder_quiz_cols => character vector
        remainder_quiz_cols <- quiz_colnames[!(quiz_colnames %in% names(top_2_quizes))]
        # Nullify the remaining quizes: x => data.frame
        x[, remainder_quiz_cols] <- NA_integer_
        # Calculate the resulting data.frame: data.frame => env
        transform(
          cbind(
            x[,non_quiz_names],
            x[,names(top_2_quizes)],
            x[,remainder_quiz_cols]
          ),
          Total = sum(top_2_quizes)
        )[,c(non_quiz_names, "Quiz2", "Quiz3", "Quiz1", "Quiz4", "Total")]
      }
    )
  ),
  row.names = NULL,
  stringsAsFactors = FALSE
)

A: Try this base R to also get the NAs
cbind( df[,1:2], t( sapply( seq_along( 1:nrow( df ) ), function(x){
  ord <- order( unlist( df[x,3:6] ) )[1:2]; arow <- df[x,3:6];
  arow[ord] <- NA; ttl <- rowSums( arow[-ord], na.rm=T );
  cbind( arow,Total=ttl ) } ) ) )

     Student    ID Quiz1 Quiz2 Quiz3 Quiz4 Total
1      Aaron 30016    NA    42    NA    36    78
2      James 87311    NA    NA    36    43    79
3  Charlotte 61755    41    NA    NA    39    80
4      Katie 55323    NA    NA    32    46    78
5     Olivia 94839    NA    NA    43    40    83
6    Timothy 38209    NA    NA    38    38    76
7      Grant 34096    NA    48    44    NA    92
8      Chloe 98432    NA    49    42    NA    91
9       Judy 19487    NA    NA    42    41    83
10    Justin 94029    NA    NA    37    41    78

A: As @akrun provided above, collapse is another efficient possibility. radixorder provides an integer ordering vector, and only the top 2 values in each row are kept, while the others are replaced with NA. Then, rowSums is used to get the totals for each row.
library(collapse)

ftransform(gvr(df, "Student|ID"),
           dapply(
             gvr(df, "^Quiz"),
             MARGIN = 1,
             FUN = function(x)
               replace(x, radixorder(radixorder(x)) %in% 1:2, NA)
           )) %>%
  ftransform(Total = rowSums(gvr(., "^Quiz"), na.rm = TRUE))

Output
# A tibble: 10 × 7
   Student      ID Quiz1 Quiz2 Quiz3 Quiz4 Total
 * <chr>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Aaron     30016    NA    42    NA    36    78
 2 James     87311    NA    NA    36    43    79
 3 Charlotte 61755    41    NA    NA    39    80
 4 Katie     55323    NA    NA    32    46    78
 5 Olivia    94839    NA    NA    43    40    83
 6 Timothy   38209    NA    NA    38    38    76
 7 Grant     34096    NA    48    44    NA    92
 8 Chloe     98432    NA    49    42    NA    91
 9 Judy      19487    NA    NA    42    41    83
10 Justin    94029    NA    NA    37    41    78


text:
Q: Multiple Comparable in a class I'd like to know if is possible implementing more Comparables for a single class.
I have first to order my arraylist by a integer field and next in another part of my program i have to order it by another field.
How i can do that? I thought about a custom Comparator but it didn't work.
public void OrderbyColours(ArrayList<Horses> scuOrderedByColours,
        ArrayList<Horses> ArrayScud) {
    scuOrderedByColours.addAll(ArrayScud);
    Collections.sort(scuOrderedByColours, new Comparator<Horses>() {
        public int compare(Horses o1, Horses o2) {
            return o1.Position - o2.Position;
        }
    });
}

A: Assuming Comparators are not working(which i'm curious as to how they're not working), or you simply don't want to use one, you could write a wrapper class that has an instance of your original class as data.
ex.
public class HorsesWrapper implements Comparable<HorsesWrapper>
{
  private Horses horses;

  public int compareTo(HorsesWrapper other)
  {
    // your sort criteria based on the Horse member.
  }
}


text:
Q: Display loading message for long running process protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            Response.Write("

");
            Response.Flush();
            LoadDirs();
            Response.Write("");
        }
    }

LoadDirs() builds a List< TreeNode > and then adds them to the TreeView.
It seems the 2nd Write to clear the loading image happens right away.
I don't want the loading image to disappear until LoadDirs() is completely finished.

A: I think you should use UpdatePanel and UpdateProgress
An introduction here => http://msdn.microsoft.com/en-us/library/vstudio/bb386421(v=vs.100).aspx


text:
Q: Get fingerprint of current page's SSL certificate in a Chrome extension I'm attempting to write an extension which verifies the SHA1 fingerprint of a site's SSL certificate with a third party. However it doesn't seem to be possible to do this either through native JavaScript or Chrome's extension APIs.
I found this question which would seem to do what I want: How can I get the SSL Certificate info for the *current* page in a Firefox Extension
But unfortunately it is only applicable to Firefox. Is there any way to do this in a cross browser compatible way, or even just in Chrome?

A: Not as of January 2014 (but there are bug reports on file).
Firefox
Firefox currently only has a way to provide certificate information passively, without any extension API to be able to block a connection that is deemed to have an inappropriate certificate.  There's Mozilla Bug #644640 — "Implement extension point for extensions to influence trust decisions in PSM", which is tracking the ability to decline connections.
Chromium
Chrome, on the other hand, doesn't even let you examine the certificate in the first place; there's Chromium Issue #107793 — "Provide information about the TLS connections to extensions via the webRequest API", which appears to track both the ability to simply examine the certificates in the first place, and also to revoke trust, if needed.
(There's also an earlier Chromium Issue #49469 — "Feature request: Implement Extensions API for accessing information about HTTPS/SSL certificate for web page", but it would seem like Issue #107793 has taken over.)
The draft of Chromium API proposal as linked to Issue 107793 above (note that it's only a draft of the proposed interface, without an actual implementation so far):

*

*https://sites.google.com/a/chromium.org/dev/developers/design-documents/extensions/proposed-changes/apis-under-development/webrequest-ssl-hooks


text:
Q: What is the difference between "provisioned" and "provided" I'm reading this article and they wrote:

After the identity is created, the credentials are provisioned onto
  the instance.

What I understand is that the credentials will be given to then instance and when I looked up provision I've ended up at:

something provided;
the providing or supplying of something, especially of food or other necessities.

So what is the difference between provided and provisioned? Can't we say

After the identity is created, the credentials are provided onto
  the instance.

And have the same meaning?

A: We are in the IT domain where specialist terminology is used. To my eyes the phrase in question is slightly odd, but acceptable in an IT context.
The general concept of supplying credentials is frequently referred to as provisioning. See this article as a random example. In my experience we would say:

Oh, I've nearly finished, just a bit of provisioning to do now ...

We would not use provide or its derivitives in this way.
In this environment where provisioning is widely understood,

the credentials are provisioned onto the instance

we might say

the instance is provisioned with the credential

but I'm not sure it's better. In the mind of the person doing the job they have created a set of credentials and are applying them to the instance, rather like attaching a bit to a drill; the focus is selecting the right implement, the credentials, so that dominates the phrase.

A: The author there is using language rather freely. The verb provisioned onto doesn't really exist in English.  The verb provision is transitive, taking a direct object and  an optional prepositional phrase introduced by with:

Headquarters provisioned the rescue team with food, blankets, and satellite radios.

In this context, where a computing object is supplied to a class instance which presumably then encapsulates that object, there is really no meaningful difference between provided to and supplied to or even sent to.  I don't see what the preposition onto adds to our understanding, and it is not idiomatic with that verb.


text:
Q: Filling In Empty Dates With Previous Data in Pandas So I have the current file in Excel where I have dates and don't have dates for everything which can be seen.

I read this excel file into a pandas dataframe, rename the column and get the following:

My question is, how would I get it so every empty date in the dataframe is filled in with the last previous date encountered. All of the blanks between 04/03/2021 and 05/03/2021 gets replaced with 04/03/2021, so every row in my dataframe has a date associated with it?
Thanks!

A: After reading the data into a dataframe, you can fill missing values using fillna with method='ffill' for forward fill

A: Just using the inbuilt way in pandas of:
duplicate_df['StartDate'] = duplicate_df['StartDate'].fillna(method = 'ffill')

This replaces all the NaNs in the dataframe with the last row that had data in.


text:
Q: How is it possible to avoid the duplication of 401 error response for each api path? ( OpenApi 3 ) I defined my authentication in security and components/securitySchemes.
In the Swagger documentation about response, they provide this example:
paths:
  /something:
    get:
      ...
      responses:
        ...
        '401':
           $ref: '#/components/responses/UnauthorizedError'
    post:
      ...
      responses:
        ...
        '401':
          $ref: '#/components/responses/UnauthorizedError'
...
components:
  responses:
    UnauthorizedError:
      description: Authentication information is missing or invalid
      headers:
        WWW_Authenticate:
          schema:
            type: string

I have a lot more paths than two, and to access any of them, the client has to be authenticated. I would like to avoid the '401' definition for each path, and define it once globally, if it is possible somehow.
How is it possible to use this response for each path?
'401':
  $ref: '#/components/responses/UnauthorizedError'

A: You can't, if you want the response to show up on that particular endpoint.
I avoid the repetition in favour of important errors by not adding them to each endpoint and instead putting the well understood standard responses - 401, 403, 429, 404, 503 - on either a status endpoint or on the root method. eg:
  '/{foo}/{bar}/status':
    get:
      tags:
        - api
      responses:
        '200':
          description: successful response with a resource
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/statusResponse'
        '400':
          $ref: '#/components/responses/400_error_response'
        '401':
          $ref: '#/components/responses/401_error_response'
        '403':
          $ref: '#/components/responses/403_error_response'
        '404':
          $ref: '#/components/responses/404_error_response'
        '500':
          $ref: '#/components/responses/500_error_response'

The boilerplate responses would then all refer to the standard responses.
Real endpoints then typically have a well defined response specific to that opearation and the things that may go specifically wrong.
  '/{foo}/{bar}/segment':
    post:
      summary: checks username is found or not
      description: |-
        checks username and returns 204 if found else 403
      operationId: checkUsername
      tags:
        - Login
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/segment_POST_request'
      responses:
        '200':
          $ref: '#/components/responses/segment_POST_200_response'
        '403':
          $ref: '#/components/responses/403_forbidden_response'
        '500':
          $ref:
 '#/components/responses/500_internal_server_error_replayable_response'

One thing I ensure is for error responses, the possible error codes for that operation are included in the response, like so:
    500_internal_server_error_replayable_response:
      description: |-
        The following `500 Internal Server Error` errors can occur during the API processing.

        | errorCode | cause | details |
        | - | - | - |
        | `SOME.ERROR.500` | There was an error processing the request either in Foo or on a downstream system | A request to something failed, Bar or Baz however the error is recoverable and can be replayed |
        | `SOME.ERROR.014` | Baz returned a `404` during the migration operation, even though it has previously confirmed the member exists | This is a fatal error during the migration process and cannot be recovered. The request should not be replayed. |
      headers:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/errorResponse'
          example:
            status: '500'
            errorCode: SOME.ERROR.500
            errorDescription: The request could not be processed
            errorSubCode: ''
            furtherDetails: ''
            docLink: ''

A: Use an extension to add them in automatically as part of your build script.
What you're looking to do is not part of the OpenAPI standard. Responses are not inherited from parent objects; they must be explicitly added to every endpoint. You can include a $ref for each response, but with a well-defined spec with lots of endpoints, you'll end up with a lot of duplication, and it's likely an endpoint might miss a response or two over time as additions and modifications are made. Plus, it's simply not a good authoring experience.
To prevent this problem, add an extension to your responses, like this:
responses:
  x-default-responses: true
  '418':
    description: Additional responses go here

The above spec will be the one that you work from. When done, have a script scan your completed yaml file, and replace that line with your list of default responses. Use this modified spec as the next stage of your development process (whatever it is you're using your OpenAPI spec for, be it documentation, testing, or SDK generation).
While you could have your script add the responses without the extension property (after all, it is just YAML you're writing), I recommend you don't do this. The extension makes your intent clear, so other editors will understand additional responses are present. Additionally, it is likely that (either now or one day in the future) you will have endpoints that do not conform to your default responses, so you wouldn't want to accidentally add those.


text:
Q: Save Web Service Response as XML I'm working with HP UFT nad HP ALM. I'm trying to save a web service response as xml in an API-Test. I found many tutorials to save a response in an Excel but it's not what I want.
Is this possible? If not, is it possible to download an .wsdl response?
API-Test construction

*

*Control if there exist an specific xml file(refernce.xml) on my computer

*If not then stop the test/if the reference.xml exist then keep going

*Now I want to save the response

*Compare the 2 files(reference.xml and downloaded xml)

A: In Api Tests/Components you can do this by simply using the standard activities available.
In the Toolbox menu, under 'Standard Activities' expand the 'File' list and add the 'Write to File' activity to your flow. Then, in the Input/Checkpoints tab of the activity you can set the export path (in the path you should include the name.xml file that will be generated) and the content (for the content you can select the main tag of the response, that holds all the content :  for example).

https://community.hpe.com/t5/Unified-Functional-Testing/UFT-API-Save-Response-as-xml/td-p/6867566

A: In Api Tests/Components you can do this by simply using the standard activities available.
In the Toolbox menu, under 'Standard Activities' expand the 'File' list and add the 'Write to File' activity to your flow. Then, in the Input/Checkpoints tab of the activity you can set the export path (in the path you should include the name.xml file that will be generated) and the content (for the content you can select the main tag of the response, that holds all the content:` for example).
Source: https://community.hpe.com.


text:
Q: Passing parametric input parameter to batch file This might be a simple question, but I didn't found any thread, may be I am searching wrong.
I am having a simple bat script and passing some arguments. Currently I am getting the argument based on there order. But I want to make simple for the user.
My current command line looks like: testBatch.bat setupip setupuser setuppass
My current batch script looks like:
set setupip=%1
set setupuser=%2
set setuppass=%3
echo I am doing some operation after this based on the input I got.

Now I want to modify the command such that the user should not be woried about the order of argument to pass. Basically I want to see my command like this: testBatch.bat --ip setupip --user setupuser --password setuppass
What modification I have to do in my batch script?

A: Thing you are looking for is called 'Named Arguments'. I found link for same question here.
Answer Which I like from that link is as follow:
set c=defaultC
set s=defaultS
set u=defaultU

:initial
if "%1"=="" goto done
echo              %1
set aux=%1
if "%aux:~0,1%"=="-" (
   set nome=%aux:~1,250%
) else (
   set "%nome%=%1"
   set nome=
)
shift
goto initial
:done

echo %c%
echo %s%
echo %u%

Run the following command:
arguments.bat -c users -u products

Will generate the following output:
users
defaultS
products

A: try this:
@echo off

for %%a in (%*) do (
    call set "%%~1=%%~2"
    shift
)

echo :%--user%
echo :%--pass%

if the passed it is called like:
namedArgs.bat --user user --pass pass

the output will be like:

:user
:pass

This will handle also quoted parameters with spaces in them.

A: There is a batch command called shift, which can basically do a shift left on your parameter variables.
So as the start of your script, you need a loop
inside that loop you decode %1 for the 'verb' part of your option with a if statement
inside that if block, you call shift.  then old %2 becomes the new%1, old %3 becomes the new %2, etc
so inside that if, you can pick up a secondary argument for the verb, if needed.  Then call shift again.
loop until your arguments are empty.  Tadah!


text:
Q: count bw and color pages from PDF in PHP Does someone knows a workable solution for the following:
A PDF file needs to be checked if it contains colored pages. Need to know total pages in black/white and total pages with some colors on it (images or colored text).
Thanks for any ideas!
More info #1:
We expect mainly plain "word" like created PDFs with some images and some colored text elements/boxes. Full scanned pages are not expected in this process.

A: See this answer for a Ghostscript-based tool:

*

*Ghostscript grayscale conversion still contains colors?
It uses the new inkcov device to determine the distribution of C (cyan), Y (yellow), M (magenta) and K (black) components (ink coverage) of each page. You'll need a Ghostscript version of 9.05 or newer.
Example command line:
gs -q  -o - -sDEVICE=inkcov temp.pdf
 0.00000  0.00000  0.00000  0.02230 CMYK OK
 0.00000  0.00000  0.00000  0.02360 CMYK OK
 0.00000  0.00000  0.00000  0.02525 CMYK OK
 0.00000  0.00000  0.00000  0.01982 CMYK OK

Each page with zeros only for C, M and Y will be black/white only.

A: Probably the easiest way to do that is to use a tool to render the PDF to a set of images and then use a small program to determine if the colors used in those images are grayscale only or not.
The second step can be performed by loading each and every image and scanning the pixels.   For scanned pages: determining if something is grayscale is not trivial since you need to consider the whitepoint, blackpoint for each page and possibly lighting coloring of edges etc etc. I once created a tool te determine if something is just text or b/w lineart by obtaining the the 2D historgram of Abs( R- G ) and Abs( R - B ), plotting a straight line  and check if that line and the regression constant where within some predefined ranges.


text:
Q: dispatch_async() "silently" failing -- why? All:
I am wrestling with a dispatch_async() problem.  My goal is for a TableViewController (TopStoriesTVC) to display some rss feeds.  The xml fetching and parsing is factored into a class called Reporter.
TopSToriesTVC tells the Reporter to fetchNewsFrom:.  Once that's done, and the xml parsing is finished, the Reporter invokes TopStoriesTVC's fileStories:fromReporter: method.
           -(void) fetchNewsFrom:(NSString *)url

TopStoriesTVC ===================================>   Reporter
             -(void)fileStories: fromReporter:
           <===================================

This works great in a single-threaded environment.  But, I want to grab several rss streams, so instead of:
// In TopStoriesTVC ...
-(id)initWithNibName:bundle: {
     // stuff omitted
     [self.newsReporter fetchNewsFrom:TOP_STORIES_NEWS_URL];
     [self.sportsReporter fetchNewsFrom:TOP_STORIES_SPORTS_URL];

}

// in Reporter...
-(void)parserDidEndDocument:(NSXMLParser *)parser{
    [self.bureauChief fileStories:self.items fromReporter:self];
}

which works perfectly, I have tried to wrap them using dispatch_async():
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self.newsReporter fetchNewsFrom:TOP_STORIES_NEWS_URL];
    [self.sportsReporter fetchNewsFrom:TOP_STORIES_SPORTS_URL];
});

and
dispatch_async(dispatch_get_main_queue(), ^{
    [self.bureauChief fileStories:self.items fromReporter:self];
});

Those don't work at all. I am using get_main_queue() because fileStories:fromReporter: includes a [self.tableView reloadData]; statement, and I understand that needs to happen on the main thread.
When I say they "don't work at all", specifically, I get a) no error messages in the console, b) nothing in the tableView, c) my NSXMLParserDelegate methods aren't even being called, d) setting debugging statements just leads me into a bunch o' assembly language.
Can anyone spot what's going wrong here?  Or have any suggestions?  I really would appreciate it.


text:
Q: change color of a text in html using javascript I'm working on changing the color of some text using a separate .js file. I am a newbie at HTML and JavaScript, please be detailed. Thank you.
This is what I got so far:
htmlfile.html

 Click the button to change the text in this paragraph.

jsfile.js
    var button = document.createElement("button")
    button.innerHTML = "Red or green"
    // Sets or returns the content of an element

    // 2. Append somewhere
    var body = document.getElementsByTagName("body")[0]
    body.appendChild(button)
    // Adds a new child node, to an element, as the last child node

    // 3. Add event handler
    button.addEventListener("click", function () {
        state = !state
        // Attaches an event handler to the specified element

        //var led = document.createElement('LED')
        if (state = 1) {
            document.getElementById("demo").style.color = "red"
        } else {
            document.getElementById("demo").style.color = "green"
        }
        //body.appendChild(led)
    })
}

A:

status = 1;
function switchStyle() {
x = document.getElementById("text");
if(status==1) {
    x.style.color = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.color = 'red';
    status = 1;
}
}

This text color will change.

<button type="button" onclick="javascript:switchStyle();">Switch Style</button>

A: a couple of advices:

*

*use document.body instead of getElementsByTagName('body')

*use semicolons at the end of lines (instructions)

*create state var outside addEventListener function

*if you compare values in if() condition, use == or === instead =

var button = document.createElement('button');
button.innerHTML = 'Red or green';

document.body.appendChild(button);

var state = 0;

button.addEventListener('click', function (){
   var demo =  document.getElementById("demo");

   if (state === 1) {
     demo.style.color = 'red';
     state = 0;
     } else {
       demo.style.color = 'green';
       state = 1;
    }
});

Click the button to change the text in this paragraph.


text:
Q: When is an HTTP cookie set? Does the browser set a cookie after it receives the header or after it receives the body? This is relevant when sending a large file in the body of the request.

A: I would think a browser would set the cookie as it is processing the response headers, since the cookie information is in there. It doesn't make much sense to receive the headers, then set the cookies after it processes the html.


text:
Q: Custom input to Lambda from alarm or Custom input to SNS from Alarm I am filtering logs using metric filter. But that filter is not giving exactly what I want.
Please do someone suggest me how I could get the API calls that are failed from the log group and send the response of the failed event as an input to the alarm that is triggered which calls SNS topic which in turn calls Lambda function. Lambda function then receives the SNS message with the response for further processing.
(OR)
Is there any other way to get the failure response from the log group based on any pattern and send the failure response to the lambda function?

A:
Is there any other way to get the failure response from the log group based on any pattern and send the failure response to the lambda function?

Instead of using metric filters and alarms, you can setup subscription filter on your log group.
The subscription can be set to stream your log data in real-time to a lambda function. How to do this is shown in the AWS docs here.
The lambda function could process the logs data, identify those of interest to you, and send to SNS topic to be picked up by other function.


text:
Q: How do I find the source for bugs in Sublime Text? I have been dealing with a bug in Sublime Text in js files for a while where anytime I write a comma or semi-colon, Sublime Text creates an autocomplete box with a specific number 62118. So anytime I hit enter it will autofill this useless number and I have to delete it.
More keystrokes = More anger, so I was wondering if

*

*anyone has run into this

*or if anyone might have an idea whats causing it

*OR if anyone has a good general technique for finding bugs in Sublime Text

It seems to only happen in .js files but I could be wrong so help me out here please I'd love to keep the configuration I have.

A: There may be information in the Sublime console. To open the console go to View > Show Console (ctrl + `).
Otherwise, uninstall your plugins one by one. While it probably isn't necessary, it would be a good idea to restart Sublime each time you uninstall, to make sure any caches the plugins create are cleared.
Finally, you can simply disable autocomplete by adding the following to your User Settings.
"auto_complete": false


text:
Q: PHP Post Values with Lambda I have set up a HTML form which when submitted will use a PHP post function to then display the values in a specific layout within a text area on another page.
This is currently running on an EC2 web server, although I would like to run this as a static website on S3.
Is it possible to do this using lambda to then display the values therefore not requiring the EC2 server?

A: Yes possible, In this case, you need to run the whole project in lambda functions.
try with lambda function by adding you .php files to lambda and run.

*

*create a sample lambda function on php and write some HelloWorld program.

*attach API gateway to that function and allow all types of methods.

*if it works, add one by one and test.

if any queries comment below...:)


text:
Q: Can any relative clauses be reduced? For this sentence:

I am a student who has little money.

Can I rewrite it as:

I am a student having little money.

Do they make a same sense?
If not, when should we use the reduced relative clause instead of the relative clause?

A: Yes you can use both constructions and they mean the same.
Obviously you have your main clause and your relative clause.

I am a student who has little money.

As deadrat has correctly identified your second sentence contains a participial clause

having little money

It's a non-finite clause using a present participle. Thus, it's called a participial clause.
However, that's just half the truth because the clause still acts as a relative clause. It's mostly overlooked as even the Wikipedia entry states and not always described as such as you will see below.

Some nonfinite clauses, including infinitive and participial clauses, may also function as relative clauses. These include:
present participle clauses having an unvoiced zero subject argument that takes an antecedent to the argument: The man Ø sitting on the bank was fishing. (These clauses are the least likely to be recognized as relative clauses.)

The posted excerpt also contains the answer to your question.
You can find further explanation and examples over here and here.

A participial relative clause is a clause which resembles a relative clause but which contains a participle instead of a finite verb.

So to conclude, it's real tricky and with English having no central language authority the naming of such edge cases is always disputed. The point remains, you are a student and you don't have a lot of money, in both your sentences.


text:
Q: printing complete stack trace of an exception in android studio I am trying to print complete stack trace of the exception thrown by my android code in android studio. For this I am using exception.printStackTrace(); I have also tried to use Log.e("",Log.getStackTraceString(exception)); and Log.e("TAG", "Exception: ", e.printStackTrace()); but the exception is not being displayed on the console, and the console is showing this:

So how can I print complete stack trace of the exception on console in android studio?

A: If you don't specify .printStackTrace(), you will be fine :
Log.e("TAG", "Exception: ", e);


text:
Q: Matlab: Differentiate between p and d I am trying to write a script to automatically evalute a test (D2 Concentration Endurance Test)
An examplary image is shown here:

The goal is to cross all d's with to strikes: So you would have to cross all d's with 2 strikes below, 2 strikes above, 1 strike below and 1 strike above the letter.
So my main question is: How can I automatically differentiate if the printed letter is a d or p?
Is there a metric than I can apply to all letters, which differentiates the two letters? I tried entropy, but difference is not discernable using that metric.
I already tried OCR, but weirdly enough, ocr doesn't return any result for the letters I put in. And I think that ocr is maybe not necessary - I am only trying to differntiate between p's and d's - maybe an ocr is a bit overkill for this? This is why I thought a simple metric could be enough..
Thank you for your help!!

A: I was able to get pretty good performance with picking a centroid which minimizes the Wasserstein (earth movers) distance. I downloaded some handwritten digits for 9's and 6's here to test this out, and was able to get classification accuracy on the order of ~98-99% without a lot of effort. I picked the 9's and 6's because the rotational symmetry they have is analogous to the p's and d's in your problem.
In total I had 1000 images of a 6 and 1000 images of a 9, each 28 x 28 pixels. The pixel intensities are not binary, but performance is still good with binary pixels.
By using Wasserstein distance on images, you are viewing the observed pixel locations as realizations of a random distribution over the pixel grid. That is, for the numbers 6 and 9, there is a distribution over where pixels end up. Then, for each individual image, the obtained values can be viewed as the observed empirical sample from this distribution. This changes the problem from being viewed as "each image is a data point" to something more like "each observed pixel is a data point." Wasserstein distance is a metric on probability measures, so framing the images this way allows you to use a distance metric not immediately obviously intended for it.
The Wasserstein distance then calculates how much "mass needs to be moved" to turn one distribution into the other. This is complicated for non-atomic distributions, but for atomic distributions turns into solving a linear program, and a bunch of people have developed various softwares to do this. A good implementation of the Wasserstein distance in Matlab can be found here.
This function takes 5 arguments and gives two values:
[x, fval] = emd(F1, F2, W1, W2, Func)

For our purposes F1 and F2 are the images (more on this later), and W1 and W2 are weights for the atoms. Because we're viewing the image as an unweighted empirical distribution, we can specify W1 and W2 to be a uniform weighting. Func is a function provided at the previous link. The important output is the real valued fval result, which gives the cost of moving the mass in F1 to F2. This is our "distance", and the thing we want to minimize in our classification.
Assuming you have some pre-classified images, come up with a "centroid" for the distributions by averaging over known 6's and 9's. Define these centroids as:
% Have "canonical example" from known images
6_centroid = mean(known_sixes,3);
9_centroid = mean(known_nines,3);
% Construct storage vectors for classifications
6_classify = zeros(1,num_testing);
9_classify = zeros(1,num_testing);
% Classify each image according to which centroid is closest in Wasserstein distance:
for j = 1:num_testing
% Compute the distance between each of the testing images for nines versus the centroid for 6's
       [flow6,cost_of_flow6]=emd(test_9(:,:,j),6_centroid,(1/28)*ones(1,28),(1/28)*ones(1,28),@gdf);
    % Compute the distance between each of the testing images for nines versus the centroid for 9's
       [flow9,cost_of_flow9]=emd(test_9(:,:,j),9_centroid,(1/28)*ones(1,28),(1/28)*ones(1,28),@gdf);
       % Classify based on minimizing Wasserstein Distance
       if cost_of_flow6<=cost_of_flow9
           nine_classify(j) = 6;
       else
           nine_classify(j) = 9;
       end
    % Compute the distance between each of the testing images for sixes versus the centroid for 6's
       [flow6,cost_of_flow6]=emd(test_6(:,:,j),6_centroid,(1/28)*ones(1,28),(1/28)*ones(1,28),@gdf);
    % Compute the distance between each of the testing images for sixes versus the centroid for 9's
       [flow9,cost_of_flow9]=emd(test_6(:,:,j),9_centroid,(1/28)*ones(1,28),(1/28)*ones(1,28),@gdf);
       % Classify based on minimizing Wasserstein Distance
       if cost_of_flow6<=cost_of_flow9
           six_classify(j) = 6;
       else
           six_classify(j) = 9;
       end
end

Important One important thing to note here that drastically affects performance is how you specify the rows and columns. The emd function does not view the images as distributions over pixels in the 2d space necessarily, but distributions over rows or columns, depending on the orientation of the image. For example, if you look at the rows of the image as being the samples, then for 6's and 9's (and likely p's and d's) the distributions is not going to be as well separated in earth movers distance because both 9's and 6's concentrate the majority of their mass towards the center of the horizontal axis.
However, if you look at the columns as samples, you can see that with 9s the distribution is heavily skewed towards the top, and 6's towards the bottom. Additionally, because the numbers are taller than they are wide, there is additional mass moving that must occur because the "stuff" has to travel a further distance. This makes it such that choosing the columns as the samples gives much better performance (98% accuracy versus 73%). This is all likely true of p's and d's as well.


text:
Q: Embedding and Displaying chinese/japanese I have been working on a subtitles engine for flash/flv video player. On my Mac everything is great, nice aliased glyphs, displaying all the characters, etc. Switch to windows, it all goes out the window. Some machines with Eastern Characters enabled display fine, but I can't guarantee all users will have this option selected.
I am using the TLFTextField, I am pulling in UTF-8 XML with Chinese/Japanese characters.
I have tried embedding the (required fonts/glyphs) but pushes the file size up massively.
I have also tried changing it to unicode, with no joy. Has anyone got any experience with displaying these characters while maintaining a low file size.

A: I'm not really offering a solution to your question, but if the user is wanting Chinese or Japanese subtitles, I'm pretty sure that they will have the correct encoding.


text:
Q: Rails application issue after deployment - 404 error I'm new to RoR.
I was able to install Rails and host it in Webrick (Sample App with "Welcome" controller) in my windows.

Now i have a Unix Weblogic Server along with a dedicated domian.
After exporting the .WAR file using Warbler, i accessed the Oracle Admin Console from where i deployed the .WAR file in the dedicated domain. I did all this for the Sample app with only the Welcome controller in it.
But even after deploying the WAR file, on accessing the Domain along with the Port Number (:9002) i ended up with 404 file not found error On looking at the server logs,there wasn't any records relating to any error. The Application must have been deployed properly. I assume that i must have missed out on some basic configurations in the routes.rb or similar files before deploying. Can anyone Guess what are all the possibilities and if possible can anyone help me by pointing to any tuts that cover the Steps to be carried out for configuration before deployment. do i need to install both JRuby and Rails inside the server before depolyment?

A: I can't really guess with Eror 404  only.
You can try mapping your rails app rack config to a different base_uri.
All you need to do is wrap the existing 'run' command in a map block
try doing this in your rails 'config.ru' file:
map '/mydepartment' do
    run Myapp::Application
end

Now when you 'rails server' the app should be at localhost:3000/mydepartment .
Not sure if this will give you the desired outcome, but worth a try.
One more thing you also add this to your config/environments/production.rb and config/environments/development.rb (if on production mode):
config.action_controller.asset_path = proc { |path| "/abc#{path}" }

otherwise when you call your helpers such as stylesheet_link_tag in your views, they will generate links without the "/abc".
Also, find some guides you may refer for good support.
JRubyOnRailsOnBEAWeblogic.
Use JRuby with JMX for Oracle WebLogic Server 11g
Let me know if it is not resolved.


text:
Q: Can the :not selector be used with 'this'? I've got a div called nav, in which some other divs are placed. When I click on one, I want it to change the colour to orange, which is fine - using this.
I'd like the others to remain black when they aren't clicked though.
Can not be used with this?
$('.nav div').click(function() {
    $(this).css('color', 'orange');
    $('.nav div:not(this)').css('color', 'black');
});

A: You can add a class to all your divs and when you click on one, remove it with jQuery with
.removeClass("<name>");

Be sure to re-add it when you click on another one.

A: You can use the .not() method instead of the selector:
$(".nav div").not(this).css("color", "black");

Or you could use the .siblings() method
$(this).siblings().css("color", "black");

A: I don't think so.  Why not set them all to black, then set the special one to orange?
$('.nav').css('color', 'black');
$(this).css('color', 'orange');


text:
Q: Как реализованы ссылки на методы в Java 8 внутри JVM? Мне стало интересно, как реализованы ссылки на методы(::) в Java 8.
Для сравнения опишу, как они реализованы в Object Pascal - простейшим образом и эффективно. Указатель на метод в нем это запись из двух указателей:
TMethod = record
  Code, Data: Pointer;
end;

В одном хранится адрес процедуры, в другом - адрес объекта-владельца.
Button1.OnClick = MyClick1;

транслируется всего лишь в копирование двух указателей.
Вызов такого метода - это вызов процедуры по адресу, с передачей неявного параметра this.
Но мне здесь сказали, что в Java 8 ссылки на методы это синтаксический сахар и что за ними скрывается что то страшное. Неужели это и правда так? Кто нибудь смотрел, в какой код на JVM транслируются ссылки на методы?

A: В Java ссылки на методы - это сокращенные лямбда-выражения:
Всего существует 3 конструкции ссылок на методы:

*

*object::instanceMethod -  ссылается на объектный метод предложенного объекта

*Class::staticMethod - ссылается на статический метод класса

*Class::instanceMethod - ссылается на объектный метод предложенного объекта. Действует, так же как в п.1, только с именем класса

Примеры реализации этих конструкций и их лямбда-аналоги ниже:

*

*System.out::println равно x -> System.out.println(x)

*Math::max равно (x,y) -> Math.max(x,y)

*String::length равно x -> x.length()
Но все таки, ссылки на методы реализуются немного по-разному(об этом ниже).
По сути, лямбда выражения похожи на анонимные классы с одним методом, но реализованы по другому. Подробный разбор их реализации - ниже.

Краткая выборка из статьи, про то, как лямбды работают под капотом JVM:

Анонимные внутренние классы имеют нежелательные характеристики,
которые могут повлиять на производительность вашего приложения.
Сначала компилятор генерирует новый файл класса для каждого анонимного
внутреннего класса.  Создание многих файлов классов нежелательно,
поскольку каждый файл класса должен быть загружен и проверен перед
использованием, что влияет на производительность при запуске
приложения. Если бы лямбды были переведены в анонимные внутренние
классы, у вас был бы новый файл класса для каждой лямбды. Как
следствие, анонимные внутренние классы увеличат потребление памяти
вашим приложением.

Вместо использования для лямбда-выражений отдельного класса версия Java 8 опирается на байткод-инструкцию invokedynamic, добавленную в версии Java 7. Инструкция invokedynamic ориентирована на bootstrap-метод, который, в свою очередь, создает реализацию лямбда-выражения при первом вызове этого метода.
Перевод лямбда-выражения в байт-код выполняется в два этапа:

*

*Генерируется динамическая лямбда-фабрика, которая при вызове возвращает экземпляр функционального интерфейса, в который преобразовывается лямбда.

*Тело лямбда-выражения преобразовывается в метод, который будет вызываться с помощью  invokedynamic.

В случае ссылок на методы все происходит почти также, как и для лямбд - но javac не генерирует синтаксический метод(потому что он уже есть в классе из которого вызывается метод, а у лямбды такого класса нет), и может ссылаться на нужный метод напрямую.
Чтобы проиллюстрировать первый шаг, давайте рассмотрим байткод, сгенерированный из простого класса, содержащего лямбду:
import java.util.function.Function;

public class Lambda {
    Function<String, Integer> f = s -> Integer.parseInt(s);
}

Этот класс сгенерируется в следующий байткод:
 0: aload_0
 1: invokespecial #1 // Method java/lang/Object."<init>":()V
 4: aload_0
 5: invokedynamic #2, 0 // InvokeDynamic
                  #0:apply:()Ljava/util/function/Function;
10: putfield #3 // Field f:Ljava/util/function/Function;
13: return

То, как будет выполнен второй шаг, зависит от того, является ли лямбда-выражение необработанным(лямбда не обращается ни к каким переменным вне ее тела), или замыкающим(лямбда получает доступ к переменным вне ее тела).
Примечание: замыкание - когда в лямбда выражении используется переменная, объявленная вне этого выражения.
В первом случае, лямбда-выражения просто превращаются в статический метод, имеющий точно такую же сигнатуру лямбда-выражения, и объявляются в том же классе, где используется лямбда-выражение. Например, лямбда-выражение, объявленное в классе Lambda выше, может быть преобразовано в метод, подобный этому:
static Integer lambda$1(String s) {
    return Integer.parseInt(s);
}

Случай замыкания лямбда-выражения немного сложнее, поскольку замыкающие переменные должны быть переданы методу, реализующему тело лямбда-выражения вместе с формальными аргументами лямбда-выражения. В этом случае общая стратегия  заключается в использования аргументов лямбда-выражения с дополнительным аргументом для каждой внешней переменной. Давайте посмотрим на практический пример:
int offset = 100;
Function<String, Integer> f = s -> Integer.parseInt(s) + offset;

Соответствующая реализация метода будет сгенерирована так:
static Integer lambda$1(int offset, String s) {
    return Integer.parseInt(s) + offset;
}

Также есть цитата Брайна Гетца из этого ответа на enSO:

Когда компилятор встречает лямбда-выражение, он сначала понижает тело
лямбды в метод(аналогичный лямбде), возможно, с некоторыми
дополнительными аргументами(если лямбда замыкающая). В момент, когда
лямбда-выражение будет захвачено, оно генерирует место динамического
вызова(CallSite object), которое при вызове возвращает экземпляр функционального
интерфейса, в который преобразовывалось лямбда-выражение. Это место
вызова называется лямбда-фабрикой(lambda-factory) для данной лямбды.
Динамические аргументы лямбда-фабрики - это значения, полученные из
лексического контекста. Метод начальной загрузки(bootstrap method)
фабрики лямбда-выражений - это стандартизированный метод в библиотеке
рантайма языка Java, который называется метафабрикой лямбда-выражения.
Ссылки на методы обрабатываются так же, как и лямбда-выражения, за
исключением того, что большинство ссылок на методы не нужно вводить в
новый метод; мы можем просто загрузить дескриптор для ссылочного
метода и передать его метафабрике.

UPD: Очень рекомендую эту статью с Хабра:
Разбираем лямбда-выражения в Java
В качестве источников я использовал две статьи - доклад Java 8 Lambdas A Peek Under the Hood и статью от IBM про лямбды.


text: Q: Office web addin does not show up in the "Admin Managed" Office add-ins tab for some users in the organization My word office addin has been deployed via the Office 365 Admin admin centre. Some users in my organization cannot add the addin. They cannot see the same when they try to manually add the addin via the Word Online menu options. When I deployed the addin via Centralized Deployment I had selected access for Everyone. Is there any additional user rights or user access that is linked with web addins.


text:
Q: Why I am not able to upload media files? I am running a wordpress blog (4.5.3) with no plugins activated, but I am unable to upload any media files. After I click upload, after a while I see Http Error on the screen. In the Firefox net tab, I see request aborted; no response is ever received.
In the apache log, I see
[Wed Aug 22 00:26:29.700169 2016] [:error] [pid 20934] [client someip:port] PHP Warning:
An unexpected error occurred. Something may be wrong with WordPress.org or this server's configuration.
If you continue to have problems, please try the support forums.
(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)
in /var/www/html/blog/wp-admin/includes/translation-install.php on line 59,
referer: http://www.somesite.com/blog/wp-admin/media-new.php

A: Put this is your themes function.php

add_filter( 'wp_image_editors', 'change_graphic_lib' );

function change_graphic_lib($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}


text:
Q: RX Scheduler - What is it? I'm reading up on RX and totally bamboozled to what the Scheduler is intended for?
Can someone explain?

A: This class is for basically what it implies.  It is a mechanism for scheduling the internal threads that make up the Rx framework.  There is a great video on this here.
The main page for Rx contains more videos that offer insight into the architecture as well as use of the framework.

A: The IScheduler interface in Rx helps an IObservable "schedule" it's subscription appropriately.  This is very important in order to handle thread affinity and similar issues, since the subscription will be causing something to happen at some point.
Here is a good description of the IScheduler interface (along with a comparison to the TPL's TaskScheduler).


text:
Q: C# - Problem while passing an argument to Thread I have a problem with my multi threading app.
I have an array with 4 Threads in it.
Here is how I initialize them:
for (int i = 0; i < threads.Length; i++)
{
    threads[i] = new Thread(delegate () { ThreadMethod(i); });
}

But after my first test(s) I showed that all four threads run with 3 as passed value.
I chagend it to
for (int i = 0; i < threads.Length; i++)
{
    int id = i;
    threads[i] = new Thread(delegate () { ThreadMethod(id); });
}

and it worked but for me it looks like there must be a better way to pass my i to my thread.
Am I right with my guess and if I am, how should I pass i?
Thank you!

A: The closure uses local variables -- in a for loop the variables declared for the loop are not local they have to be inside the block ({}) for that.  That is why the 2nd example works.
The delegate keyword is what creates the closure and it looks for local variables to include in the closure.  When it finds id it includes it.  When it doesn't it references the global (outside the closure) value of i and at the time of running i has a value of 3.


text:
Q: Can a query that executes quickly still be a poorly written query? This is more of a theoretical question and here is some background. Our system uses MySQL and was experiencing some slowdowns late in the day. Running SHOW FULL PROCESSLIST showed me around 10 rows where the state was "Sending data" and the time value was ranging from 400 to 800. For all of those rows, it was the same exact query. As time passed, some would finish and some would run again because it's a query that runs on a user's dashboard. If I run the query in MySQL Workbench, the query executes pretty quickly, around 0.27 seconds on average.
So I'm wondering how to troubleshoot something like this and figure out where the issue came from. Could a query execute quickly, but still be inefficient in some other area? Or could there have been some other issue aside from the query itself? Nothing was showing up in the slow-query log. What would cause a query, which seems to run quickly, have those kinds of stats in the process list? I thought it was unusual for everything to be working fine throughout the peak times, and then have issues at the end of the day when less users were active. But I'm sure there's a good explanation somewhere. IT also reported that the server experienced high CPU usage around that time.
About the query itself, I'm sure I can optimize it further. I think the biggest thing about it is that it uses a case statement on a join, which I haven't had to do before. The idea is basically a conditional join because we need to join a table based on certain values. Since MySQL doesn't seem to support recursion, this was the path we took. But again, the query itself at least executes quickly in Workbench.
If anyone has any insight to this, I'd appreciate any help.

A: Simply put: yes. Something being fast does not mean it is necessary good as there are other factors, some objective and some very subjective, to consider.
Some examples:

*

*The query could be unnecessarily complex: doing more work than needed to get the same result as a more optimal version. Maybe what it is doing in ~0.27s could actually be done in ~0.07s a different way around?

*The query could be difficult to maintain, either because of excess complexity as above or due to bad coding conventions and naming conventions.

*The query could be fast now, with current data, but have awful complexity growth as your data grows.

*The query could be fast in itself, but for some reason cause too many locks to be held which will make it slow when run multiple times concurrently or make other queries less unresponsive while it runs.

*The query could be written in a way that causes spills of temporary data to disk, which due to IO contention can have similar effects by way of imposing concurrency limits as holding locks.

*"Quickly" itself is a very subjective term. Is 0.27s really quick? If the query is run tens of times a minute it could be using hours of CPU resource or IO bandwidth each day that could otherwise be used by other processes (on fixed hardware) or is imposing a cost (on virtual/cloud hardware where you are paying everything that is used).


text:
Q: CSS media queries do not work for child elements I cannot address child elements via CSS mediaqueries. How can I style the list elements in the example below for a screen width that is bigger than 800px?
js fiddle
HTML

CSS
   .navigation > li{ display: block; width: 10em; };

@media screen and (min-width: 800px) {

.navigation > li{ width: 20em; };
}

A: hope it will help you, add media queries after the regular css code,
  @media only screen and (mix-width: 800px) {
           //add your css it may help you

 }

A: You should get rid of semicolons after braces. Chrome doesn't like them:
.navigation > li{
    display: block;
    width: 10em;
    background: red;
    margin: 10px;
}

@media screen and (min-width: 300px) {

    .navigation > li{
        width: 20em;
    }

}

Fiddle: http://jsfiddle.net/wQu9j/2/


text:
Q: iPad app crash making executeFetchRequest:error: and device is in low power consumption I'm having this problem, I'm making a request with ASIHttpRequest that takes a few minutes, when request is finished the iPad is in low power consumption, the screen is black, etc. The downloaded data is saved in coredata and in this process the app crash.
This is part of the crash information:
MyApp[2978] has active assertions beyond permitted time:
{(
    <BKProcessAssertion: 0x1f841ec0> identifier: Suspending process: MyApp[2978] permittedBackgroundDuration: 10.000000 reason: suspend owner pid:26 preventSuspend  preventThrottleDownCPU  preventThrottleDownUI
)}

Elapsed total CPU time (seconds): 10.220 (user 10.220, system 0.000), 51% CPU
Elapsed application CPU time (seconds): 9.860, 49% CPU

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x3c6ae39c pread + 20
1   libsqlite3.dylib                0x3c3b75c8 0x3c3b2000 + 21960
2   libsqlite3.dylib                0x3c3ca0fe 0x3c3b2000 + 98558
3   libsqlite3.dylib                0x3c3c929a 0x3c3b2000 + 94874
4   libsqlite3.dylib                0x3c3e208e 0x3c3b2000 + 196750
5   libsqlite3.dylib                0x3c3e32be 0x3c3b2000 + 201406
6   libsqlite3.dylib                0x3c3df488 0x3c3b2000 + 185480
7   libsqlite3.dylib                0x3c3d8482 sqlite3_step + 2138
8   CoreData                        0x340e596a _execute + 122
9   CoreData                        0x340e5864 -[NSSQLiteConnection execute] + 2168
10  CoreData                        0x341a5486 newFetchedRowsForFetchPlan_MT + 1006
11  CoreData                        0x340ec73a -[NSSQLCore objectsForFetchRequest:inContext:] + 678
12  CoreData                        0x340ec200 -[NSSQLCore executeRequest:withContext:error:] + 464
13  CoreData                        0x340eb618 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1640
14  CoreData                        0x340e9f12 -[NSManagedObjectContext executeFetchRequest:error:] + 642
15  Georeporting                    0x000b7506 +[Model loadObject:withId:createNew:] (ModelObject.m:51)
16  Georeporting                    0x000b18ae -[Data request:didFinished:] (DataManager.m:309)
17  Georeporting                    0x000a69fe -[Server requestFinished:] (ServerClient.m:80)
18  Georeporting                    0x000e6c04 -[ASIHTTPRequest reportFinished] + 76

This is the code of the executeFetchRequest
NSEntityDescription * entity = [NSEntityDescription entityForName:[objectClass entityName] inManagedObjectContext:[Model manageObjectContext]];
    NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    NSString * query = [NSString stringWithFormat:@"%@='%@'", [objectClass primaryKeyFieldName], objectKey];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:query];
    [fetchRequest setPredicate:predicate];

        NSArray * objects = [[ModelObject manageObjectContext] executeFetchRequest:fetchRequest error:nil];

A: You can disable the idle timer on iOS extremely easily - see this question:
How to disable/enable the sleep mode programmatically in iOS?
Although that should fix your problem, do make sure that you're not doing your network operations on the main thread. I can't tell from the stack trace you've posted, but I suspect you might be. As someone else has already suggested, you should migrate away from ASIHTTPRequest to a more modern alternative if possible.


text:
Q: difficulty with adding values from html textbox in javascript Sorry if this is a stupid question. I am a newbie to programming...
I have 3 values from a text input.  I want 2 of these values to be stored into separate arrays for later access. finally I want to display a sum of these 3 values in my document.
What am I doing wrong?
Here is my code:
<script>

function displayCurrentBalance() {
  var initialBalance =  parseFloat(document.getElementById("initialBalance").value);

  var inAmounts=[0];
  var outAmounts = [0];
  inAmounts.push(document.getElementById("amountIn").value);
  outAmounts.push(document.getElementById("amountOut").value);

  var sumIn = (inAmounts.reduce(function(a, b) {
    return a + b[1];
  }, 0));
  var sumOut = (outAmounts.reduce(function(c, d) {
    return c + d[1];
  }, 0));

  var result = initialBalance + sumIn - sumOut;
  document.write(result);
};

displayCurrentBalance();

</script>

A: *

*document.write(result); will overwrite your document before you even have a chance to enter the values. Make it display a value in another input box, or alert(result).

*You should probably attach displayCurrentBalance to an onclick handler of some button, like <button onclick="displayCurrentBalance()">Calculate</button>.

*document.getElementById("amountIn").value and similar calls will give you a string. You should use parseFloat or parseInt to convert it to an integer or a float.

A: You are likely calling the function before the elements are available in the page. Otherwise the script should be below the elements in the page.
You main problem is how you are using reduce. The values returned from the inputs are strings, so convert them to numbers before trying to add them (otherwise you will be concatenating strings, not adding numbers). You should probably validate the values too.
Also, reduce is called with the values of the members of the array, not the array itself (which is the 4th parameter provided to the callback, not the second), so:
var sumIn = (inAmounts.reduce(function(a, b) {
  return +a + +b;
}, 0));

Modify the other call to reduce similarly. I don't think you need to provide an initial value since you initialise the array as [0]. Alternatively, keep the initial value in the call and initialise the array as [] (i.e. an empty array).
Rather than using document.write to display the result, better to write it as the value of a read–only input element so you can update it with subsequent calls as the user modifies the values in the other inputs.


text:
Q: javascript: is it possible to target div of another file? Let me explain the purpose of this. I'm using some CMS and I'm trying to customize it with php scripts of my own that I embedded to the home page with IFRAME. My php script gives back some links which I would like to open outside that IFRAME - as a part of some other CMS block on the homepage. The idea is to target (from my php script) the div of that CMS block which is already showing some data. Is that possible?

A: var iframe = document.getElementById('idOfIframe');
var frame = iframe.contentDocument || iframe.contentWindow.document;
var yourDiv= frame.getElementById('div_you_want');

A: If you need to access
 or any other element of parent window from its child iframe
USE:
var elem=window.parent.document.getElementById('target');

inside

This is iframe

html;
?>

OR
if you need to access element in iframe from parent window
USE:
var iframe = document.getElementById('idOfIframe');
var frame = iframe.contentDocument || iframe.contentWindow.document;
var yourDiv= frame.getElementById('div_you_want');

inside

Blah!

file: xyz.php (same as src of iframe)
<?php
echo<<<html

 This div from iframe

html;
?>

parent window is the one in which original html(index.html) document along with your iframe(xyz.php) resides.
Hope it helps :-)!

A: From the page running inside the  you can refer to the parent page as window.parent, and perform actions as you normally would.
parent.document.getElementById('target_div').innerHTML = 'New content.';

Note JavaScript's cross-domain restrictions apply. You can only do that if both pages belong to the same domain.
In case of links, you can include to your  tags the attribute target="_parent", or set it as base target to apply to all links.

    ...
    <base target="_parent">

You can also target a link to another iframe, all you have to do is set a name="iframe_name" to it and set target="iframe_name" to all links that should open in that area.


text:
Q: 'Converting date and/or time from character string' Question I have created a temp table where I need to filter Effective_Date >= 2018-05-01. I have tried different variations of playing around with both the character type (DATETIME2) as well as the WHERE criteria but get the below error message:

Msg 241, Level 16, State 1, Line 164
  Conversion failed when converting date and/or time from character string.

DROP TABLE #EarnedPremium
GO
CREATE TABLE #EarnedPremium
       ([Policy_Number] VARCHAR(250)
      ,[Effective_Date] DATETIME2
      ,[Earned_Premium] MONEY
       )
GO
INSERT INTO #EarnedPremium
SELECT
      Policy_Number
      ,Effective_Date
      ,Earned_Premium
FROM dbo.AGG_EarnedPremium
WHERE Effective_Date >= '%2018-05-01 00:00:00.0000000%'

SELECT * FROM #EarnedPremium

Any suggestions would be very much appreciated!

A: % is used for LIKE which is an operator for comparing strings for pattern matching.
You want to compare dates based on ordering.  Comparing strings for matching patterns and comparing dates based on time really have nothing to do with each other.
Just use date comparisons:
WHERE Effective_Date >= '2018-05-01'


text:
Q: Angular Delete request is not working. But Postman works HttpService
 delete<T>(url: string): Observable<T> {
    return this.httpClient.delete<T>(`${url}`);
  }

SettingsService
deleteTeamMember(companyId: number, userId: number): Observable<void> {
    return this.httpService.delete<void>(
      `${environment.urls.api}/company/${companyId}/team/${userId}`
    );
  }

component.ts
 this.settingsService
          .deleteTeamMember(this.company.companyId, teamMember.userId)
          .subscribe(); //api call

The above API call is not working. It says 400 bad request. It has access tokens and etc too.
API response
{
    "code": "BadRequest",
    "title": "Bad Request",
    "message": "Expected one of: <<{,[>> but got: <<EOF>>",
    "type": "tag:oracle.com,2020:error/BadRequest",
    "instance": "tag:oracle.com,2020:ecid/XgKKiZB497hJdOcC1jQxOQ"
}

But the same API and access token are working fine with the Postman.
Do you know why?
AuthInterceptor
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private isRefreshing = false;

  private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
    null
  );

  constructor(
    private authService: AuthService,
    private userDataService: UserDataService
  ) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let authRequest = request;
    const accessToken = this.userDataService.getAccessToken();

    if (accessToken != null) {
      authRequest = this.addTokenHeader(request, accessToken);
    }

    return next.handle(authRequest).pipe(
      catchError((error) => {
        if (
          error instanceof HttpErrorResponse &&
          !authRequest.url.includes('auth/sign-in') &&
          error.status === 401
        ) {
          return this.handle401Error(authRequest, next);
        }

        return throwError(error);
      })
    );
  }

  private handle401Error(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      const refreshToken = this.userDataService.getRefreshToken();

      if (refreshToken) {
        return this.authService.refreshToken(refreshToken).pipe(
          switchMap((token: TokenModel) => {
            this.isRefreshing = false;

            this.userDataService.setAccessToken(token?.accessToken);
            this.userDataService.setRefreshToken(token?.refreshToken);

            this.refreshTokenSubject.next(token.accessToken); //get the 'accessToken' from refreshToken() call

            return next.handle(this.addTokenHeader(request, token.accessToken));
          }),
          catchError((err) => {
            this.isRefreshing = false;

            this.userDataService.setIsSignedOut(true); //Sign Out the app

            return throwError(err);
          })
        );
      }
    }

    return this.refreshTokenSubject.pipe(
      filter((accessToken) => accessToken !== null),
      take(1),
      switchMap((accessToken) =>
        next.handle(this.addTokenHeader(request, accessToken))
      )
    );
  }

  private addTokenHeader(
    request: HttpRequest<any>,
    accessToken: string
  ): HttpRequest<any> {
    return request.clone({
      setHeaders: {
        'Content-Type': 'application/json',
        'Access-Token': accessToken,
      },
    });
  }
}

A: Most likely just remove the 'Content-Type': 'application/json' from your interceptor. Angular sets this header automatically when necessary. Delete requests don't need it.
private addTokenHeader(
    request: HttpRequest<any>,
    accessToken: string
  ): HttpRequest<any> {
    return request.clone({
      setHeaders: {
        'Content-Type': 'application/json', // REMOVE
        'Access-Token': accessToken,
      },
    });


text:
Q: ImageIO no suitable reader in Java web start I have a java web start application that shows some png images that are loaded with:
InputStream is = AClass.class.getClassLoader().getResourceAsStream("icon/tray.png");
ImageIO.read(is);

While this works perfectly from Eclipse it doesn't work when I run the application with Java web start. Obviously the difference in both setups is that in Java web start the image will be loaded from a jar file while in Eclipse the images comes directly from the file system.
What happens in Java web start is, that the InputStream gets created as expected (meaning the resource can be loaded) but, as far as I can see it, within the ImageIO.read() method no suitable reader can be found for the image in the stream and ImageIO.read() returns null. How can it be that a reader can be found when starting from Eclipse but not if started with Java web start?
Furthermore I got some more png's that are loaded with mechanisms from JavaFX more precisely via css e.g.
-fx-image: url('icon/settings_general_32x32.png');

I see the same behavior here too. It works from Eclipse but not with Java web start although I'm not sure if this is because of the same reason or even for another reason but I would guess that it is because of the missing reader too.
So I looked in the code of PNGImageReaderSpi and there one can see in the method canDecodeInput() that the first 8 byte of the stream will be analyzed to decide if the PNG reader can decode the image or not. So I had a look at the first 8 bytes of the image stream when starting from Eclipse and when starting from Java web start and indeed there is a difference. When running from Eclipse the first bytes are -119,80,78,71,13,10,26,10 and in Java web  start the first bytes are -17,-65,-67,80,78,71,13,10. For me this looks at least a little strange, but I'm not sure if that is the cause of the problem.
Has anybody come across this problem? Did I miss anything? Any help or ideas are highly appreciated.

A: As writen in the comment the images where currupted by the applications build script. This was the reason why it was not working with Java web start but was working from Eclipse where the build script was not used.


text:
Q: Venn Diagram Probability Question For two events $A$ and $B$ we have $\text{Pr}(A′) = 0.71$, $\text{Pr}(B) = 0.43$, and
$\text{Pr}(A\cup B) = 0.65$.
Find $\text{Pr}(A\cap B)$.
I know the answer is $0.07$. I just can't seem to figure out how.
For $A$ I found the probability was $0.22$ (Just the left portion of the circle not overlapping B.)
That is as far as I am able to get. Working on a practice exam for tomorrow's test. Thanks in advance!

A: Your Venn Diagram should have two overlapping circles (A, B) with the three sections labelled $A\setminus B, A\cap B, B\setminus A$.
From the information given you know that $\Pr(A\setminus B)=\Pr(A\cup B)-\Pr(B)=0.65-0.43=0.22\quad$ (Note: this is not $\Pr(A)$)
Similarly you should find $\Pr(A)=1-\Pr(A')=1-0.71=0.29$ and thus $\Pr(B\setminus A)=\Pr(A\cup B)-\Pr(A) =\underline{\qquad}$.
The middle area is $\Pr(A\cap B)=\Pr(A\cup B)-\Pr(A\setminus B)-\Pr(B\setminus A) =\underline{\qquad}$

Alternatively, you could use: $\Pr(A\cap B)=\Pr(A)+\Pr(B)-\Pr(A\cup B) =\underline{\qquad}$

A: Since the question contains the keyword venn, let me do it the venn's way :
Consider this image :

It describes your problem :
$Pr(A')$ = White + Yellow + Green = $0.71$
$Pr(B)$ = Green + Yellow = $0.43$
$Pr(A\cup B)$ = Red + Yellow + Green = $0.65$
And you want to find $Pr(A\cap B)$ (Yellow):
You can find whatever you want only by playing with those colors, keeping in mind the sum of all of them equals $1$
$Pr(A)$ = Red + Yellow
$Pr(B)$ = Green + Yellow
$Pr(A\cup B$ = Red + Yellow + Green
         = (Red + Yellow) + (Green + Yellow) - Yellow

         = $Pr(A)$ + $P(B)$ - $P(A\cap B)$ ... $(1)$

I'll live it to you to complete ...


text:
Q: comunication between server, JavaFX desktop app and android app this is a theoric question.
I want to deploy an app, actually 3, that:
-Manage a database (SQLite) from the desktop, in JavaFX, Done!!
-Server/WebApp that sends data(JSON) to several android devices.(¿Grails??)
-Android App to recieve and manage the JSON (and more things).
My doubts are:
-In my desktop app when the user chilck the "Send info to device"
    the app must do a call to the service app like http://myserver/receiveJSONtoSend and the server listen the  request and send the data to the device? and in the device recieve and do things with the JSON, and when the task are finished send other request to the server and the server comunicate to the desktop app. This is right?
-How the server comunicate with the desktop app? by suscribing like a listener?
Sorry abot my english and my non especific question, if some extra information is needed tell to me please!
Thanks a lot!!!

A: Since Java is painfully object oriented its often a good idea to use a JavaRMI engine for Java to Java communication.
@mod: I see this as a comment, but can't put it there on my own. Thanks!


text:
Q: Questions about monotone sequences and subsequences I have the following questions about sequence:

*

*Does every monotone sequence have a bounded subsequence?

*Does every bounded sequence have a monotone subsequence?

*Does every sequence have a subsequence for which the limit makes sense?

*If lim sup $a_n$ is finite, then the sequence $a_n$ is bounded above?
I think the answers should be False, True, True, and True, but I cannot come up with a valid reasoning or counter examples. Can anybody help?

A: *

*False.  Consider the sequence $1,2,3,\dots$

*True.  In fact, every sequence of real numbers has a monotone subsequence.  This is the monotone subsequence theorem.

*True.  This follows from question $2$.

*True.  If a sequence is not bounded above, then it has a subsequence that diverges to $\infty$, so the lim sup is infinite.


text:
Q: Using logistic regression scores for inference I'm training the logistic regression for binary classification on a labeled data set. Now I'm using the same entries and predict their scores using the model.
For example, I have an entry with label 0 and predicted score is 0.1 and another entry with known label 0 and predicted score 0.2.
So basically I'm using model to get probability for seen (as opposite to unseen) data.
And I'm trying to argue whether the predicted probability shows the ordering/ranking of the entries - second entry from the example is closer to class 1 than first entry?
Or do they just show the performance of my model?
This contradicts to common approach when trained model is used on unseen data, and I feel that comparing the scores of training data has no sense, but I can't understand why

A: Logistic regression models, though used for categorical Y, are not classification methods.  They are instead used to estimate tendencies, i.e., probabilities.  Briefly, a classifier is appropriate when the probabilities of class membership hover around 0.0 and 1.0, i.e., when the signal:noise ratio is exceedingly high.  Otherwise it is not often useful to force probabilities to be converted to labels.  At any rate that would require a utility/loss/cost function because it is a decision, not a prediction.  Details may be found here.


text:
Q: Is there any way to compile our PHP code into executable file i'm wondering about this possibility. Is it possible to make our code written in code and string compile and make it become Executable and can operate without the use of server such as Apache.
The OS environment will be Windows family.

A: I've never tried it, but you could take a look at PHC.  It appears to be able to do just that.
Also take a look at Hip-Hop by Facebook.  Looks good (and more recent).
Edit: And for more PHP Compilers, see Wikipedia

A: There are some application which compress your application, a web browser and PHP into an executable file. This way it works like an application.
If you want write an application in windows using PHP you can try PHP windows bindings http://winbinder.org/ . It looks promising
Also I have found two windows compilers for PHP while googling (I did not use them).

*

*http://www.bambalam.se/bamcompile/

*http://www.phpcompiler.org/

A: The existing answers cover the bases fairly well for possible ways to compile your php code into an executable. That said, you may not have to go to those lengths, based on your question.
If all you are looking for is a way to execute php scripts in Windows away from an Apache server, then all you need to do is install php to your Windows machine. Then you can run any php script from the command-line by simply typing > php script.php
You can download the Windows installation package for this from http://windows.php.net/download/