Are the results of the medical residency match algorithm unique? Variant of the stable marriage problem

Question: Every year, applicants to medical residency programs each submit a strict ordering of a subset of available programs called a "rank order list" or "rank list" to the National Resident Matching Program (NRMP) that reflects each of their preferences. Residency programs similarly each submit rank lists of applicants to the NRMP. The NRMP then runs an algorithm that attempts to match applicants to their most preferred programs. Programs vary in the number of positions they need to fill.
While the algorithm apparently produces a matching that is stable (i.e., after the match, there does not exist a pair of applicants $x_1$ and $x_2$ who would prefer to switch the programs they got matched to), there is no public information that I can find as to whether the results of this algorithm are unique. As a current applicant, I would like to know if an algorithm exists that would ensure that the results are unique, or if not, to what extent the results may not be unique (i.e. how farther down could an applicant match in their rank list if the algorithm is re-run in a different order or with different parameters?).
I read the paper by Clark (http://pareto.uab.es/jmasso/pdf/ClarkCTE2006.pdf) which gives a sufficient condition for the uniqueness of stable matchings in the classic stable marriage problem, but I could not find anything regarding the NRMP Match variant of the stable marriage problem.
Answer: The criterion you give for the stability of a matching is incomplete. The matching is stable if there doesn't exist a blocking pair of assignments of a student $\ x_1\ $ to residency program $\ p_1\ $ and student $\ x_2\ $ to residency program $\ p_2\ $.  For the assignments to constitute a blocking pair it isn't sufficient merely for the two students to prefer the program that the other has been assigned to.  It's necessary also for the two residency programs to prefer the other student to the one who has been assigned to it.
The matching problem in the simple form you've described it is known variously as the "college admissions problem", the "hospital/residents problem", or the "rural hospital problem".  Although it isn't quite as simple as the stable marriage problem (which is a special case of it), the Gale-Shapley algorithm will nevertheless still always produce a unique stable matching for it. This doesn't mean that there exists only one stable matching, but I understand that the one produced by the Gale-Shapley algorithm has some particularly nice properties.
The problem which the NRMP tries to solve is somewhat more complicated than a simple vanilla college admissions problem, however, and it now uses the Roth-Peranson algorithm, a modified version of Gale-Shapley developed by Alvin Roth and Elliott Peranson, and described by them in  this paper.  A Google search on "Roth-Peranson algorithm" will return links to a lot of literature on it.
Comment: Thank you. The primer by Maaz 2020 in the Google search actually states the following:

"Interestingly, what is best for the students and what is best for the hospitals seem to be at odds with one another. When there are two or more different possible stable matchings, the student-proposing algorithm yields the student-optimal, but the hospital-proposing algorithm yields the hospital-optimal match."
Comment: An interesting side-note: the student-optimal match is actually the hospital-pessimal match, and vice versa!


How to create 2 divs with equal height without bootstrap or jquery

Question: I am trying to write a code is CSS and normal javascript but it won't work. Here is my code (HTML and CSS).

.wrapper{
        height: 100%;
        margin: 1.5rem 0 0 0;
        display: flex;
    }
    .first{
        vertical-align: top;
        display: inline-block;
        margin-right: 2rem;
        flex: 1;
    }

    .second{
        vertical-align:top;
        display: inline-block;
        flex: 1;
    }

TIMES

TIMES

GESLOTEN

Dinsdag - Zaterdag

09:30 UUR - 18:00 UUR

WELKOM

TEKST

I have tried everything, at least I think I have.
The problem is that I can't fix this in CSS but I tried Java.
Still no success. Can someone please explain why I can't get it the same height.
It's a school project and I need to make a website from scratch.
Here is my full website source code: https://codepen.io/crosso_7/pen/VERrvQ
Comment: @TrueTiem OMG it worked thank you. Pls reply with an answer so i can aprove yours.
Comment: Actually, those are have same height. if you give background to them you can see. https://codepen.io/truetiem/pen/wYOrLR
Comment: @TrueTiem I have tried it and it looks horrible. https://imgur.com/a/zXFJvqV Background is #000 (black)
Comment: Have you tried flexbox?
Comment: @SandipNirmal I am pretty new to this so I have no clue what you mean with flexbox
Comment: @CrossProduction Added code in the answer. Please check.
Comment: @CrossProduction do you want it to looks like this: https://i.imgur.com/tZiMHIm.png
Comment: @TrueTiem Yes but that black part needs to be white. How did you do that ? With padding?
Comment: @SandipNirmal Still no effect
Comment: @CrossProduction Just add a white background, not black :d Those are already have same height. Just their background is transparent, you can't see.
Comment: @CrossProduction Can you add fiddle or codeSandbox link. Will try to fix it there
Comment: @SandipNirmal I appriciate it bro but TrueTiem already helped me
Answer: Both first and second divs are actually the same height - I just copied your snippet and applied a border around each div to see the issue and both divs are equal.

.wrapper{
        height: 100%;
        margin: 1.5rem 0 0 0;
        display: flex;
    }
    .first{
        vertical-align: top;
        display: inline-block;
        margin-right: 2rem;
        flex: 1;
        border: solid 1px blue;
    }

    .second{
        vertical-align:top;
        display: inline-block;
        flex: 1;
        border: solid 1px red;
    }

TIMES

TIMES

GESLOTEN

Dinsdag - Zaterdag

09:30 UUR - 18:00 UUR

WELKOM

TEKST

Answer: You can do it using flexbox. Something like this code snippet.

.wrapper {
 display: flex;
 justify-content: space-between;
}

.wrapper div {
 background: #000;
 color: #fff;
 flex: 1;
 margin: 10px;
 justify-content: center;
}

1

asasasa

2

Answer: Is the first div the one thats higher? It's probably created by the padding from first div content vs seconds less content.
May have to set first and second div with a px or % height which are the same to make it equal.
Comment: I have the height set to 100% still nothing. I also have tried auto but it has no effect.
Answer: Try using the code below in your .first and .second divs
flex: 1;
display: flex;


Prove that $A \mathop \triangle C \subseteq (A \mathop \triangle B)\cup (B \mathop \triangle C)$

Question: Suppose A, B, and C are sets, prove that $A \mathop \triangle C \subseteq (A \mathop \triangle B)\cup (B \mathop \triangle C)$
I'm just wondering if this proof is ok, or if I'm overlooking something, thanks!
Proof. Suppose $x \in A \mathop \triangle C$. If $x \in A \mathop \triangle B$, then clearly $x \in (A \mathop \triangle B) \cup (B \mathop \triangle C)$, so we will consider the case when $x \notin A \mathop \triangle B$. Suppose $x \notin A \mathop \triangle B$. This means that $x \in A \leftrightarrow x \in B$. Since $x \in A \mathop \triangle C$, either $x \in A \mathop \backslash C$ or $x \in C \mathop \backslash A$. We will consider both cases.
Case 1: $x \in A \mathop \backslash C$. So $x \in A$ and $x \notin C$. Since $x \in A$ and $x \in A \leftrightarrow x \in B$, it follows that $x \in B$. Then since $x \notin C$, $x \in B \mathop \backslash C$, so $x \in B \mathop \triangle C$. Hence, $x \in (A \mathop \triangle B)\cup (B \mathop \triangle C)$
Case 2: $x \in C \mathop \backslash A$. So $x \in C$ and $x \notin A$. Then since $x \notin A$ and $x \in A \leftrightarrow x \in B$, it follows that $x \notin B$. Thus, $x \in C \mathop \backslash B$, so $x \in B \mathop \triangle C$, and hence, $x \in (A \mathop \triangle B)\cup (B \mathop \triangle C)$.
Edit: Also, I would be interested to see any alternative methods of proving this.
Comment: Looks good to me!
Comment: Alternative, we could use characteristic function: http://en.wikipedia.org/wiki/Indicator_function
Answer: Here is an alternative:
$$A\triangle C=A\triangle\varnothing\triangle C=A\triangle(B\triangle B)\triangle C=(A\triangle B)\triangle(B\triangle C)\subseteq(A\triangle B)\cup(B\triangle C)$$
Comment: This is a nice argument, assuming that you know that symmetric difference is *associative.*
Comment: Of course. ${}{}{}{}$
Answer: How about some Venn diagrams?  (Please don't comment on the lack of rigor.)
Answer: Let $x \in A \mathop \triangle C$.
Case $1$: $x \in A \backslash C$. Then $x \in A$ and $x \notin C$. If $x \in B$ then $x \in B\backslash C$ and if $x\notin B$ then $x \in A\backslash B$. In either case we have $x \in(A \mathop \triangle B)\cup (B \mathop \triangle C)$.
Case $2$: $x\in C\backslash A$. Then $x \in C$ and $x \notin A$. If $x \in B$ then $x \in B \backslash A$ and if $x \notin B$ then $x \in C \backslash B$. In either case we have $x \in (A \mathop \triangle B)\cup (B \mathop \triangle C)$.
Answer: Here is another alternative proof, in my favorite proof format: the calculational Feijen(-Dijkstra-Scholten-Gries-etc.) format.  I will use the following definition of $\Delta$: $$x \in P \Delta Q \equiv x \in P \not\equiv x \in Q$$
Starting with the most complex side, and working on the element level, we try to transform $x \in (A \Delta B) \cup (B \Delta C)$ and work towards $A \Delta C$ using logic:
$$
\begin{align}
& x \in (A \Delta B) \cup (B \Delta C) \\
\equiv & \;\;\;\;\;\text{"definition of $\cup$; above definition of $\Delta$, twice"} \\
& (x \in A \not\equiv x \in B) \lor (x \in B \not\equiv x \in C) \\
\equiv & \;\;\;\;\;\text{"logic: use negation of right side of $\lor$ in left side -- to bring $A$ and $C$ together"} \\
& (x \in A \not\equiv x \in C) \lor (x \in B \not\equiv x \in C) \\
\Leftarrow & \;\;\;\;\;\text{"logic: weakening"} \\
& x \in A \not\equiv x \in C \\
\equiv & \;\;\;\;\;\text{"above definition of $\Delta$"} \\
& x \in A \Delta C \\
\end{align}
$$
By the definition of $\subseteq$ this completes the proof.


Is a p-value correction necessary for assessing pairwise location shifts on centered data?

Question: I am currently assessing whether or not a location-shift can be assumed in non-parametric comparisons to be able to formulate the rejection of the null hypothesis in other terms than the probabilistic index. To do so, I center my data and execute a pairwise two-sample Kolmogorov-Smirnov test on each pair. The data is in some cases unbalanced and not-normally distributed.
Currently I am using this function (in R):
pairwise.ks.test<-function (x, g, p.adjust.method = p.adjust.methods, alternative="two.sided",centered=T,...)
{
    p.adjust.method <- match.arg(p.adjust.method)
    DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(g)))
    g <- factor(g)
    METHOD <- if (centered)
    "Pairwise KS test on centered data"
    else "Paiwise KS test "
    compare.levels <- function(i, j) {
        xi <- x[as.integer(g) == i]
        xj <- x[as.integer(g) == j]
        ks.test(xi, xj, alternative=alternative, ...)$p.value
        }
        compare.levels.centered<-function(i,j)
        {
        xi <- x[as.integer(g) == i]-mean(x[as.integer(g) == i],na.rm=T)
        xj <- x[as.integer(g) == j]-mean(x[as.integer(g) == j],na.rm=T)
        ks.test(xi, xj, alternative=alternative, ...)$p.value
    }

if(centered)
     PVAL <- pairwise.table(compare.levels.centered, levels(g), p.adjust.method)
else PVAL <- pairwise.table(compare.levels, levels(g), p.adjust.method)
ans <- list(method = METHOD, data.name = DNAME, p.value = PVAL,
    p.adjust.method = p.adjust.method)
class(ans) <- "pairwise.htest"
ans
}

And at the moment I apply it on my list of datasets without p-value correction:
lapply(datalist,function(x)pairwise.ks.test(x$value,x$trt,p.adjust.method="none",alternative="two.sided",centered=T,exact=F))

My set has ties and therefore an exact p-value cannot be calculated (hence exact=F). As I only want to assess a possible location shift for each pairwise comparison to be able to formulate rejection of $H_0$ in terms of medians or means in Holm-corrected pairwise Wilcoxon-rank sum tests, should I also apply a (Holm?) p-value correction to assess multiple location shifts?
Comment: I'm not sure I understand - doesn't centering remove the very effect you're testing for?
Comment: @Glen_b I center the data to see if there is a location shift: after centering I can use a two-sample KS test to see if data CDFs differ significantly. If they don't that means that there was a location shift (e.g by subtracting a location parameter the CDF's are equal).
Comment: "*If they don't that means that there was a location shift*" -- no, it doesn't necessarily mean that. Unless there's something I missed, your logic is faulty in several ways at once.
Comment: I'm sorry, @Glen_b but I do not see my faulty logic here. $H_0$ is that there is a location shift. i.e. $H0$: $CDF_1$=$CDF_2$ - $\Delta$. If after substracting a location parameter (either median or mean, doesn't really matter under $H_0$) under $H_0$ the CDFs should be the same. Hence they will not be significantly different. Hence you cannot reject $H_0$ in favor of $H_1$. Hence we withold equality of centered CDFs. Hence the location shift assumption holds. Or am I missing something here?
Comment: Here's a few problems to get you started: (1) failure to reject doesn't mean $H_0$ (and the other assumptions) are true. That is, if you assume a location shift, subtract an estimate of one, and fail to reject a goodness of fit test, it doesn't lead to the conclusion that it *was* a location shift, it may be only that you lacked power to pick up any other difference. (2) The KS is based on a completely specified distribution. It doesn't have the desired properties when you do what you did. Your nominal p-values don't take account of what you did to the data; they're less likely to reject.
Comment: What do you mean by 'sometimes unbalanced'?
Comment: @Glen_b, thanks that is very helpful. (1) Do you think it  is better to formulate $H_0$ as no location shift? For example $H_0: CDF_1 = CDF_2$, and then run a GOF test? (2) I think I lack the background for this but given that I do not know the underlying distribution of my data beforehand, isn't the empirical CDF the closest match? How can I incorporate my transformations into my p-values? (3) With sometimes unbalanced I mean that in some of the pairwise comparisons unbalancedness may occur while in others not or less.
Comment: (a) If the hypothesis is of a location shift the usual approach is to make no location shift the null (and with reason); (b) If you want power against the location-shift alternative, a goodness of fit test is a poor choice, power-wise; (c) the empirical CDF may be your best estimate of the original CDF\*, but that doesn't mean it's the best way to find a location-shift; \*(perhaps - I bet you know a few things that would narrow the possibilities down)... (d) simulation allows you to examine at both power and the null distribution of whatever you do, under various circumstance; ...(ctd)
Comment: (ctd)... (e) in your (3) what do you mean when you say 'in some of the pairwise comparisons unbalancedness may occur while in others not or less'. You explained what you mean by 'unbalanced' by using the word in your definition. Please explain as if you were explaining it to an intelligent six year old, avoiding undefined terms (like 'unbalanced') as much as possible.
Comment: Oh, and what's a 'probabilistic index'?
Comment: @Glen_b sorry for my tardy reply. (a) very well, let's assume $H_0: CDF_1 = CDF_2$ in further discussion (b) I understand, but I did not know of a more powerfull alternative (c) I don't know where you are getting at here: I have no prior idea about my underlying distribution, that is why I am opting for a non-parametric method. (d) in simulation, you still have to estimate parameters to be able to simulate, right? In some comparisons I do not have a lot of observations (cfr 'unbalancedness'), and hence estimating parameters will be challgenging. ... (ctd)
Comment: (ctd)... (e) I mean that I do multiple comparisons, and hence have to assess multiple location shift hypotheses. In one comparison $n_1$ might be 19 and $n_2$ 21 (n being the number of observations) while in another comparison $n_1$ may be 19 and $n_2$ 8. This is what I mean when I refer to the terms 'unbalanced' and the 'severity' of this 'unbalancedness.' Finally, the probabilistic index is a way to formulate the alternative hypothesis of a non-parametric comparison. It is defined as the probability that one random variable is smaller then the other. $P\{X_i < X_j\}$ so you want. ... (ctd)
Comment: (ctd)... e.g. for the Kruskal-Wallis rank sum test we can define $H_0$ as $H_0: F_1(x)=F_2(x)=...=F_K(x)$ for all x where $F_i(x)$ is the population CDF. The alternative hypothesis is then specified as $P\{X_i < X_j\} \neq 1/2$ for at least one combination of i and j ($i \neq j$)
Answer: It looks like a "general" multiple testing problem to me, since you're assessing location shift for each of the pairs of datasets? It may lead to a bigger than alpha family-wise false rejection rate and thus a smaller than alpha familywise chance to incorrectly make an interpretation on the mean/median instead of the probabilistic index, which is of course no problem (PI interpretation is of course okay for location shift models also) but may not be what you want to achieve here.
On the other hand, if you choose to apply a multiple testing correction, there may (will) be a tradeoff with the power and thus correcting for the multiple testing may lead you to falsely make interpretations on the mean/median while you should actually be making them on the probabilistic index... I think the easy and safe thing to do here is not apply a multiple testing correction.
Comment: Thanks, @Matt.Vn this was exactly my reasoning. I don't want to loose too much power whilst still being able to express rejection of the $H_0$ in terms of location parameters as the PI is a challenging thing for people to deal with.


Memória e processamento - Variáveis e verificação

Question: Há grande diferença para memória e processamento na forma de executar a verificação nesses dois exemplos? Se sim, porquê e como ambos se comportam na hora de executar os códigos.
Método 1:
var exam = FindExamByID(id);

if (exam == null)
{
    return NotFound();
}

Método 2:
if (FindExamByID(id) == null)
{
    return NotFound();
}

Answer: Fiz uma comparação com as duas formas só para comprovar. O primeiro:
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldloc.0
IL_0004: call instance string C::FindExamByID(int32)
IL_0009: brtrue.s IL_0012
IL_000b: ldarg.0
IL_000c: call instance int32 C::NotFound()
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret

O segundo:
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldloc.0
IL_0004: call instance string C::FindExamByID(int32)
IL_0009: brtrue.s IL_0012
IL_000b: ldarg.0
IL_000c: call instance int32 C::NotFound()
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret

Pode ser conferido no SharpLab.
É o mesmo bytecode então não tem como ser diferente em processamento ou consumo de memória, neste caso. Eu não posso garantir que em algum caso ocorra uma otimização fazendo de um jeito e que não seja possível da outra forma. Composto de outras partes o código gerado pode ser um pouco diferente e aí ter diferença. Uma simples reordenação de instruções pode fazer o processamento ter outro compromisso.
O .maxstack 2 igual em ambos mostra que o fato de existir uma variável para suportar o valor não muda nada quando comparado com o slot  no stack frame necessário para o valor sem a variável.
Answer: Não a diferença, a diferença a é apenas na leitura do código. Muitos programadores preferem colocar o retorno de uma função em uma variavel antes de fazer algum processamento com a mesma, alguns ja preferem usar a função diretamente, mas neste caso em específico não irá ter diferença.
Answer: Não faz diferença se você estiver compilando utilizando o modo Release (com o optimize code ativado), o qual deveria ser utilizado para ambiente de produção. Em ambos os casos, o código Intermediate Language gerado pelo compilador é o que está descrito abaixo.
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  call       object MetodosTeste.Program::FindExamById(int32)
  IL_0006:  pop
  IL_0007:  ret
} // end of method Program::Main

O pseudo-código utilizado para gerar o IL acima foi este:
 class Program
    {
        static void Main(string[] args)
        {
            int id = 0;

            //var exam = FindExamById(id);

            if (FindExamById(id) == null)
                return;
        }

        static object FindExamById(int id)
        {
            return int.MinValue;
        }
    }


How does one troubleshoot errors only showing when using a custom binding?

Question: TLDR;
I get an error when using a custom domain binding in Azure, but not when using the default azurewebsites binding. For example https://somewebsite.com do produce the error, while https://somewebsite.azurewebsites.net does not produce the error.
Background info:
In my application I am using Three.js to generate a background on my landing page. I've enclosed all the animation code within a component I call <Wave /> which I include in my index.vue.
<Wave /> has only a div, in which I am trying to append a renderer – this works flawlessly in both production and development on my local computer, as well as in production on the default azurewebsites domain binding.
But then when accessing the same app service from a custom binding set up through CloudFlare, the component fails and I get the error saying DOMException: Node.appendChild: Cannot add children to a Text (This time using Firefox).
This however only happens on a hard reload while accessing the custom binding, if I visit other links inside the app and move back to the route with the <Wave /> component, then it works perfectly.
General concept:
<template>

</template>

Which produce the error only in a deployed production using the custom domain binding:
DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method.
    at Object.appendChild (/_nuxt/0fdd5ad.js:2:41686)
    ...

I also did try to wrap the <Wave /> component in <ClientOnly>-tags, but this does not change the error in any way.
Any pointers on where to begin would be greatly appreciated.
Comment: Your issue here is a lifecycle one and the fact that you're mainly try to access the ID of the DOM, which is not the recommended way of doing things. Prefer using [`refs`](https://vuejs.org/v2/api/#ref). This has nothing to do with the subdomain. More of the way your app is loading IMO.
Comment: I seem to have pasted my old code (Had this problem for a while now). I am currently using $refs to get the container, however I still get the same issue @kissu.
Answer: You need to keep in mind that your code is executed on Server at first, as shown on this lifecycle: https://nuxtjs.org/docs/concepts/nuxt-lifecycle#nuxt-lifecycle
But I'm pretty sure that appendChild is not a method that works on the server. Since you're probably using ssr: true, I do recommend running this specific code only on the client-side, here is how to achieve this: https://stackoverflow.com/a/67751550/8816585
Comment: @MariusMikelsen having the component in `` is not solving the issue that your code may still have an issue. Even if `mounted()` is only run on the client as shown here: https://nuxtjs.org/docs/concepts/nuxt-lifecycle#client You maybe have an issue, so try to use `process.client` still and see what happens.
Comment: I forgot to mention it, but the component is already wrapped in -tags. This is why I am so baffeled with this issue.
Comment: adding `process.client` directly to a v-if gave me an error, but I tried adding v-if="isReady" and setting it to true in the mounted() hook, as well as false by default. There is however no change in the error, and still only on one of the bindings.
Comment: Also tried a variant like this:

`mounted() { if(this.process.client) { this.isReady = true; } }`

without any change in the error
Comment: What is `this.isReady`? @MariusMikelsen
Comment: isReady is a variable I set to false in data(), like I tried to explain (perhaps a bit poorly). I tried this since I couldn't use process.client directly in the html without producing an error. Therefore I checked for process.client in the mounted() hook and set the variable to true (thus showing the `` component only if the code runs clientside.

The error I experience haven't changed, and is still only reproduced through a custom domain while the azurewebsites one work. @kissu
Comment: @MariusMikelsen please update your question with your updated code.
Answer: The problem originated from another part of the website, but affected the loading of the animation and made it look like it had something to do with it. I still have no clue what caused the error, but luckily don't experience this error any more.


Creating a DropDownListFor in loop

Question: I need to create several drop-down lists on the form, but the selected item is not displayed in each list. Model:
 public class CreditOrganizationCurrencyModel
    {
        public List<CreditOrganizationCurrencyPair> CurrencyPairs { get; set; }
    }

    public class CreditOrganizationCurrencyPair
    {
        public string SelectedCurrencyId1 { get; set; }
        public string SelectedCurrencyId2 { get; set; }
        public CreditOrganizationCurrency CurrencyPair { get; set; }
    }

Data generation:
List<CreditOrganizationCurrency> currencyCouples = CreditOrganizationHelper.Instance.GetOrganizationCurrencyCouples(id).ToList();

            var pairs = new List<CreditOrganizationCurrencyPair>();
            foreach (var currency_pair in currencyCouples)
            {
                pairs.Add(new CreditOrganizationCurrencyPair()
                {
                    CurrencyPair = currency_pair,
                    SelectedCurrencyId1 = currency_pair.Currency1.Id.ToString(),
                    SelectedCurrencyId2 = currency_pair.Currency2.Id.ToString()
                });
            }

List for each DropDownListFor:
List<SelectListItem> currencies = CurrencyHelper.Instance.GetAll()
                    .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString()})
                    .OrderBy(x => x.Text)
                    .ToList();

View:
<% for (int i = 0; i < Model.CurrencyPairs.Count; i++)
{
%>
    <%: Html.HiddenFor(m => m.CurrencyPairs[i].SelectedCurrencyId1) %>
    <%: Html.DropDownListFor(m => m.CurrencyPairs[i].SelectedCurrencyId1, (IEnumerable<SelectListItem>)ViewData["Currencies"])%>
<%} %>

At the same time, if you use a separate field with an ID, then the selected element works successfully (TestId is specified in controller):
<%: Html.DropDownListFor(m => m.TestID, (IEnumerable<SelectListItem>)ViewData["Currencies"])%>

The feeling that the problem is that the desired ID for the drop-down list is nested in another structure, but I can't explain it
Comment: Still acutally.
Answer: $(document).ready(function () {
    <% if (Model.CurrencyPairs != null)
    { %>
        <% for (int i = 0; i < Model.CurrencyPairs.Count; i++)
        {%>
            $("#CurrencyPairs_<%: i %>__FirstCurrency_Id").val("<%:Model.CurrencyPairs[i].FirstCurrency.Id %>");
            $("#CurrencyPairs_<%: i %>__SecondCurrency_Id").val("<%:Model.CurrencyPairs[i].SecondCurrency.Id %>");
     <% } %>
 <% } %>
});

The problem was solved using js: after loading the page, go through the displayed list and and set the selected item. But this is a crutch, I have not found another solution...

Creating a DropDownListFor in loop


Latex how to define a simple math subtraction by new command

Question: In Latex, I want to define a simple math operation. For example, I have many numbers 1,2,3,4,5, how to subtract 1:
Like
\newcommand\myMath[1]%
{%
  \pgfmathparse{#1-1}%
}

Answer: You'll need \pgfmathresult or similar to print the result of your calculation:
\documentclass{article}

\usepackage{tikz}

\newcommand\myMath[1]{%
  \pgfmathparse{#1-1}\pgfmathresult%
}

\begin{document}

\myMath{1}

\myMath{2}

\myMath{3}

\myMath{4}

\end{document}

If you don't want to use the heavy TikZ weapons just to do some calculations, you could use package like xfp:
\documentclass{article}

\usepackage{xfp}

\newcommand\myMath[1]{%
  \fpeval{#1-1}%
}

\begin{document}

\myMath{1}

\myMath{2}

\myMath{3}

\myMath{4}

\end{document}

Or if your calculations don't get too complicated, you could let latex do them:
\documentclass{article}

\newcommand\myMath[1]{%
  \number\numexpr#1-1\relax%
}

\begin{document}

\myMath{1}

\myMath{2}

\myMath{3}

\myMath{4}

\end{document}


Advanced combinatorics question for R

Question: I have 2 groups with 3 observations each.
Group 1: a=1, b=3, and c=2
Group 2: d=0, e=1, and f=0
I would like to understand which group has the higher values, but cannot use a t-test (neither non-parametric nor dependent t-tests can resolve the special dependency I have in my data).
A solution is to now create all possible combinations of observations. In addition to our data order abc-def, we create abd-cef, abe-cdf, abf-cde, etc. We want all possible permutations, but we don't count within group order differences (abc-def is not different from abc-edf and should be considered one permutation, because the same items belong to the same group).
We create a distribution of group differences across all permutations, and can find out whether our data is within the 2.5% on both ends to see whether the difference is significant on a 5% level.
How would I go about this in R? (I have many more observations but once this example code is setup I could adapt).
Comment: Although the referenced *question* is not a duplicate of this one, [@Gung's reply there](http://stats.stackexchange.com/a/137188/919) completely answers this question, right down to working `R` code.
Answer: Permutation tests are actually implemented in R in coin package so I would recommend checking it first before coding things by hand. However, if you want to code your function then you could use combn function from utils library (available by default). combn generates all possible combinations of elements in given input variable (vector, matrix etc.). Notice however that the number of possible combinations depends on the number of distinct values in your variables and could be possibly huge, so this could be possibly very time-inefficient method.

Advanced combinatorics question for R


How long would it take to learn grade 6 music theory?

Question: My teacher wants me to go in for my grade six piano. However, I have only ever done grade one, so my theory is somewhat inferior to my playing. I want to then carry on to do my grade seven and eight. I am in year 12 now and doing all three would help me acquire more UCAS points. How long do you think it would take me to learn the theory, and do you think I would be able to do at least grade six and seven before I leave school?
Answer: You won't need grade VI theory. Most boards expect grade V theory to be passed before a candidate takes grade VI, VII and VIII practical - on any instrument.
The theory will help with your playing - to a degree. No, not a degree exam! You need to concentrate on reading the syllabus for grade V theory, and within say 6 mths, be ready for the exam. That happens three times a year, and teacher will know when. The practical exams take about a year each for an average player - whatever that is!
Answer: Roughly speaking, grade 5 music theory is considered equivalent to a UK GCSE exam.  So it's not a trivial thing to do.
There are theory books, and exercise books to buy.  You can buy past exam papers from the ABRSM, along with the answers to go with them.  So it's possible to test yourself before taking the exam.


Queries about database management system

Question: i want to write these queries

show the name of students who never Loaned Poetry books.
show the Name of student who Loaned more than 5 books.
show student name, book Title, issue Date, and author name  of all bookes issued books.

Query i wrote so far is not working for first task
SELECT
    name
FROM
    students
INNER JOIN issued ON students.rollno = issued.rollno
GROUP BY
    issued.rollno
HAVING
    COUNT( issued.rollno )> 2

Comment: please write your approaches and where you got stuck... is it a homework?
Comment: Please modify your question to include table data in _text_ format, and make it clear for reading.
Answer: Give these queries a try
select s.name from students s
left join issued i on (s.rollno = i.rollno)
left join bookcopy bc on (i.copyid = bc.copyid)
left join books b on (bc.bookid = b.bookid)
left join category c on (b.catid = c.catid and c.catname = 'Poetry')
where c.catid is null

select s.name, count(*) as from students s
left join issued i on (s.rollno = i.rollno)
group by s.name
having count(*) > 5

select s.name, b.title, a.authorname, i.issuedate from students s
left join issued i on (s.rollno = i.rollno)
left join bookcopy bc on (i.copyid = bc.copyid)
left join books b on (bc.bookid = b.bookid)
left join author a on (b.authorid = a.authorid);

Comment: I have a weird feeling I just did your homework, but if you find sql hard, I hope you study these queries and try to understand them so that you can write them yourself :)
Comment: select name, count(*) from students s
left join issued i on (s.rollno = i.rollno)
group by s.name
having count(*) > 5 this one works only one question solved thanks
Comment: I'm glad I could be of assistance :) Sure, I can give it a try
Comment: btw, a tip for next time your write a question here (as stated by Tim under your original post) Write table structure and data in raw text format, much easier for people to read and understand :)
Comment: Your first question, look at the first query i wrote. its basically the same but opposite, so you would like to change "where c.catid is null" to "where c.catid is not null" and change "c.catname = 'Poetry'" to "c.catname in ('Poetry','Novel','Mathematics')"
Comment: Similar approach on second question: select a.authroname from books b
left join bookcopy bc on (b.bookid = bc.bookid)
left join issued i on (bc.copyid = i.copyid)
left join author a on (b.authorid = a.authorid)
where i.issueid is null
Comment: third question: select b.title from books b
join bookcopy bc on (b.bookid = bc.bookid)
join issued i on (bc.copyid = i.copyid)
where b.price >= 500
Comment: you are awesome . whats this reason behind your query writing skill? can you suggest me any good way to get hands on it
Comment: Thank you for your kind words :)
Mostly practice, practice, practice, a dash of google and a few years working with databases writing A LOT of queries.
But all jokes aside.
I would try small, like for example the structure you have displayed in your post, try joining books on author.
See how the result varies with different conditions and joins. If I was in your position, I would probably google sql join examples, and look at the queries that display how this work and try to match my own needs to this, once I get the hang of that, I would expand my query and try to include more tables, etc
Comment: First question you can try something like this: select b.title from books b
where b.price >= (select max(b.price) from books b join category c on (b.catid = c.catid and catname = 'Computer Science'))
Comment: May I ask, are these queries related to a school assignment?
Comment: it might not be the best suggestion of how to acquire knowledge. But never giving up and always trying different approaches and trying to learn what might be wrong if something you write gives the wrong result compared to what you expected is also a good mindset to learning something like writing sql :)
Comment: okey good to hear, not that I would have anything against helping a student, it just would feel a bit wrong writing someones homework :) Congratulations as a fresh graduate tho! :)
Comment: thanks , where are you from and whats your age and designation ?
what is your Whats app number?
and last two queries please
Comment: second question is pretty similar to the first, try this one: select * from books b
join author a on (b.authorid = a.authorid)
where b.price >= (select max(price) from books b join author a on (b.authorid = a.authorid and a.authorname = 'Deitel & Deitel'))
and a.authorname <> 'Deitel & Deitel'
Comment: I think this will solve your third question: select s.name from students s
join issued i on (s.rollno = i.rollno)
join bookcopy bc on (i.copyid  = bc.copyid)
join books b on (b.bookid = bc.bookid)
group by s.rollno
having sum(b.price) >= 500
Comment: on third there is an error message
Column 'students.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
Comment: Try changing 'group by s.rollno' to 'group by s.name'
Comment: from what I can see, the second and third query looks fine to me
Comment: and what about first
Comment: on the first one you probably would want to change 'bookid=4' to 'catid=4' as that's what defines if a book is of Poetry :)
Comment: okay thank you very much . now its time to practice and understand all these joins that you have solved for me. you are great (Y)
Comment: but for catid instead of bookid i have to write a join for it i think
Comment: what was your knowledge level when you had passed graduation ?
Comment: Only if you want to have a condition that says "catname = 'Poetry' from the  table category. But since catid is already in the books table and you know Poetry is catid 4, then 'catid = 4' should work :)
Comment: Bachelors degree within IT. But I had next to nothing related to databases or sql for that matter, I think it was the worst grade I had and I basically disliked anything related to "databases". But money and career opportunities helps a lot :D
Comment: but i have to pick from totalcopy table not from books table, becuase i have to wirte query to 'display total copies of Poetry books '
Comment: hahaha whats your designation and salary. and whats app number. dont worry we will delete our messaging if this site have any kind of restriction :D
Comment: ah yes, you probably need to join bookcopy and books :)
Comment: Titled as a senior consultant working with Oracle database. I avoid any more personal information on the web, so the rest will remain a mystery, besides, I don't user whats app :)
Comment: SELECT COUNT(copyno) FROM bookcopy inner join books on bookcopy.bookid=books.bookid where catid=4   is this right now ?
Comment: Hehe, I'll be around on stackoverflow tho, So I might bump into you on other questions :D


graph $G=(V,E)$ with $i(G) > |V|/2$

Question: Dominating set for a graph $G = (V, E)$ is a subset $D$ of $V$ such that every vertex not in $D$ is adjacent to at least one member of $D$. The domination number $γ(G)$ is the number of vertices in a smallest dominating set for $G$.
Independent set is also a dominating set if and only if it is a maximal independent set, so any maximal independent set in a graph is necessarily also a minimal dominating set. Thus, the smallest maximal independent set is greater in size than the smallest independent dominating set. The independent domination number $i(G)$ of a graph G is the size of the smallest independent dominating set (or, equivalently, the size of the smallest maximal independent set).
I need a graph $G=(V,E)$ with $i(G) > |V|/2$.
Can you help me?
Answer: Take the graph $G = (V,E)$ with $V = \{a,b\}$ and $E = \emptyset$. Then, $i(G) = |V| = 2$.
edit: For a non-trivial example, consider the following graph:

Suppose $W \subset V$ is independent and dominating. If $W$ does not contain $A,B$ or $C$, it mus contain all outer vertices and it follows that $|W| = 9$. If $W$ contains one of the inner vertices ($A,B$ or $C$), it cannot contain the other two and hence must contain the 'other' 6 outer vertices. In this case $|W| = 7$.
It follows that $i(G) = 7 > 6 = |V|/2$.

graph $G=(V,E)$ with $i(G) > |V|/2$


How to prove distributivity in Boolean Rings

Question: A Boolean ring is a ring which all of its elements are idempotent, i.e. $a ^{2}=a$. I know that If we interpret multiplication and addition in such a ring, as meet and joint respectively, then Boolean Ring is essentially the same as Boolean Algebra. But, I don't know how to show that multiplication can be distributed over addition in a Boolean Ring,
$$
a+\left(b.c\right)=\left(a+b\right).\left(a+c\right)
$$
 a property which is an axiom in Boolean Algebra;
$$
a \vee \left(b \wedge c \right)=\left(a\vee b\right)\wedge\left(a\vee c\right)
$$
Answer: Nooo.. Addition is not the join operation, it is rather the symmetric difference:
$$ a+b := (a\land\lnot b) \lor (\lnot a\land b)$$
Comment: And in the opposite direction: If you start from a Boolean ring, you can get the join by $a\lor b := 1-(1-a)(1-b) = a+b-ab$.


Query NHibernate Cache

Question: Is there a way to check if an entity is allready in the cache of NHB (no 2nd level cache enabled)
when only the database primary key/Id is known, without hitting the DB as one would if using Get?
In short something down the lines of:
<code> _session.ExistsInCache()
</code>
Kind regards
Answer: This is one way...
<code>var exists = NHibernateUtil.IsInitialized(Session.Load<YourClass>(id));
</code>

Query NHibernate Cache


How to display nodes based on the taxonomy terms of the current logged in user, with multiple vocabularies?

Question: Say I have 3 taxonomy vocabularies:
Products, Professions and Support
Each vocabulary has 2 terms:
Products -> product1, product2
Professions -> profession1, profession2
Support -> support1, support2
Users can be tagged with terms. User A is tagged with:
product1 and support1
Nodes can be tagged with terms. Node 1 is tagged with:
product1
Node 2 is tagged with:
support1
Node 3 is tagged with:
profession1
So when User A logs in and goes to the view, they should see Node 1 and Node 2 only. I can't seem to achieve this in views. It's possible when there is just one vocabulary, but i can't seem to get it done when there are multiple vocabularies involved. Can anyone help without coding? Or perhaps I need to use code?
Comment: You add a taxonomy field in user profile?
Comment: Hi, this was 6 months ago now :), I used a work around of just having one taxonomy vocabulary instead of 3 - But yes I had a field in the user profile for the taxonomy
Comment: I didn't recognize the date. Sry. :P
Answer: Did you try this using fields instead of taxonomy? I personally prefer using fields over taxonomy since fields are more flexible with views. In your case, if your site is still under development I suggest you to use fields and try out the same.
Comment: Hi Sharan,

Thanks for your response. In the end I just went for the one vocabulary and structured it accordingly. Thanks for the field suggestion, i'll keep that in mind for the future.
Comment: Correct me if I am wrong...am thinking current user in relationships, and in filters using the users taxonomy field and matching it with the contents taxonomy. Comments?


Value of information in a multi-arm bandit problem

Question: Consider a stochastic multi-armed bandit problem, where one of the $N$ arms of a given slot machine must be chosen to be played. Each arm $i$, when played, yields a random real-valued reward $r_i$ according to some fixed (unknown) distribution $p_i(r_i)$ with support over the real line. The random reward obtained from playing an arm repeatedly are i.i.d. and independent of the plays of the other arms. The reward is observed immediately after playing the arm.
Assume that, after $T$ plays of this problem, we have derived an estimate of $p_i(r_i)$ from a limited number of samples, denoted $\hat{p}_i(r_i)$. Clearly, the expected reward obtained in this multi-arm bandit problem should be higher the closer $\hat{p}_i(r_i)$ is from $p_i(r_i)$.
I would like to calculate the utility of knowing the true distribution $p_i(r_i)$, in terms of the expected improvement in rewards from playing according to $p_i(r_i)$ as opposed to $\hat{p}_i(r_i)$.
PS: I realize that the question may require information about which arm is selected based on the various probability distributions estimates $\hat{p}_i(r_i)$. If we assume that the arm with highest $E[r_i]$ is selected, this would suggest that there's no added value in knowing the true distribution $p_i(r_i)$ if $r_i$ has the same mean under both $p_i(r_i)$ and $\hat{p}_i(r_i)$, even if the distributions have different variances. Similarly, if the arm with highest $E[r_i]$ under $\hat{p}_i(r_i)$ is still the best arm under $p_i(r_i)$, this would suggest that learning about $p_i(r_i)$ would have no added value. However, intuitively, it seems like having a more precise and unbiased representation of the reward distributions would be advantageous. Perhaps we need to consider a different action selection approach, such as Thompson-Sampling.
Any pointers towards relevant literature would be greatly appreciated.
Answer: The difference in the expected rewards between a policy which knows the true distribution and your policy which must learn the distribution is called the expected regret (sometimes called the Bayes regret). As a general rule of thumb, the best you can hope for is that the expected regret is $\sqrt{T}$, that is, the penalty for having to learn the distribution is $O(\sqrt{T})$. In general, you can find papers which achieve $O(\log(T)\sqrt{T})$ regret. Sometimes regret bounds are given in terms of the `distribution gap' $\Delta$ (difference between the highest and second highest mean of the rewards), in which case the best bounds are $O\left(\frac{1}{\Delta} \log(T)\right)$.
A good starting place is work by Russo and Van Roy in their paper: "An information-theoretic analysis of Thompson sampling"
https://arxiv.org/abs/1403.5341
Also consider their other work, "Learning to optimize via posterior sampling", https://arxiv.org/abs/1301.2609 which has a very good background and examples section. Finally, their work on Information directed sampling also may be relevant.
You may also find work on Gaussian process bandits helpful, e.g. `Information-Theoretic Regret Bounds for Gaussian Process Optimization in the Bandit Setting' by Srinivas et al. Note that the results in this paper are high-probability bounds on the regret, which in general is a much stronger guarantee than bounds on the Bayes regret.


Flutter Adding Account with AccountManager?

Question: Query
I want to adding account with AccountManager in Flutter.
I have googled but I found in Android not in Flutter; I found flutter package:
https://pub.dev/packages/account_manager_plugin
this package get all account but never to add new account.
any body help me...
Answer: Currently, there is no available plugin that has all the features of Android's AccountManager. You'll either have to dive into its source to jumpstart and create your own plugin, wait for one to be available, or integrate your own Android-specific code.
Comment: Still waiting !


MySQL: How to select rows from one table between each interval taken from other table

Question: There are tables:
1.current_table:

date        value
02.10.2019  1
03.10.2019  2
04.10.2019  2
05.10.2019 -1
06.10.2019  1
07.10.2019  1
08.10.2019  2
09.10.2019  2
10.10.2019 -1
11.10.2019  2
12.10.2019  1

2.intervals

date_start  date_end
02.10.2019  04.10.2019  3
06.10.2019  09.10.2019  4
11.10.2019  12.10.2019  2

"intervals" table contains maximum length of an uninterrupted sequence of positive values.
How to select rows  from "current_table"  between each interval taken from "intervals" table (there are many of such intervals)?
So result should be:
date        value
02.10.2019  1
03.10.2019  2
04.10.2019  2
06.10.2019  1
07.10.2019  1
08.10.2019  2
09.10.2019  2
11.10.2019  2
12.10.2019  1

Comment: I'm a bit lost.  Why not just select from the first table `where value > 0`?  It returns the same result set without referencing the second table.
Answer: My first inclination is simply:
select t1.*
from table1 t1
where t1.value > 0;

Perhaps your intervals might overlap.  Or you might want to filter only for intervals in the second table.  If so, then exists is handy:
select t1.*
from table1 t1
where t1.value > 0 and
      exists (select 1
              from table2 t2
              where t1.date between t2.date_start and t2.date_end
             );

This is overkill for your sample data, though.
Answer: Join the tables.
Only the rows that belong to an interval in table intervals will be returned:
select t.*
from current_table t inner join intervals i
on t.date between i.date_start and i.date_end

See the demo.
Or with EXISTS:
select t.*
from current_table t
where exists (
  select 1 from intervals i
  where t.date between i.date_start and i.date_end
)

See the demo.
Results:
| date       | value |
| ---------- | ----- |
| 2019-02-10 | 1     |
| 2019-03-10 | 2     |
| 2019-04-10 | 2     |
| 2019-06-10 | 1     |
| 2019-07-10 | 1     |
| 2019-08-10 | 2     |
| 2019-09-10 | 2     |
| 2019-11-10 | 2     |
| 2019-12-10 | 1     |


Convergence of discrete function satisfying $|f_{k+1}(X_k)|\leq \delta\Vert f\Vert_\infty$ for $X_k$ Markov chain

Question: Let $N\subset \mathbb N$ be a finite set. Define the sequence of functions $f_{k}: N\to\mathbb R$. Let  $X_k$ be a homogeneous irreducible aperiodic Markov chain taking values in $N$ with no absorbing states. Assume that $f_{k+1}(X_k)$ satisfies the following:
\begin{align}\tag{1}
| f_{k+1}(X_k) |\leq \delta \Vert f_k\Vert_\infty
\ \ \ \text{a. s.}
\end{align}
with $\delta\in(0,1)$.
Question: Can we know something about the convergence of $f_k$? If nothing, what kind of conditions do we need to get some kind of convergence?

Attempts. I think that $f_k\to 0$ at least pointwise. But I cannot use usual tools, because there is some randomness going on here. My stochastic process knowledge is weak, but I tried the following. Define $\tau_n:=\sum_{j=1}^n Y_j$ where $Y_j$ is the time it takes to get to see each state of $X_k$ at least once starting from where we were last in $Y_{j-1}$. Then from $(1)$ we immediately see the following:
$$\Vert f_{\tau_{n+1}}\Vert_\infty \leq \delta \Vert f_{\tau_n}\Vert_\infty$$ Clearly $f_{\tau_n}\to 0$ as $n\to\infty$ (I don't know what kind of convergence do we have here?). It seems that now I have something like: given $\varepsilon>0$, then there is some random time $\tau$ such that for all $k>\tau$ one has:
\begin{align}
\Vert f_k \Vert_\infty \leq \Vert f_{\tau}\Vert_\infty <\varepsilon
\end{align}
Can we conclude $f_k\to 0$ then? What bothers me is the random time $\tau$. Also I think that I need some assumptions on $\tau_n$ like $\tau_n<\infty$ a.s., is that true?
I appreciate any help. Even hints like  "You need to study that part of that book.". Thanks in advance!
(This is actually part of a larger problem where I'm trying to show that the error made in an algorithm will be zero eventuallly)
Comment: @nicomezi yes, I forgot. Edited.
Comment: Does equality (1) hold with probability 1? Is the chain aperiodic?
Comment: @Michael it is actually also aperiodic. I'll add that too.
Answer: For simplicity, assume that the initial condition of the Markov chain is fixed, say, $X_0=0$ surely, where $0$ is a particular state in $N$. Your equality (1) is equivalent to: For all $k \in \{0, 1, 2, ...\}$ we have
$$ |f_{k+1}(X_k)|\leq \delta \max_{x \in N} |f_k(x)| \quad \mbox{(with prob 1)} \quad (1)$$
where $\delta \in (0,1)$ is a given constant.
If the chain is irreducible and aperiodic
Since the chain is finite state, irreducible, and aperiodic, there is a (deterministic) time index $K$ such that for every $y \in N$, we have
$$ P[X_k = y] >0 \quad \forall k \geq K$$
(This can be proven from the fact that aperiodic means there is a $\tilde{K}$ such that it is possible to go from state $0$ to state $0$ in $k$ hops whenever $k \geq \tilde{K}$.) Fix $y \in N, k \geq K$.  If $f_{k+1}(y)>\delta \max_{x \in N} |f_k(x)|$ then
$$P\left[|f_{k+1}(X_k)|> \delta \max_{x \in N}|f_k(x)|\right] \geq P[X_k=y]>0$$
which contradicts (1).  Thus,
$$ |f_{k+1}(y) |\leq \delta \max_{x \in N} |f_k(x)| \quad \forall y \in N, \forall k \geq K$$
Taking a max of both sides over all $y \in N$ gives
$$\max_{y \in N} |f_{k+1}(y)|\leq \delta \max_{x\in N} |f_k(x)| \quad \forall k \geq K$$
and so $\lim_{k\rightarrow\infty}\max_{x \in N} |f_k(x)|= 0$.
If the chain is irreducible but not aperiodic
Here is a counter-example:  Let $N=\{0,1\}$ and consider the Markov chain that deterministically alternates between states 0 and 1 over time $k \in \{0, 1, 2, ...\}$:
$$ X_k =  \left\{ \begin{array}{ll}
0 &\mbox{ if $k$ is even} \\
1  & \mbox{ if $k$ is odd}
\end{array}
\right.$$
It is easy to construct functions $f_k:\{0,1\}\rightarrow\mathbb{R}$ that satisfy (1) with $\delta = 1/2$ such that
$$ \lim_{k\rightarrow\infty}\max_{x \in \{0,1\}} |f_k(x)| = \infty$$
Comment: So $K$ is random, right? How could that be non-problematic? Sorry if this is a silly question. Also your comment says that (1) implies $|f_{k+1}(X_k)|\leq \delta |f_k(X_{k-1})|$, but that is stronger than (1) itself, so I doubt the truth of it...
Comment: $K$ is not random.  I updated my answer to emphasize that, with some explanation.
Comment: You are right about the extra comment I had after my answer, so I deleted it.  It does not affect my answer.
Comment: Thanks for the explanation. One last question about some possible generalization, if one assumes $f_k:N\times \Omega\to\mathbb R$ is random which is fully determined by $\sigma(X_1,...,X_k)$ or see $f_k$ as a random vector with dimension $N$, then I think the same argument applies. Is that true or things get non-trivial then?
Comment: It depends on your revised condition (1)'. It seems you now have functions $f_k(a, X_1, ..., X_k)$ for $a \in N$ and random $X_1, ..., X_k$ in $N$.  Then what is the meaning of $||f_k||$?  Is it $\max_{a, x_1, ..., x_k} |f_k(a, x_1, ..., x_k)|$? In that case there may be vectors $(a, x_1, ..., x_k)$ that never arise in the Markov chain as states $(X_{k-1}, X_1, ..., X_k)$, but have very large $f$ values (similar to my counter-example for the periodic case).
Comment: No then we have $f_k(X_k, \omega)$ and the norm $\Vert f\Vert =\max_x | f(x,\omega)|$. The condition in one remains the same. Just that the sequence of functions $f_k$ are again random on their own.
Comment: So your condition is:
$$ |f_{k+1}(X_k, X_0, X_1, …, X_{k+1})| \leq  \delta \max_{x \in N} | f_k(x, X_0, X_1, .., X_{k})| \quad (\mbox{with prob 1}) $$
This doesn't work: Define $f_0=0$ and for $k>0$ define $$f_k(x, X_0, ..., X_k)= \left\{ \begin{array}{ll}
0 &\mbox{ if $x=X_{k-1}$} \\
k  & \mbox{ otherwise}
\end{array}
\right.$$ Then $f_{k+1}(X_k, X_0, ..., X_{k+1}) = 0$ for all $k$ so the condition is trivially satisfied.
Comment: Many thanks for your time! I really appreciate it.


Does $A$ commuting with a block-diagonal matrix $B=B_1\oplus B_2$ implies it is block-diagonal?

Question: Let $B$ be a block-diagonal matrix, $B\equiv B_1\oplus B_2$, and suppose that $A$ is a matrix such that $[A,B]=0$.
Does this imply that $A$ has the same block-diagonal structure as $B$ (that is, it is block-diagonal with blocks placed at the same positions as those of $B$)?
I understand that, as discussed in Why does a diagonalization of a matrix B with the basis of a commuting matrix A give a block diagonal matrix?, if $A$ and $B$ commute, then they respect each others eigenspaces. This would mean that if, say, $V_1$ is an eigenspace of $B$, then $A V_1\subseteq V_1$. Therefore, if $B_1$ is diagonalizable, then I think $A$ should at least have the block structure
$$ A = \begin{pmatrix} A_{11} & A_{12} \\ 0 & A_{22}\end{pmatrix}.$$
However, what about the cases in which $B_i$ are not necessarily diagonalizable? Do similar conclusions hold? If not, what are some counterexamples?
I'm interested in the statement when we are not assuming the underlying field to be algebraically complete.
Another realted question is Commuting block diagonal matrices, but they also seem to be making further assumptions about the diagonalizability of the underlying matrices.
Comment: $B$ being a multiple of the identity would still make it block diagonal, with any block-diagonal structure you want.
Answer: An easy counterexample is
$$
B=\left(\begin{array}{cc|cc}p&0&0&0\\ 0&1&0&0\\ \hline0&0&1&0\\ 0&0&0&q\end{array}\right),
\ A=\left(\begin{array}{cc|cc}0&0&0&0\\ 0&1&1&0\\ \hline0&1&1&0\\ 0&0&0&0\end{array}\right)
$$
for any $p$ and $q$.
However, the statement is true when $B_1$ and $B_2$ do not share any eigenvalue over the algebraic closure of the underlying field. In this case, when $A$ is comformingly partitioned as $\pmatrix{X&Y\\ Z&W}$, the Sylvester equations $B_1Y=YB_2$ and $B_2Z=ZB_1$ have only trivial solutions $Y=0$ and $Z=0$.
Comment: that is very interesting, thanks. I did get to those equations with $Y$ and $Z$ "intertwining" $B_i$ but didn't know about Sylvester equations.


How to copy only rows for the selected columns C#?

Question: Copying rows (only cells of rows) of selected columns from datagridview1 to a datagridview2 in c#
So far I done this:
int[] onlyCols = { 2,3,5,7 };
int cols = datagridview1.Columns.Count;

datagridview1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect; //default mode
datagridview1.MultiSelect = true;
for (int i = 0; i < cols; i++) { datagridview1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; }
datagridview1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
for (int j = 0; j < cols; j++)
{
    if (onlyCols.Contains(j))
    {
        Console.WriteLine($"j={j}");
        datagridview1.Columns[j].Selected = true;
    }
}

//then copy the columns that I need to have in datagridview2:
foreach (DataGridViewColumn c in datagridview1.SelectedColumns)
{
    datagridview2.Columns.Add(c.Clone() as DataGridViewColumn);
}

Then, lets say, we have 10 columns and 5 rows in datagridview1 and I need to copy only columns from onlyCols(array) into datagridview2 (so far I've done that) but also the cells of the rows for the selected columns.
Comment: The posted code is confusing… instead of looping through `datagridview1` columns once to "select" the columns in the `onlyCols` array, then another loop through those "selected" columns… would it not be easier to simply "clone" the columns that are in the `int` array (`onlyCols`) instead of "selecting" the columns and then cloning the "selected" columns? Example: `foreach (int c in onlyCols) { datagridview2.Columns.Add(datagridview1.Columns[c].Clone() as DataGridViewColumn); }`
Comment: Then to add the rows, the code is going to have to loop through the rows of `dataGridView1` and add those rows to `datagridview2`. Bear in mind that the column indexes will NOT necessarily be the same, therefore you will need to introduce a separate column index variable for `datagridview2`. Example: if the first column cloned in `datagridview1` is column 2, then the index for this column in `datagridview2` is going to be column zero (0). Again, it is difficult to follow exactly what you are trying to do.
Comment: If you can't get what I described working, I can post a small example. However, I suggest you try this on your own first. Since you have the columns added…I suggest adding the same number of rows in grid1 as empty rows to grid2, then, loop through all the rows in grid1 and copy those columns in the array `onlyCol` to the appropriate columns in grid2. But as I stated previously, the column indexes for each grid will/may be different.
Answer: First I like to thank you very much for make me understand this principle of index!
I managed to do what I had in mind to do:
datagridview2.Columns.Clear();
datagridview2.Rows.Clear();
foreach (int c in onlyCols) { datagridview2.Columns.Add(datagridview1.Columns[c].Clone() as DataGridViewColumn); }

foreach (DataGridViewRow r in datagridview1.Rows)
{
    int index = datagridview2.Rows.Add();
    int nCell = 0;
    foreach (DataGridViewCell o in r.Cells)
    {
        if (onlyCols.Contains(o.ColumnIndex))
        {
            datagridview2.Rows[index].Cells[nCell].Value = o.Value;
            nCell++;
        }
    }
}

PS: With the guidance of JohnG, I found out that it was do easy to do!
Thanks man!
Comment: Good effort. May I suggest that looping through ALL the columns in each grid1 row with the `foreach` loop… `foreach (DataGridViewCell o in r.Cells)` … may be doing unnecessary work. This is looping through ALL the columns when we are only concerned with the columns in the `onlyCols` variable. I suggest looping again through all the values in the `onlyCols` array. Something like… `foreach (int c in onlyCols) { datagridview2.Rows[index].Cells[nCell++].Value = r.Cells[c].Value;`. This removes the check for the proper column.


Manifold without point homotopy equivalent to wedge of $2$-spheres.

Question: Let $F$ be a closed, simply connected four-manifold. Let $F'$ be obtained from $F$ by removing a point. How do I see that $F'$ is homotopy equivalent to a wedge of $S^2$'s?
Comment: See Hatcher 4C.
Comment: Have you tried computing the homology of $F'$?
Comment: @MikeMiller Proposition 4C.3?
Answer: The answer is: if and only if $\pi_1(F)=1$.
By cellular approximation theorem we have $\pi_1(F)=\pi_1(F')$, so if $F'$ is a bouquet of spheres, our assumption is satisfied.
In the opposite direction, by $\pi_1(F)=1$ we have $H_1(F)=H^3(F)=0$ using Poincare duality. Therefore, by universal coefficient theorem, $H_2(F)$ has no torsion and $H^1(F)=0$. So, using Poincare duality again, we have $H_3(F)=0$.
By extision, $F$ and $F'$ have the same homology except $H_4$, so $\pi_2(F')=\mathbb Z^k$ for some $k$, and we may to construct a map $\vee_k S^2 \to F'$ that will be an isomorphism on $\pi_2$. Such a map will be also an equivalence on homology, so we have a desired statement.
Comment: Your answer is quite terse. Is it possible you could add a bit more detail/clarification for someone who's a bit slow like me?
Comment: @user378405 i added some details, does it become more understandable?
Comment: If the manifold is not orientable, then I don't see how Poincaré duality can be used?
Comment: @arkeet in this case it actually is, by $\pi_1=1$
Comment: Ah, simply connected implies orientable. OK.


How to exclude any zero within a vector and values after two consecutive zeros?

Question: There's a little thing that I have a lot of problems with: let's say I have a random 10x10 matrix with column a as you see below. What I now want to do is to exclude any row containing a zero in column a. Also, any values after two consecutive zeros have to be excluded so that b is the target vector I want.
a <- c(13, 7, 2, 0, 4, 3, 0, 0, 5, 8)

b <- c(13, 7, 2, 4, 3)

I already tried applying the diff function with different lags but nothing really worked out so far. I appreciate any help!
2nd example: d <- c(0, 0, 0, 0, 0.8, 0, 0, 0.4, 0, 0, 0.5, 0.1, 0, 0.1, 0.1)
The first ten elements should not be included. Maybe, I forgot to mention that I want to exclude all values right after the FIRST two consecutive zeros.
Comment: In the 2nd example, then none of the elements would be included, right because there are 4 consecutive 0's at the beginning?  If it is only 2 consecutive 0's then after the 5th element, ie. 0.8, there are 2 consecutive 0's sorry, I am so confused with your `first ten elements should not be included`
Comment: 0.8 0.4 0.5 0.1 0.1 0.1 is what it spits out. It's just that the 0.8/0.4 is too much, it doesn't exclude ANY value after the first two cons. zeros (starting from the behind on this one). The thing is that I have to start excluding zeros starting backwards on this vector for example, if you understand what I mean: keeping both 0.1, skipping the zero, keeping 0.1 and 0.5, that's all, because two zeros follow
Comment: As I mentioned in the earlier comment, the first 2 consecutive 0's occur after 0.8.  What is your expected output
Comment: 0.5 0.1 0.1 0.1
is what I want
Comment: In your second example, isn't 0.5 after two consecutive 0s and therefore should be removed?
Comment: as weird as it sounds, it's about going backwards..let's say having a dataframe with 200 rows, starting in row 100 and going upwards to row 1.
Comment: @rapuu Did you meant that the first 2 consecutive 0's from backwards?
Comment: @akrun exactly that
Comment: So the two examples correspond to 2 different questions, the first is about removing what is after two consecutive zeros and the second about removing what is before two consecutive zeros?
Comment: Couldn't have said it better, sorry for the confusion, very confused myself.
Comment: I've edited my answer to include both cases.
Comment: it's just that I have a dataframe with 10 cols and 200 rows and starting from a given point I have to go up in one column while in the other column I have to go down, excluding any zeros and stopping right after I hit two consecutive zeros.
Comment: Try `d1 <- rev(d);d2 <- d1[!cumsum(d1 == 0)>=2];rev(d2[d2!=0])
#[1] 0.5 0.1 0.1 0.1`
Comment: @Lamia The two codes work perfectly. There's just one more thing I need help with. Is there a way of making your code start from a certain point within the vector, let's say starting in row 100?
Comment: Apply it to `a[100:length(a)]` instead of applying it to `a`. If you want to keep rows 1 to 99 untouched in the beginning, then do `c(a[1:99],b)`.
Comment: @akrun mhh, the first 10-20 values are not correct, seems like it summed up some values
Comment: @Lamia hey, it's me again, is there a way of keeping the whole row while looking for zeros only in the first column?
Comment: There is no immediate adaptation of this method to a dataframe. It would have to be modified a lot. Had you specified your question from the beginning, I would have answered quite differently, probably using `rle`.
Comment: Alright. I'll try to work it out myself somehow, not quite sure I'll make it! Thanks!
Comment: The format on SO is not suited for new questions within comments. If you have a separate question, you should post it as such.
Answer: We can use
a[cumsum(a == 0)<2 & a!=0]
#[1] 13  7  2  4  3

To get the other values
a[cumsum(a == 0)>2 & a!=0]
#[1] 5 8

Or another option is
library(data.table)
a1 <- a[seq_len(which((a== 0) & (shift(a, fill =0, type = 'lead')==0))-1)]
b <- a1[a1!=0]
b
#[1] 13  7  2  4  3

Comment: @rapuu  Updated the post
Comment: Mhh, I applied the 2nd code to my actual data but it still included values "before" the two consecutive zeros appeared.
Comment: @rapuu You meant the `a[cumsum(a == 0)>2 & a!=0]`.  Could you update your question with another example to check
Comment: Done, sorry for not writing the vector correctly @akrun
Answer: If you want to remove every single 0 and everything that comes after two consecutive 0s, you could do it this way: converting your vector to a string with numbers separated by commas, using a regular expression to remove unwanted elements, and then convert back to numeric vector form:
## gsub("0\\,|(0\\,){2}.*","",..) removes every 0 and every two zeros followed by anything
a = c(13,7,2,0,4,3,0,0,5,8)
b = as.numeric(unlist(strsplit(gsub("0\\,|(0\\,){2}.*","",paste0(a,collapse=",")),",")))

This returns:
[1] 13  7  2  4  3

If you want to remove every single 0 and everything that comes BEFORE two consecutive 0s:
d = c(0, 0, 0, 0, 0.8, 0, 0, 0.4, 0, 0, 0.5, 0.1, 0, 0.1, 0.1)
c = as.numeric(unlist(strsplit(gsub("0\\,|.*(0\\,){2}","",paste0(d,collapse=",")),",")))

This returns:
[1] 0.5 0.1 0.1 0.1

Comment: using this code it says: numeric(0), used on the 2nd example I edited in the original post. @Lamia


When is it useful to have custom construct/destroy methods in allocators?

Question: Custom allocators, and specifically the ability to customise the allocate/deallocate methods are very useful - allowing for control over the low-level memory allocation strategies used in certain performance critical areas. Pooled allocators for node-based containers, and fixed-size allocators are a few examples that come to mind.
But when is it useful to define custom construct/destroy methods?
As I understand it, the standard mandates that these methods have the same effect as placement new and explicit destruction, i.e:
//construct should give the same effect as:
    construct (_Type *_ptr, _Type const&_val)
    {
        new(_ptr) _Type(_val);
    }
//destroy should give the same effect as:
    destroy (_Type *_ptr)
    {
        _ptr->~_Type();
    }

Is there any way to implement these methods in another way - not using placement new and explicit destruction? If not, why are they part of the allocator object? Wouldn't it be easier if everyone just used placement new and explicit destruction directly?
Comment: The `construct` function could perhaps do something else *in addition to* placement new. This is a customization point, it's good to have if you need it.
Comment: @BoPersson: Is there a practical example of what the "something else" would be? I haven't come up with anything that wouldn't be better placed in the `ctor/dtor` of the actual object type itself... Also, if `construct/destroy` did do something different to plain object creation/destruction, the behaviour of local objects created on the stack would be different to those created through the allocator. Is that reasonable?
Comment: That's one reason for having this functionality in the allocator. Perhaps something special *is* needed when the container is stored  in shared memory? It *allows* contained objects to be different from stack objects.
Comment: More answers here: http://stackoverflow.com/q/652715/395718
Answer: For an allocator that substitutes a wrapper type around the template argument, and operates on that instead, construct and destroy should call the wrapper constructor and destructor rather than the allocated type.
In C++11, construct forwards any number of arguments to the constructor. A custom allocator could insert arguments at the beginning or end of the list, or otherwise intercept and modify arguments. This would only work when the user uses in-place construction, though.
By the way, you should never use _Type as an identifier; identifiers with leading underscore followed by capital are reserved for the implementation.


Stability of non-homogeneous ODE

Question: I try to examine stability of non-homogeneous ODE system:
\begin{cases} Dy_{1} = y_{1}+2y_{2} +\frac{3}{x^4} \\ Dy_{2}= 3y_{1}+4y_{2}+ \frac{3}{x^4} \end{cases}
I tried to find solutions of such system and then examine whether solutions are stable, but I can't find them, is there any other method to determine stability of such system?
Comment: Can you show us a screenshot or picture of what you tried? That would really help us help you better. Also, personally, this looks like a problem for variation of parameters. Did you try that?
Answer: First, solve the homogeneous equation:
$$Dy_1=y_1+2y_2$$
$$Dy_2=3y_1+4y_2$$
I am assuming you already know how to do this, so I will just write the solution here:
$$\left[\begin{matrix} y_1 \\ y_2\end{matrix}\right]=\left[\begin{matrix} \frac{1}{6}(-3-\sqrt{33})e^{(5-\sqrt{33})/2} & \frac{1}{6}(-3+\sqrt{33})e^{(5+\sqrt{33})/2} \\ e^{(5-\sqrt{33})/2} & e^{(5+\sqrt{33})/2}\end{matrix}\right]\left[\begin{matrix} c_1 \\ c_2\end{matrix}\right] \text{ where } c_1,c_2\in\mathbb{R}$$
Since there is one negative eigenvalue $\frac{5-\sqrt{33}}{2}$ and one positive eigenvalue $\frac{5+\sqrt{33}}{2}$, the origin is a saddle point and the system is unstable. Therefore, at the very least, you now know the stability of the ODE system.
Now, to actually solve the non-homogeneous equation, use variation of parameters by changing $c_1,c_2$ to $u_1(t),u_2(t)$:
$$\left[\begin{matrix} y_1 \\ y_2\end{matrix}\right]=\left[\begin{matrix} \frac{1}{6}(-3-\sqrt{33})e^{(5-\sqrt{33})/2} & \frac{1}{6}(-3+\sqrt{33})e^{(5+\sqrt{33})/2} \\ e^{(5-\sqrt{33})/2} & e^{(5+\sqrt{33})/2}\end{matrix}\right]\left[\begin{matrix} u_1(t) \\ u_2(t)\end{matrix}\right]$$
$$\left[\begin{matrix} \frac{1}{6}(-3-\sqrt{33})e^{(5-\sqrt{33})/2} & \frac{1}{6}(-3+\sqrt{33})e^{(5+\sqrt{33})/2} \\ e^{(5-\sqrt{33})/2} & e^{(5+\sqrt{33})/2}\end{matrix}\right]\left[\begin{matrix} u_1'(t) \\ u_2'(t)\end{matrix}\right]=\left[\begin{matrix} \frac{3}{x^4} \\ \frac{3}{x^4}\end{matrix}\right]$$
Here, you can use the second equation to solve for $u_1'(t),u_2'(t)$, integrate to solve for $u_1(t),u_2(t)$, and then plug into the first equation to solve for $y_1,y_2$. Good luck!

Stability of non-homogeneous ODE


Self adjoint operators on incomplete spaces

Question: I am actually a physics student.
The definition of self adjoint operators which I have studied is
Definition. A densely defined $A: D_A \rightarrow \mathcal{H}$ is self adjoint if it coincides with its adjoint, where the adjoint is given by
$$D_{A^*} = \{\psi \in \mathcal{H}|\exists \eta \;\forall \alpha \in D_A: \langle \psi, A\alpha\rangle = \langle \eta, \alpha\rangle \}$$
and $A^* \psi = \eta$
This suggests to me that the underlying space $\mathcal{H}$ needs to be a Hilbert space, necessarily, since
(i) the domain lies dense in $\mathcal{H}$ (thus we need complete space (?))
(ii) The definition uses inner product structure
Is this true, or can we still define them on incomplete spaces? The reason I ask this is, suppose I see a random differential equation (excuse me for the typical physics notation)
$$D_x f(x) = g(x);\; x\in (a,b)$$
Given nothing more, the reference I use says
$$\int_a^b dx |x\rangle\langle x| = 1$$
which is actually analogue of something like integration over projection valued measure (of some self adjoint operator)
$$\int_\mathbb{R} dP = id_{\mathcal{H}}$$
According to my knowledge, if we can't define self adjoint operators (here, projection valued measure) without Hilbert space structure, this cannot be done. And if indeed this is to be true, $g \in L^2(a,b)$ and differential operator must be defined on domain of $L^2$.
Can you tell whether I am right or wrong( and why?)
Answer: You can get around using complete spaces for classical problems where separation of variables works. As an example, consider the following on $L^2[0,2\pi]$ consisting of continuous functions:
$$
           A = \frac{1}{i}\frac{d}{dx}
$$
The domain of $A$ may be defined as all continuously differentiable functions $f$ on $[0,2\pi]$ with $f(0)=f(2\pi)$. This $L^2[0,2\pi]$ space is not complete, but it is a valid inner product space, without having to group according to equivalence classes of functions. And $A$ has a classical resolvent operator $(A-\lambda I)^{-1}$ that can be explicitly obtained by solving a classical ODE:
$$
              g = (A-\lambda I)^{-1}f \iff -ig'-\lambda g=f,\; g(0)=g(2\pi).
$$
This has a unique solution for $\lambda\ne 0,\pm 1,\pm 2,\cdots$ given by
$$
    (A-\lambda I)^{-1}f = \frac{e^{i\lambda x}}{e^{-2\pi i\lambda}-1}\int_{0}^{2\pi}ie^{-i\lambda t}f(t)dt+e^{i\lambda x}\int_{0}^{x}ie^{-i\lambda t}f(t)dt.
$$
The resolvent has simple poles at the eigenvalues $\lambda=0,\pm 1,\pm 2,\cdots$ with residues
$$
     R_n f = \left(\frac{1}{2\pi}\int_{0}^{2\pi}f(t)e^{-in t}dt\right)e^{inx}
$$
You will no doubt recognize this as the projection of $f$ onto the eigenfunction $e^{inx}$. It is Stone's formula that connects the resolvent with the spectral object:
$$
      \frac{1}{2}(E[a,b]f+E(a,b)f) \\=\lim_{\epsilon\downarrow 0}\frac{1}{2\pi i}\int_{a}^{b}(A-(u-iv)I)^{-1}f-(A-(u+iv)I)^{-1}f du
$$
And this formula allows you to construct the spectral measure on all finite intervals in a classical way. The above works for all sefaldjoint operators $A$ on a Hilbert space. The convergence of the limit is in $L^2$, but this stays classical in classical ODE problems, even when there is continuous spectrum. Some of the first general classical proofs of convergence of Fourier expansions relied on this method. For the continuous spectrum case on $(-\infty,\infty)$, the problem is formulated with continuous $f\in L^2$ as
$$
           -ig-\lambda g = f,\;\; g\in L^2(\mathbb{R}).
$$
This gives continuous spectrum equal to $\mathbb{R}$ and Stone's formula gives
$$
             E[a,b]f = \mathcal{F}^{-1}(\chi_[a,b]\mathcal{F}f),
$$
where $\mathcal{F}$ is the Fourier transform. The substitute for complete spaces is the existence of the resolvent operator on the full space of continuous functions, for example.
The spectral objects are "constructible," which they would have to be in order to be useful in Quantum Mechanics. And you can restrict to classical settings when dealing with problems that separate. You do end up with Riemann-Stieltjes integrals because general spectral density functions are needed, but that's a long way from the general spaces required for studying non-separable PDEs.
The Hilbert space constructions for a general selfadjoint operator force you into complete spaces, but still the derivation of the spectral measure on an interval follows Stone's formula, and the spectral integrals may be formed from limits of classical Riemann integrals of vector-valued holomorphic functions $R(\lambda)f=(A-\lambda I)^{-1}f$.
Comment: @physicophilic : That's correct: the example is essentially selfadjoint in the context of the Hilbert space $L^2$. Selfadjoint is not completely meaningful when working in incomplete spaces, such as the one I suggested. Requiring symmetry and the existence of the resolvent $R(\lambda)$ for non-real $\lambda$ provides a way to circumvent Hilbert space and selfadjointness. By the way, the resolvent was the earliest way of dealing with this. Fredholm used the resolvent as a foundation;  spectral theory, compactness and complex analysis of the resolvent all grew out his work on integral equations.
Comment: Thank you very much for such an informative answer. I believe I will find this highly instructive in my further study. One question: your example A is only essentially self adjoint, if I am not mistaken.. right?


Resolving namespace conflicts

Question: I've got a namespace with a ton of symbols I use, but I want to overwrite one of them:
external_library.h
namespace LottaStuff
{
class LotsOfClasses {};
class OneMoreClass {};
};

my_file.h
using namespace LottaStuff;
namespace MyCustomizations
{
class OneMoreClass {};
};
using MyCustomizations::OneMoreClass;

my_file.cpp
int main()
{
    OneMoreClass foo; // error: reference to 'OneMoreClass' is ambiguous
    return 0;
}

How do I get resolve the 'ambiguous' error without resorting to replacing 'using namespace LottaStuff' with a thousand individual "using xxx;" statements?
Edit: Also, say I can't edit my_file.cpp, only my_file.h.  So, replacing OneMoreClass with MyCustomizations::OneMoreClass everywhere as suggested below wouldn't be possible.
Comment: Here's a tip - DON'T use the "using" keyword but instead refer to classes with their fully qualified names: vector<> -> ::std::vector<> !
Comment: C++11 will have a nice feature for versioning namespaces (inline namespace) that will allow the user to get exactly this... then again, you might need to wait more than you want for the feature to be in your compiler (unless you are using gcc >4.4) http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2535.htm
Comment: See also [How do you properly use namespaces in C++?](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c)
Answer: The entire point of namespaces is defeated when you say "using namespace".
So take it out and use namespaces. If you want a using directive, put it within main:
int main()
{
    using myCustomizations::OneMoreClass;

    // OneMoreClass unambiguously refers
    // to the myCustomizations variant
}

Understand what using directives do. What you have is essentially this:
namespace foo
{
    struct baz{};
}

namespace bar
{
    struct baz{};
}

using namespace foo; // take *everything* in foo and make it usable in this scope
using bar::baz; // take baz from bar and make it usable in this scope

int main()
{
    baz x; // no baz in this scope, check global... oh crap!
}

One or the other will work, as well as placing one within the scope for main. If you find a namespace truly tedious to type, make an alias:
namespace ez = manthisisacrappilynamednamespace;

ez::...

But never use using namespace in a header, and probably never in global scope. It's fine in local scopes.
Answer: You should explicitly specify which OneMoreClass you want:
int main()
{
    myCustomizations::OneMoreClass foo;
}

Comment: @Kyle: Then stop using `using namespace`. You can't use that then complain about namespace conflicts. That's like having seat-belts in your car, but you rip them out then complain you're not safe.
Comment: what if I can't edit my_file.cpp though?  edited my question above.

Resolving namespace conflicts


Google GCM not registering on some devices

Question: My application is not registering on GCM for some devices. HTC explorer , Galaxy S2 are the devices which are not registering. However LG optimus 4x hd , Galaxy s4 , samsung duos , y are the devices where it is registering with GCM. I am posting my manifest. Any help would be appreciated.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.suremcx"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <permission
        android:name="com.suremcx.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.suremcx.permission.C2D_MESSAGE" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.GET_TASKS" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_om"
        android:label="@string/app_name"
        android:name="com.suremcx.utils.MyApplication"
        android:theme="@android:style/Theme.Black.NoTitleBar" >
        <activity
            android:name="com.suremcx.activity.MainActivity"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.suremcx.activity.MenuActivity" android:screenOrientation="portrait"></activity>
        <activity android:name="com.suremcx.activity.CustomChatActivity" android:screenOrientation="portrait"></activity>
        <activity android:name="com.suremcx.activity.TipsFragment" android:screenOrientation="portrait"></activity>

        <receiver
            android:name="com.suremcx.activity.GcmBroadCastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.suremcx" />
            </intent-filter>
        </receiver>

        <service android:name="com.suremcx.activty.PushNotificationService" />

    </application>

</manifest>

Answer: You've misspelled 'activity' in com.suremcx.activty.PushNotificationService


Why will the estimates of prediction error typically be biased upward with Cross-Validation?

Question: Why the estimates of prediction error will typically be biased upward with Cross-Validation?
Is it like with decisions tree? Using a stopping criterion will increase a little the bias but will considerably decrease the variance (or overfitting in the test set)? Is this why LOOCV minimize bias but has high variance (since using LOOCV is like not using stopping criterion with decision trees)?
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: The training samples in cross validation are smaller than the original sample. Therefore, the model's parameters are not estimated as precisely. Therefore, the validation errors are generally larger than they would be if they were obtained from the model trained on the original sample. This is negligible for LOOCV because the training samples are almost as large as the original sample but can be noticeable for K-fold CV, especially for smaller values of K.
Regarding the variance of LOOCV vs. K-fold CV, it is not clear that the former is generally larger than the latter; see "Bias and variance in leave-one-out vs K-fold cross validation".


Remove data from array according to the second one

Question: I have array that contain - name, email, and ID
I have second array that contain the same parameters, but with different data
I would like to remove all the cells, from the first array, where the emails don't exist in the second array.
For instance -
first array:
array (size=4)
  0 =>
    array (size=3)
      'name' => string 'Shlomi green' (length=25)
      'email' => string 'shlomig$mail.co.il' (length=25)
      'contactID' => string '28' (length=2)
  1 =>
    array (size=3)
      'name' => string 'Roi Keen' (length=21)
      'email' => string 'firstname.lastname@example.com' (length=16)
      'contactID' => string '53' (length=2)
  2 =>
    array (size=3)
      'name' => string 'Ronen' (length=8)
      'email' => string 'ronen$mail.com' (length=23)
      'contactID' => string '43' (length=2)
  3 =>
    array (size=3)
      'name' => string 'Shlomi' (length=10)
      'email' => string 'shlomi$mail.co.il' (length=17)
      'contactID' => string '54' (length=2)

Second array:
array (size=4)
  0 =>
    array (size=3)
      'name' => string 'Shlomi green' (length=25)
      'email' => string 'shlomig$mail.co.il' (length=25)
      'contactID' => string '28' (length=2)
  1 =>
    array (size=3)
      'name' => string 'Ronen' (length=8)
      'email' => string 'ronen$mail.com' (length=23)
      'contactID' => string '43' (length=2)

Only "shlomig$mail.co.il" and "ronen$mail.com" will stay i the first array
Comment: Have you tried something?
Comment: better you could use second array itself.
Comment: what is your expected result ?
Answer: See below, the in-line comments should explain it well enough.
// First populate a single dimension array with
// all of the email addresses in the second array
$keepEmails = [];
foreach($arrB as $keyB=>$valueB) {
    $keepEmails[] = $valueB['email'];
}

// Then iterate through the first array
foreach ($arrA as $keyA=>$valueA) {
    // If email is not in the keepEmails array, then remove
    if (!in_array($valueA['email'], $keepEmails)) {
        unset($arrA[$keyA]);
    }
}

// Re-key the array (so the key values are sequential)
$arrA = array_values($arrA);

If you use array_intersect, take heed of the note in the PHP docs:

Note: Two elements are considered equal if and only if (string) $elem1
  === (string) $elem2. In words: when the string representation is the same.
Comment: @Rio Rizier123 is right, you should look at the comments particularly 'better you could use second array itself.' I assumed that the first array was going to have other entries in the sub-arrays which i why you weren't using the second array, but if you are talking about using array_interesect then that can't be the case. You need to expand on your question.
Comment: can I use "array_intersect" ?
Comment: @Roi Yes you can but be careful of the value comparison, see my updated answer.
Comment: @Roi Maybe you would get more help if you would read and take a look at the comments under your question
Answer: you can user array_intersect if your values are String.
However, in case your values relate to different string representation, although you wanted some of them to be considered as equal, you should take a look at array_uintersect. Thanks to this method, it's possible to use a custom comparison function as a callback.


Erro em reescrita de código procedural para OOP

Question: O arquivo wishlist.php disponível no GIST deveria, através de métodos do arquivo db.php, realizar ações de CRUD e imprimir na tela os resultados obtidos, mas nada é impresso. De mesmo modo o arquivo createNewWisher.php deveria também realizar operações do tipo, mas a tela fica branca.
O sistema funciona perfeitamente em modo procedural, isso aconteceu quando o adaptei para OO. Acredito que esteja deixando algo muito simples passar em branco, e como sou iniciante com programação não estou conseguindo perceber.
Códigos:

db.php: https://gist.github.com/Silence00/64399f17777925211a43
wishlist.php: https://gist.github.com/Silence00/0c7236aa0176b5043f1a
createNewWisher: https://gist.github.com/Silence00/0ec38b8b13839b6bc23b
Comment: Coloque no arquivo onde a tela fica em branco isso no inicio:
`ini_set('display_error', true); error_reporting(E_ALL);`
Comment: @rray inseri, mas nenhum erro foi informado.
Comment: @rray a página não está carregando nem o formulário; como se não houvesse nenhum código na página. Quando eu retiro do script o require e o `$wisherID = WishDB:: ...` o formulário funciona.
Answer: Tela em branco é uma indição de que algum erro aconteceu e o servidor normalmente o de produção oculta os erros por questão de segurança. Para conserto ou debug rápido em produção basta adicionar duas linhas uma que exibe os erros e a outra que indica quais deles devem ser mostrados.
Mais informações sobre erros veja no wiki do php.
ini_set('display_error', true);
error_reporting(E_ALL);

Testei o seu código de listagem e ela apresentou os seguintes erros na classe db

Fatal error: Cannot override final method PDO::__wakeup()

Esse é um método mágico e final que não pode ser sobreescrito, logo comenta ou remova ela.

Fatal error: Access level to WishDB::__construct() must be public (as
  in class PDO) in

Como a classe db herda de PDO você não pode diminuir o nível de acesso um método/propriedade da classe pai. Como o erro sugere deixe o construtor de dbcomo público.
class WishDB extends PDO{
   //propriedades omitidas
   private function __construct(){

O resultado da listagem não pode ser obtido por que seu método retorna um boolean(retorno de execute() ao invés de um array. No caso adicione o tratamento de erro e um array
public function getWishesByWisherId($wisherID)
{
    $consult = $this->prepare("SELECT `id`, `description`, `due_date` FROM `wishes` WHERE `wisherid`=:wisherid");
    $consult->bindValue(':wisherid', $wisherID);
    return $consult->execute();
}

Remova o return $consult->execute(); conforme o código abaixo.
    if($consult->execute() === false){
        print_r($consult->errorInfo());
    }

No arquivo de listagem, mude:
$result = WishDB::getInstance()->getWishesByWisherId($wisherID);
while ($row = $result->fetch(PDO::FETCH_ASSOC))

por:
$result = WishDB::getInstance()->getWishesByWisherId($wisherID);
foreach($result as $row)

Comment: obrigado pela ajuda!! Obrigado também pela dica!
Comment: De nada quando precisar, resolveu tudo? não testei a parte do insert. @Luan.
Comment: Consegui arrumar; com as dicas que você me deu consegui ver alguns outros erros. Obrigado!


$f(x, y)=(x^2-2y^2)e^{-x^2-y^2}$ is bounded

Question: I am trying to prove that the function
$$f(x, y)=(x^2-2y^2)e^{-x^2-y^2}$$
has an absolute maximum and minimum on $\mathbb{R}^2$.
I've found the local maximum / minimum ($\frac{1}{e}$ and $\frac{-2}{e}$) but am not sure how to show that they're also the global max/min.
Comment: Consider writing this in polar coordinates as $ \ (x^2 \ + \ y^2) \ e^{-(x^2 + y^2)} \ - \ 3 y^2 \ e^{-(x^2 + y^2)} \ $ $ \ = \ r^2  \ e^{-r^2} \ - \ 3 r^2 \ (\sin \theta )^2 \ e^{-r^2} \ $ .  Is each term bounded? How do the terms behave far from the origin?
Comment: Sorry but out of curiosity I'm asking as I am new to calculus did you find  the maxima and minima by implicit differentiation.
Comment: Once you've identified all the local extrema, the only thing left to consider is the behaviour at infinity, which is a bit more complicated than the $1$ variable case.  Nevertheless, it is relatively simple to bound $f$ above by $x^2 e^{-x^2-y^2}$ and below by $-2y^2 e^{-x^2-y^2}$, and then show that both of those tend to $0$ as $(x,y)$ grows unbounded.
Answer: $$\frac{d(x^2-2y^2)e^{(-x^2-y^2)}}{dx}=2x(1-x^2+2y^2)e^{(-x^2-y^2)}=0 $$so $$x=0 , x^2-2y^2=1  $$
$$x^2-2y^2=1$$ $$ \frac{1}{e^{(1-3y^2)}}<\frac{1}{e} $$
$$x=0$$
$$-2y^2e^{-y^2}=\frac{-2y^2}{e^{y^2}}>\frac{-2}{e}$$
since:$$(\frac{y^2}{e^{y^2}})^{'}=0$$ gives$$y=0.y=1,y=-1$$