Using $a_{\overline {n} \rceil i}$ from Exam FM.

Question: I am trying to solve the following problem

Olga buys a 5-yr increasing annuity for $X$. Olga will receive $2$ at the end of the first month, $4$ at the end of the second month, and for each month thereafter the payment increases by $2$.  The nominal interest rate is $9\%$ convertible quarterly.  Calculate $X$.

Below is my attempt. I did not use the formula for the special case where P=Q=1 but I chose to use the general formula. But I got the different answer and I don't which step had the problem
$j = \left(1+\tfrac{.09}{4}\right)^{1/3}-1  \approx 0.007444$.
$X = Pa_{\overline {n} \rceil j}+Q*\frac{a_{\overline {n} \rceil j}-nv^{n}}{j}$
$X = (P+\frac{Q}{j})a_{\overline {n} \rceil j}-Q\frac{nv^{n}}{j}$, using the TVM calculator
I got $X = 13068.1656-10304.2044=2763.9612$, which is close to answer C: 2780
But the correct answer is B: 2730
Comment: I get $X=\sum_{n=1}^{60} 2n(1.0225)^{-n/3}=2729.2143$.  Something must have gone wrong before that, as you should have $Qnv^n/j=(2)(60)(1.0225^{-1/3})^{60}/j=10329.5813$ for example.
Comment: Does this answer your question? [Using $(I^{(m)}a)^{(m)}_{\bar{n}|}$ to solve for the present value of an annuity where payments increase monthly](https://math.stackexchange.com/questions/4521292/using-imam-barn-to-solve-for-the-present-value-of-an-annuity)
Answer: $P=Q=2\\
j\approx.007444\\
a_{\bar{n}|j}=\frac{1-1.007444^{-60}}{.007444}\approx48.25\\
nv^n=60\times1.007444^{-60}\approx38.45\\
X=\color{blue}{(2+2\div.007444)\times48.25}-\color{green}{2\times38.45\div.007444}\\
\approx\color{blue}{13060}-\color{green}{10330}=2730$


Criação de objetos (factory) javascript

Question: Olá, Estou tendo a tentar criar dois objetos do tipo pessoa usando Factory e na primeira tentativa eu criar o primeiro elemento e a segunda tentativa em vez de criar o segundo elemento cria um novo elemento, mas com as mesmas características que o primeiro elemento
Classe Pessoa, que será uma super classe
function Pessoa(id, nome) {
  this.id = id;
  this.nome = nome;
}

Classe Aluno extends Pessoa
function Aluno(id, nome) {
  Pessoa.call(this, id, nome);
}

Classe Professor extends Pessoa
function Professor(id, nome) {
  Pessoa.call(this, id, nome);
}

utilizando a função de factory para criar aluno e professor
function Factory() {
    var idAluno = 0;
    var idProfessor = 0;

  this.criarPessoa = function(tipo, nome) {
    var pessoa = new Pessoa();
    switch (tipo) {
      case "1":
        pessoa = new Aluno(idAluno++, nome);
        break;
      case "2":
        pessoa = new Professor(idProfessor++, nome);
        break;
    }
    return pessoa;
  }
}

Classe Escola com uma lista de pessoas[alunos e professores]
function Escola(id) {
  this.pessoas = [];
  this.factory = new Factory();
  this.pessoaCriada = null;

  this.criarProfessorOuAluno = function(tipo,nome) {

    if (tipo!== null) {
      this.pessoaCriada = this.factory.criarPessoa(tipo,nome);

      this.pessoas.push(this.pessoaCriada);

      console.log("\nID: "+this.pessoas[this.pessoaCriada.id].id+
      "\nNome: "+this.pessoas[this.pessoaCriada.id].nome);
    } else {
      console.log("não pode ser vazio");
    }
  }
}

teste no cmd, node app.js
var escola = new Escola(1);
escola.criarProfessorOuAluno("1","Jonh"); //
escola.criarProfessorOuAluno("1","Bob"); //
escola.criarProfessorOuAluno("1","Jerry"); //
escola.criarProfessorOuAluno("2","Tom"); //
escola.criarProfessorOuAluno("2","Peter"); //

e obtive esse resultado

e não aparece os nomes dos professores Tom e Peter, ou se for apenas para um tipo de pessoa funciona tudo bem e se quiser criar outro tipo de pessoa, retorna o valor das pessoas que já se encontram criadas
Comment: da um `console.log(this.pessoas)` esta lá dois índices, do Aluno e Professor, agora  e só você percorrer eles corretamente para mostrar as informações.
Answer: O teu código está correto e podes verificar isso se fizeres console.log(escola.pessoas); que vai dar
[{
    "id": 0,
    "nome": "Jonh"
}, {
    "id": 1,
    "nome": "Bob"
}, {
    "id": 2,
    "nome": "Jerry"
}, {
    "id": 0,
    "nome": "Tom"
}, {
    "id": 1,
    "nome": "Peter"
}]

O que não está correto é como estás a verificar com a consola os dados que estás a criar. Quando usas
console.log(
    "\nID: " + this.pessoas[this.pessoaCriada.id].id +
    "\nNome: " + this.pessoas[this.pessoaCriada.id].nome
);

estás a usar o ID do tipo de pessoa. Ou seja em vêz de estares a verificar a pessoa 1, 2, 3 (independentemente de ser Aluno ou Professor) estás a verificar o índice  em this.pessoas lendo o id interno que está relacionado com quantos desse tipo já existem.
Ora no caso de ser o primeiro Professor registado vai ser 0 e vais estar a buscar o nome de this.pessoas[0].nome e não this.pessoaCriada.nome que é o que procuras. Se criares depois o primeiro Aluno vai dar de novo 0 e vais receber outra vez o mesmo valor. Estás portanto a apontar a lanterna para o sitio errado.
Creio que queres usar
var ultimo = this.pessoas.length - 1;
console.log(
    "\nID: " + this.pessoas[ultimo].id +
    " Nome: " + this.pessoas[ultimo].nome
);

jsFiddle: https://jsfiddle.net/0c72r1uq/
Comment: obrigado, deu certo, funciona perfeitamente. valeu
Comment: @DSanches ótimo, de nada.
Comment: as vezes pequenas instruções o programa não funciona como pretendido mas ainda bem que havia solução

Criação de objetos (factory) javascript


Package names should comply with a naming convention (squid:S00120) and underscore

Question: SonarLint produces an error:
Package names should comply with a naming convention (squid:S00120) ... With the default regular expression ^[a-z]+(\.[a-z][a-z0-9]*)*$.
However the JLS allows and even recommends using the underscore. Clause 6.1. Declarations says, i.a.,

If the domain name contains a hyphen, or any other special character
  not allowed in an identifier (§3.8), convert it into an underscore.

Can I change the regular expression or must it be fixed in the product?
Comment: It is not normative but it is strongly recommended, even with Java 9. I cannot see how a JLS recommendation could be considered bad style.
Comment: I would *tell* the sonarlint people to *stop* enforcing a different (tighter) constraint than what is *specified* in the JLS. They are 100% wrong to do so.
Comment: Underscores and capital letters are *legal* in package names, but they're widely considered bad style.
Comment: I have no problem with banning capital letters, but one cannot comply with another clause in the JLS without the underscore: "You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as oracle.com. You then reverse this name, component by component, ..., and use this as a prefix for your package names, using a convention developed within your organization to further administer package names." My domain is www.qsm-fss.com. So it cannot be bad style to have an underscore in a package name.
Comment: The domain-name-based package naming algorithm is non-normative, right? It is very widely violated in practice.
Comment: I'd ask the sonarlint people why they flag it as an error when someone is following a naming convention from the JLS.
Comment: I posted the same issue on the Google group.
Comment: FWIW I would say that even having a domain name with a hyphen in it is "bad style" of a sort. I don't know of any organization that *only* owns a domain name with a hyphen... to be honest, if I were in that situation I'd think about registering an alternative domain name anyway.
Comment: And refactor hundreds of classes the followed the recommendation?
Comment: SonalLint responded in the Google group: You are right, it was an oversight on our side and since it's not yet possible to change rule parameters from SonarLint in standalone mode, it is a major annoyance.
I've created a ticket to fix this: SONARJAVA-2596
Comment: Thanks but the bug has been fixed.
Answer: Consider using a SonarQube server. You can connect your SonarLint plugin to the server and manipulate the way SL performs SCA in your IDE.
One of the nicer features of SQ is the ability to disable SCA rules and remove them from all future scan. Using this feature, you can disable the package name rule (which I also find annoying),a and not have it clutter up the editing view.
Another option is to create a new rule, which will enforce a new regular expression convention on the package names - for example, allowing package names to be Camel Case.
Finally, as stated by Jonathan Rosenne in a comment to the question, the package name issue SONARJAVA-2596 which Jonathan had opened following this question has been fixed, as can be seen here.
Reference:

How to disable a rule in SonarQube
Writing Custom Java Rules 101
Comment: @JonathanRosenne : I highly recommend using Static Code Analysis tools as a part of any organization's CI/CD flow. I have seen multiple examples of critical issues being exposed prior to the release of an official version thanks to SQ/SL.
Comment: Well, after reviewing the following SCA list : https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#Java - I can say that I know a little about JTest from previous experience in Automation and ThreadSafe which I did not personally use. JTest is interesting thanks to its ability to consolidate automation testing and SCA, which is synergistic IMHO. ThreadSafe I heard about from friends who worked on highly multi-threaded environments and they mentioned it as a life-saver. Add a code coverage tool and your CI should be close to perfect.
Comment: Using an external server is not appropriate to sensitive software.
Comment: @JonathanRosenne : The SQ server is an on-premise server - it  resides on your private cloud and is not exposed outside of your organization. One simply downloads the SQ installation and creates a dedicated SQ server in the internal private cloud.
Comment: Good to know if we ever need it.
Comment: We are using SonarLint, StopBugs and CheckStyle. Could you suggest anything else?


When does this matrix have an integral square root?

Question: Let $d_1$, $d_2$, ..., $d_n$ be positive integers. Let $B$ be the $n \times n$ matrix
$$\begin{pmatrix}
d_1 & 1 & 1 & \cdots & 1 \\
1 & d_2 & 1 & \cdots & 1 \\
1 & 1 & d_3 & \cdots & 1 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
1 & 1 & 1 & \cdots & d_n \end{pmatrix}.$$
When does $B$ have a square root in $\mathrm{Mat}_n(\mathbb{Z})$?
Motivation: The Friendship Theorem states that the only graph in which every pair of vertices is joined by a path of length $2$ is the "Friendship Graph", which you can see at the linked article. If $A$ is the adjacency matrix of such a graph, with degree sequence $(d_1, d_2, \ldots, d_n)$, then $A^2=B$. So this contributes the solution $(d_1, d_2, \ldots, d_n) = (2,2,2,\ldots,2,2m)$, with $n=2m+1$.
I was preparing notes on the friendship theorem and got distracted by trying to figure out when this matrix has an integer square root at all. It seemed like it might make a nice challenge for here.
Answer: $$\pmatrix{r&s\cr t&u\cr}\pmatrix{r&s\cr t&u\cr}=\pmatrix{d_1&1\cr1&d_2\cr}$$ $rs+su=1=(r+u)s$, $tr+ut=1=(r+u)t$, $s=t=r+u=\pm1$. $$\pmatrix{r&1\cr1&1-r\cr}^2=\pmatrix{r^2+1&1\cr1&(r-1)^2+1\cr}$$ $$\pmatrix{r&-1\cr-1&-1-r\cr}^2=\pmatrix{r^2+1&1\cr1&(r+1)^2+1\cr}$$ So for $n=2$, the answer is, $d_1-1$ and $d_2-1$ are squares of consecutive integers.


Norm of Functional on : $c_0 = \{ x \in l^\infty :\ \lim_{k \to \infty}=0 \}$

Question: Take $E = c_0 = \{ x \in l^\infty :\ \lim_{k \to \infty}=0 \}$ and define on $E$ the functional:
$$F(x) = \sum_{n=1}^\infty \frac{x_n}{2^n}$$
$\cdot$Show that $F$ is a linear continuos functional on $E$and compute $||F||$.
Linearity is trivial. To show continuity we show boundedness.
$|F(x)|\leq \sum_{n=1}^\infty \frac{|x_n|}{2^n}\leq \sum_{n=1}^\infty \frac{||x||_\infty}{2^n}= ||x||_\infty\cdot\sum_{n=1}^\infty\frac{1}{2^n}= ||x||_\infty$. Taking the sup for $||x||_\infty\leq 1$, yields $||F||\leq 1$.
So the guess is that $||F||=1$.
However I have now problems computing the actual norm of $F$. For $\forall x\in E$ we have that : $|F(x)|\leq ||F||\cdot||x||_\infty$, but I can not find a sequence $x$ to yield the desired result.
Any suggestion?
Comment: Note that the definition of $\|F\|$ contains a $\sup$, not a $\max$.  Equality does not have to be achieved by any particular $x$.  But here's a hint: consider a sequence  $x$ of which the first $n$ terms are 1 and the rest are 0.
Answer: This is similar to a previous problem you posted. It would be cool if we could take $\{x_n=1\}$ as the witness for the norm. But, $x_n$ doesn't tend to zero.
Instead we use a sequence of sequences $u_n$ such that $|F(u_n)|/||u_n||_{\infty}\to|||F|$. We can take $$u_n:=\{x_k=1\text{ for }n\leq n,\text{ and }x_k=0,\text{ for }k>n\}$$
Then $$\frac{|F(u_n)|}{||u_n||}=|F(u_n)|=\sum_{k=1}^{n}2^{-k}\to\sum_{k=1}^{\infty}2^{-k}=1$$
Answer: For $k\in\mathbb{N}$, take the cutoff sequence $x^k\in c_0$ defined by $x^k_j=1$ for $j\le k$ and $x^k_j=0$ for $j>k$. Now clearly $\Vert x^k\Vert=1$ and
$$|F(x^k)|=\sum\limits_{j=1}^{k}\frac{1}{2^j}=1-2^{-k}$$
which tends to $1$. I don't think there's an $x\in c_0$ with $\Vert x\Vert=1$ and $|F(x)|=1$.


Green's Theorem in polar coordinates - what am I doing wrong?

Question: Let $$\vec F = M\hat i + N\hat j = (3x^2y^2)\hat i + (2x^2 + 2x^3y)\hat j$$
be a vector field, and C be the counterclockwise circle centered at $(a,0)$, with a radius of $a$. Find $\oint_C M\,dx + N\,dy$.
Applying Green's Theorem:
$$\oint_C M\,dx + N\,dy = \iint_R N_x-M_y\,dA = 4\iint_R x\,dx$$
Using center of mass with uniform density in place of direct computation:
$$4\iint_R x\,dx=4\frac{\iint_R x\,dx}{\iint_R\,dx}\iint_R\,dx = 4 \bar x *Area(R) = 4\pi a^3$$
The problem I'm having is when I try to do the double integral by direct computation in polar coordinates. I've checked the intermediate steps with an integral calculator to make sure there wasn't a simple calculation error, which there wasn't, so I'm guessing something is wrong with the setup.
The first thing I did was get an expression for $x$ and $y$ in terms of $\theta$. I did this by noting that, for any ray coming from the origin, it will intersect the circle and form an isosceles triangle, where the first leg of length $a$ is coincidental with the $x$ axis, and the second leg, call it $l$, is the line segment of length $a$ going through the circle's origin and the point of intersection.
From this, the angle between the two legs should be $\pi-2\theta$, since there are two equivalent $\theta$s, and the sum of the angles in a triangle is $\pi$ radians.
The angle $\alpha$ between $l$ and the $x$ axis is $\pi - (\pi - 2\theta)$, since the angle between the two legs of the isosceles triangle plus the angle between $l$ and the $x$ axis should be $\pi$. This makes it easy to get an expression for $x$ and $y$ using vectors. If the circle were at the origin, then we would have $\vec r = (a\,cos(\alpha),a\,sin(\alpha)=(a\,cos(2\theta), a\,sin(2\theta)$, to which we add the offset vector $(a,0)$ to obtain $\vec r = (a(1+cos(2\theta), a\,sin(2\theta)$.
I did this another way to confirm, by using the law of cosines, and it seems correct from that standpoint as well. If the angle between the two sides of the isosceles triangle is $\pi - 2\theta$, then $r$ should be $\sqrt{2a^2(1-cos(\pi - 2\theta)}$, or equivalently, $\sqrt{2a^2(1+cos(2\theta))}$, since $cos(\pi-x)=-cos(x)$. Then, the unit vector extending in the direction of the ray from the origin is $\hat u = (cos(\theta), sin(\theta))$, and the ray should be $r \hat u$.
I graphed both of these representations for the $x$ coordinate, namely, $x=a(1+cos(2\theta))$ and $x=cos(\theta) \sqrt{2a^2(1+cos(2\theta))}$, and they are equivalent on $-\frac{\pi}{2} \le x \le \frac{\pi}{2}$.
Finally, I set up the integral:
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \int_0^{\sqrt{2a^2(1+cos(2\theta))}}r(4a(1+cos(2\theta)))\,dr\,d\theta$$
Evaluating the inner integral leaves:
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} 4a^3(1+cos(2\theta))^2\,d\theta = 6 \pi a^3$$
Interestingly, if I evaluate this integral without the square, i.e.,
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} 4a^3(1+cos(2\theta))\,d\theta$$
then I get the correct answer, although I have no clue at this point how I would get such an expression.
Any insight would be much appreciated.
Answer: Here is a method that produces a value of $4\pi a^3$.
The set of points in $R$ is given by
$$ \{ \theta \in [-\frac{\pi}{2}, \frac{\pi}{2}] , r \in [0,2a\cos(\theta)] \} .$$
In polar coordinates, $x = r\cos(\theta)$. So, the integral becomes
$$ \int_{-\pi/2}^{\pi/2} \int_{0}^{2a\cos(\theta)} 4(r\cos(\theta))r\ dr\ d\theta .$$
Evaluating the inner integral, this is equal to
$$ \frac{32a^3}{3} \int_{-\pi/2}^{\pi/2} \cos^4(\theta)\ d\theta $$
Since $\int_{-\pi/2}^{\pi/2} \cos^4(\theta)\ d\theta$, the result is $4\pi a^3$ as expected.

Unfortunately, I can't figure out why your method doesn't work. Your integral
$$ \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \int_0^{\sqrt{2a^2(1+cos(2\theta))}}r(4a(1+cos(2\theta)))\,dr\,d\theta $$
should be equivalent to my integral because:

$\sqrt{2a^2(1+cos(2\theta))} = \sqrt{4a^2 \cos(\theta)^2} = 2a\cos(\theta)$ on the interval $\theta \in [-\pi/2,\pi/2]$.
$a (1+\cos(2\theta)) = 2a \cos(\theta)^2 = r\cos(\theta)$.

The problem seems to be the manipulation in (2). Running (your integral)
Integrate[4 r (a (1 + Cos[2 t])), {t, -Pi/2, Pi/2}, {r, 0, 2 a Cos[t]}]

in Mathematica returns $6a^3 \pi$. Running (my integral)
Integrate[4 r^2 Cos[t], {t, -Pi/2, Pi/2}, {r, 0, 2 a Cos[t]}]

in Mathematica returns $4a^3 \pi$. The limits of integration are the same, but they produce two different values.
Maybe somebody else can figure out why they produce two different results.

Update: The issue is that we cannot assume $r = 2a \cos(\theta)$. This is because $2a \cos(\theta)$ is the maximum value $r$ obtains, but $r$ varies over the region $R$. Specifically, $r \in [0, 2a\cos(\theta)$.
It's like trying to compute the area of a circle of radius $a$, but instead of writing
$$ \int_0^{2\pi} \int_0^a r\ dr\ d\theta = \pi a^2$$
you write
$$ \int_0^{2\pi} \int_0^a a\ dr\ d\theta = 2\pi a^2$$
and get an answer that is too big.
Comment: @user407691 I got it! Yes, that seems to be the issue. $r = 2a \cos(t)$ is only true for the MAXIMUM value of $r$. But when integrating, $r$ ranges in the interval $[0,2a\cos(t)]$. Assuming $r = 2a\cos(t)$ overestimates the area.
Comment: Hmm, how strange. If I plug in $r=2acos(\theta)$ into your inner integral, $\int_0^{2acos(\theta)} 4r^2cos(\theta)\,dr$, giving $\int_0^{2acos(\theta)} 16a^2cos^3(\theta)\,dr$, the answer becomes $12 a^3 \pi$. I think the issue may be that, in the inner integral, $\theta$ is fixed, so that $r(\theta)$ is also fixed (it's the distance to the circle's circumference). Then this constant value gets included in the calculation an infinite number of times, instead of taking into account small chunks of $r$. Thanks for the reply, will have to think more on this. :)


Let $f, g :(0,1) \to \mathbb{R}\,\,$ s.t. $\lVert g \rVert_2 =3$ and $\lVert f \rVert_1 = e\,\,$, show that $|\int_{0}^{1} g \sqrt{\log(f)}dx| \le 3$

Question: Let $g\in L^2((0,1))$ s.t. $\lVert g \rVert_2 =3\,\,\,$ and $f \ge1, f \in L^1((0,1))$ s.t. $\lVert f \rVert_1 = e\,\,$, prove that:
$$ \Biggl|\int_{0}^{1} g \sqrt{\log(f)}\,dx \Biggr|\,\,\le\,\,3$$
My solution was:
$$ \Biggl|\int_{0}^{1} g \sqrt{\log(f)}\,dx \Biggr|\le \int_{0}^{1} \biggl|g \sqrt{\log(f)}\biggr|\,dx \le \biggl(\int_{0}^{1} |g|^2 \,dx\biggr)^{\frac{1}{2}}\biggl(\int_{0}^{1} \log(f)\,dx\biggr)^{\frac{1}{2}} =3\biggl(\int_{0}^{1} \log(f)\,dx\biggr)^{\frac{1}{2}}$$
the temptation is to say that $(\sup_{x\in(0,1)}|f|)\le\lVert f \rVert_1=e\,\,$ to conclude, but I don't know if it is true in this case. Any suggestion?
Comment: @TitoEliatron Whys is $f \leq \|f\|_1$?
Comment: Mistake... I was thinking on $\|f\|_\infty$
Answer: It is not true that $|f(x)| \leq \|f\|_1$ for all $x$ so your argument does not hold.
Natural logarithm is concave so Jensen's inequaity gives $\int_0^{1} \log f \leq log \int_0^{1} f=1$.
Comment: True! I am feeling a bit stupid now, because I would have thought of it before. Thank you.


How do I read the results of a stored proc into it's complex type

Question: I've created my stored procedure, I've created the complex type using the entity model. Now assuming I have successfully established a connection to the database - I'm now ready to run the store procedure and store the rows in a List<ComplexType>. How do I do this in the best, most efficient way? I'm aware that I can iterate through the columns and rows of an SQLDataReader but it sort of feels like I'd be missing the point of the entity framework.
Thanks a lot.
Answer: You can add the stored procedure as a function import and then call it in your assembly directly:
Using (var context = new NorthwindEntities())
{
               Var query = context.GetEmployeeNames(); // we import the stored procedure as a function GetEmployeeNames().
               //…
}

If you use OUTPUT parameter in your stored procedure, you need to add ObjectParameters to get the return value. For example,
Using(var context = new NorthwindEntities())
{
               ObjectParameter firstname = new ObjectParameter("firstname", typeof(String));
               ObjectParameter lastname  = new ObjectParameter("lastname", typeof(String));
               Var query = context.GetEmployeeByID(123, firstname, lastname);
               // Console.WriteLine("Employee {0}'s name is: {1}.{2}.", 123, firstname, lastname);
}

Here is a live sample:

ReferralVisitors is a Stored Procedure.
Comment: @SkonJeet I just put the live sample in C#.
Comment: Dmitry, thanks so much! I solved it by giving each column an alias in the stored procedure. Thanks again for your help, your original suggestion is what's cracked my problem for me.
Comment: Thanks a lot Dmitry, really appreciate your response. I seem to be getting the following error though: "The data reader is incompatible with the specified 'NorthwindModel.StoredProcedure_Result'. A member of the type, 'Column1', does not have a corresponding column in the data reader with the same name."
Comment: In the above case, Column1 refers to a Count column. Any help is seriously appreciated!
Comment: @SkonJeet   "NorthwindEntities" is only some example. Perhaps you have to use your own data context name.
Comment: I know sorry, ignore that for now - I put that in myself too (to fill the space). The problem is that the complex type doesn't match the result for some reason!? But I've only just created it so I don't know where the mismatch is.


How can I identify the service ID?

Question: I am trying to use Cdn service provided in CDN module version 4.0.1 in my custom module
Until 3.x version we had service id as cdn.settings
But from 4.x version I can see there is no service id
https://git.drupalcode.org/project/cdn/-/blob/4.x/cdn.services.yml?ref_type=heads
I need to pass cdn.settings service id as an argument in my custom service but I am not able to pass due to missing service id  as shown below , when I pass cdn.settings in argument it gives an error, what should be the solution for the same ?
<code>    class: 'Drupal\abc_views\CDNWrapperService'
    arguments: ["@cdn.settings", "@request_stack"]```

</code>
Answer: These are the first two entries in the services file you have linked:
<code>services:
  Drupal\cdn\CdnSettings:
    arguments: ['@config.factory']

  Drupal\cdn\File\FileUrlGenerator:
    public: false
    decorates: file_url_generator
    arguments:
      - '@Drupal\cdn\File\FileUrlGenerator.inner'
      - '%app.root%'
      - '@stream_wrapper_manager'
      - '@request_stack'
      - '@private_key'
      - '@Drupal\cdn\CdnSettings'
</code>
You can see in the second service definition that the last argument is referencing the first service.
Using the class name as service ID makes it easier to autowire services, although Drupal didn't take this route for core services, they implemented aliases. See https://www.drupal.org/node/3323122
Comment: Of course, if in doubt always use single quotes. You didn't get the hint, though. After the module changed the service ID you can use the option `autowire: true` instead of `arguments: ...`.
Comment: when I try to add it under .services.yml file ```arguments: ["@Drupal\cdn\CdnSettings", "@request_stack"]```
Comment: it throws an error ``  Found unknown escape character "\c" at line 26 (near "arguments: ["@Drupal\cdn\CdnSettings", "@request_stack"]").
``
Comment: It worked when I used single quotes instead of double quotes

How can I identify the service ID?


Attempting to use a Datetime from a mouseevent from Matplotlib within Tkinter

Question: I have a plot of data  (using matplotlib and Tkinter) and created a funtion that responds to the user clicking on a point on the plot. I got the program to return the correct y value (because it's simply a float type). However, my x-axis has datetime type data and when I ask it to print the x value, it prints a numpy.float64 type. I'm looking to use the datetime value the user chooses, but I need to access it first.
One example of the x-value returned: 735764.731698
Below is the function dealing with the onpick event.
import matplotlib.pyplot as plt
from Tkinter import *
from PIL import ImageTk, Image
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
from images_to_list import images_to_list
from tkFileDialog import askopenfilename, askdirectory
import matplotlib.dates as mdates

def onpick(self,event):

      im=Image.open('C:\Carbonite\EL_36604.02_231694\EL_36604.02_231694_2015-06-15 10.39.57.jpeg')
        im.show()

        x = event.mouseevent.xdata
        y = event.mouseevent.ydata
        x1 = event.mouseevent.x
        y1 = event.mouseevent.y

        dataind = event.ind[0]

        print type(x),x,y,x1,y1, len(event.ind)

        return True

#Action Creating the UI and running the program
app = App(extra)
app.canvas.mpl_connect('pick_event', app.onpick)
extra.mainloop()

Below is an example of an output when a point is chosen:
%run "C:\Carbonite\Main_interface_file.py"
<type 'numpy.float64'> 735764.732134 1.93689320388 499 242.0 1

Answer: Internally mpl converts dates -> floats (which it knows how to plot) and converts back to date-time for labeling the axes.  The function you need here is num2date
import matplotlib.dates as mdate
dt = mdate.num2date(num)

ex
In [222]:  mdate.num2date(735764.732134).isoformat()
Out[222]: '2015-06-15T17:34:16.377604+00:00'

Also note that the float representation mpl uses internally is float days from 0001-01-01


Execute command give top: failed tty get

Question: I have a problem when executing this line shown below.
sudo /usr/bin/env TERM=xterm /usr/bin/php /home/folder/folder/script.php -b val -a 2018-07-01

It gives me a error top: failed tty get. When I try it with php -f it gives me another problem similar to php --help.
[0] => Array
        (
            [error] => 1
            [return] =>     top: failed tty get

        )

The result that I want is to execute command with success not error I execute this command with SSH in a PHP script.
Comment: "I execute this command with SSH in a PHP script." Please [edit] your question to include the code in your PHP script that executes this command.
Comment: https://serverfault.com/questions/304470/problems-with-cron-script-and-term-definition-using-top-command
Comment: See how I got around it `top -n 1 -b > top-out`, https://github.com/plinker-rpc/system/blob/master/src/System.php#L477
Comment: top -n 1 -b not working @LawrenceCherone i want to exec the line on top without getting this error
Answer: Really could do with a copy of your PHP script here (as requested in comments) to confirm, but based on what you've provided:
It appears what you are trying to do it run "top" in some configuration that requires terminal in a PHP script.
/home/folder/folder/script.php
<?php

exec('top -n 1 -b', $out, $error);

print_r($out);

called by
/usr/bin/php /home/folder/folder/script.php

There are two solutions:
1) Using the above parameters (-n 1 -b) runs in batch mode for one iteration - tested Centos7. This should not need terminal and adds the output to an array. This could be what you need. But if it still fails:
2) Otherwise, you can specify the TERM=xterm - it looks like this is what you've attempted to do, but you need to to it inside the exec, and not in the shell that calls the php script.
/home/folder/folder/script.php
<?php

exec('TERM=xterm top -n 1 -b', $out, $error);

print_r($out);

called by
/usr/bin/php /home/folder/folder/script.php


Automapper: Checking for null in MapFrom

Question: Using version 4.
How do I check for null when doing a map? I tried the .Value, but that's not there on a Null:
        Mapper.CreateMap<Agenda, AgendaViewModel>()
            .ForMember(x => x.DateApproved,
               y => y.MapFrom(s =>  DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc)));

Comment: `s.DateApproved.HasValue` maybe ?
Comment: Check this, use ResolveUsing solution for the better performance of the code:

http://stackoverflow.com/a/35972650/1559611
Answer: Alternatively, you can just check the HasValue property prior to mapping:
Mapper.CreateMap<Agenda, AgendaViewModel>()
     .ForMember(x => x.DateApproved,
                y => y.MapFrom(s => s.DateApproved.HasValue ?
                                    DateTime.SpecifyKind(s.DateApproved.Value, DateTimeKind.Utc) :
                                    DateTime.UtcNow));

Comment: Is z.DateApproved.HasValue same as null check, can't we do simple null check here
Comment: For such scenario ResolveUsing would be a preferred call
Answer: I think this would work:
Mapper.CreateMap<Agenda, AgendaViewModel>()
        .ForMember(x => x.DateApproved,
                    y => y.ResolveUsing(z => z.DateApproved.HasValue
                           ? DateTime.UtcNow :
                           Mapper.Map<Agenda, AgendaViewModel>
                          (DateTime.SpecifyKind(z.DateApproved.Value, DateTimeKind.Utc)));

Comment: Is z.DateApproved.HasValue same as null check, can't we do simple null check here
Comment: @MrinalKamboj Compiler will convert `== null` to .`HasValue` for Nullable types. So it is the same.


Select from group by based on case statement

Question: Based on a table like this I want to group by PRODID, then select a row based on a case statement.  Case statement being if IND1 = 1 select row, else if IND2 = 1 select row, else select row with max DATE. If multiple indicators within a group are 1 select row with the max date from the group of indicators being 1.

PRODID   IND1       IND2       DATE
---------------------------------------------------
1          1         0      4/24/2020
1          0         0      1/2/2020
1          1         0      1/1/2020
2          0         1      4/24/2020
2          0         1      1/1/2020
3          0         0      4/24/2020
3          0         0      1/1/2020
4          1         0      2/2/2020
4          0         1      4/24/2020
4          0         1      4/24/2020

PRODID   IND1       IND2       DATE
---------------------------------------------------
1          1         0      4/24/2020
2          0         1      4/24/2020
3          0         0      4/24/2020
4          1         0      2/2/2020

Answer: One method uses row_number():
select t.*
from (select t.*,
             row_number() over (partition by prodid
                                order by (case when ind1 > 0 then 1 else 2 end),
                                         (case when ind1 = 0 and ind2 > 0 then 1 else 2 end),
                                         date desc
                               ) as seqnum

      from t
     ) t
where seqnum = 1;

If you like arithmetic, this can be simplified to:
select t.*
from (select t.*,
             row_number() over (partition by prodid
                                order by ind1 desc, ind2 * (1 - ind1) desc, date desc
                               ) as seqnum

      from t
     ) t
where seqnum = 1;

Note that one trick in putting the logic together is ensuring that the first row is used in the following situation:
1       0      0      2020-01-21
1       1      0      2020-01-20
1       1      1      2020-01-19

This is why you can't use order by ind1 desc, ind2 desc, date desc (which is quite tempting).


ISOWeek2Date R output the first day of the week?

Question: Quick question.
The IsoWeek2Date function in the ISOweek package in R takes an ISOweek formatted string and outputs a date.
This is probably the case, but I just need to confirm...
Is this date the first day of the week?
Comment: Why don't you try it out and test it?
Comment: Good point... It does.
Answer: Yes it looks like it outputs the first day of the week...


automysqlbackup then rsync

Question: I'm trying to configure an automatic MySQL backup solution under an Ubuntu server.
I have chosen automysqlbackup and rsync for this purpose (does it seem to be a good choice ?)
rsync will be used in the automysqlbackup #POSTBACKUP callback to send the backup to a remote server after each backup.
I found that automysqlbackup uses root as default user to make his operations.
How can I make automysqlbackup use a dedicated linux user so I'd be able to easily manage ssh keys and things like that ?
Update:
The script attached to #POSTBACKUP would resemble:
#!/bin/bash
rsync -ar /var/lib/automysqlbackup/ \
  backup@my_remote_backup_server:~/remote_backup/$HOSTNAME

Answer: You can switch to another user before running rsync, something like this:
su - mysql -s /bin/bash -c 'rsync -ar ...'

Other some solutions that you might interested in:

http://www.zmanda.com/backup-mysql.html
http://www.percona.com/doc/percona-xtrabackup/
Comment: Run it as a cron job of `mysql` instead of `root`.
Comment: What does your postbackup script look like?
Comment: See my updated.
Comment: Run it as `mysql` user instead of `root`. Make sure that `mysql` user has write permission to `/var/lib/automysqlbackup/`.
Comment: `automysqlbackup` runs automatically through cron and following directives from a config file. So I don't know where I should change this user. This config file does not specify the user.
Comment: My daily cron is now `test -x /usr/sbin/automysqlbackup && su -c /usr/sbin/automysqlbackup mybackup` but it is still creating backup files as `-rw------- root root` (`mybackup` is my backup user)
Comment: From `root`, type `crontab -u mysql -e`, then call `automysqlbackup` to run it as `mysql` user.

automysqlbackup then rsync


Is 'fair statistics' a thing?

Question: Given that statistics can often be abused to deliberately present 'facts' to support a pre-existing viewpoint. (Lies, damned lies and statistics).
And given confirmation bias.
Is there an established method of choosing which statistics to use, which ensures (or at least endeavours) to be as fair as possible? And does this area of enquiry have a name?
An example
If you want to compare the relative safety of flying vs. driving, you could choose from:

fatalities per km
fatalities per journey
fatalities per time
injuries per...

etc.
Each one of these would yield different results which would 'pull the blanket' one way or the other. So how do you choose?
Comment: Your formulation is loaded: I would want to advise frequent recourse to Hanlon's Razor: http://en.wikipedia.org/wiki/Hanlon's_razor Otherwise I don't think we can easily improve on what Socrates emphasised: Identify precisely what is the real question and how (indeed how far, or even whether) it can be answered using the data (and science) we have. (Socrates wouldn't have used that wording, but updating is allowed.)
Comment: Your example is not a problem of statistics, but the problem of formalizing the vague concept of "relative safety". As most things affecting the live of people are non-deterministic, many propositions in this "hard to grasp" context can only originate from statistical analysis. This means statistics are often used in areas where there is much room for interpretation, but this is just a coincidence. Thus, the only "fault" of statistics I can identify is its wide applicability.
Comment: I don't meta-analysis is an appropriate tag here and I've edited it out.
Comment: @Nick, maybe I should reformulate my question. I'm not accusing others of lying, I'm saying how do I go about arriving at a valid conclusion, knowing that I may have a bias before starting?
Answer: I think statistics should always focus on their use. In your example, the overall question to compare the safety of flying with driving is hardly useful: You cannot choose to drive from New York to Paris in France by car. In turn, you cannot choose to go to your next supermarket by plane.
But you can decide if you want to travel from Madrid to Paris by either plane or car. This question is much more useful. Also, comparisons between both become automatically fairer because now you compare where both are more comparable.
However, you might find that the actual choice between both by the subjects in your sample might depend on factors like cost, travelling time and luggage. You may find that these factors could also be related to security preferences. You could then try to adjust for these confounding factors by some model if you want to compare only the technical security itself. Or you don't consider these factors as confounders because you are interested in the security of the transportation including the different usages in terms of safety.
In the end, fair statistics is possible by isolating closely the factors involved from the factors you want to have a statement about.
Another requirement is to choose the measurable variable that represents best the point of interest: Is safety understood in terms of life hazards or in terms of injuries? There, it depends on what you are afraid of.
Also, there are questions that cannot be answered by statistical means due to lack of measurable variables.
In the end, fair statistics is possible by isolating closely the factors involved from the factors you want to have a statement about.
Answer: There is an area of enquiry named 'research methods' (students are often required to take a module in research methods prior to undertaking a research project as part of their course).  Its scope is wide, but one aspect is to draw a distinction between a 'research question', which indicates in general terms a  topic of interest, and a 'research hypothesis', which is sufficiently specific and precise to be suitable (if of a quantitative nature) for statistical testing.
In terms of your example, the question 'Is flying safer than driving?' might be acceptable as a research question, but certainly not (even if reformulated as a statement rather than a question) as a research hypothesis.  An example of a good research hypothesis might be: 'The rate of fatalities per journey is lower for flying than for driving when travelling between European cities separated by between 100 and 1,000 miles'.
The practical problem of course is that people often quote statistics when debating or arguing about questions that (like many research questions) are too vague to be resolved by statistical evidence, or indeed to be resolved at all.  Seeking 'fair statistics' doesn't really help here.  The choice is between trying to help people to see that the question is vague and perhaps identify a more precise question that is important to them, or perhaps judging that the debate is fruitless and declining to participate.
Comment: The problem is that 99.9% of political debates and decisions happen in the 'research question' domain, most often with 'supporting' statistics :(

Is 'fair statistics' a thing?


Grouping list elements to dictionary

Question: I have a list that contains 8 elements:
ConfigFile.ControllerList

this list is type of:
List<Controller>

How can i add Controllers from ControllerList to 3 dictionary keys. Dictionary is like:
Dictionary<int, List<Controller>> ControllerDictionary = new Dictionary<int, List<Controller>>();

I want to add first 3 controllers to dictionary key 0, then want to add next 3 controllers to dictionary key 1 and lastly want to add last 2 controllers to dictionary key 2. How can i do that?
Answer: You can use / to split the list into sub-list:
var ControllerDictionary = ControllerList
    .Select((c, i) => new { Controller = c, Index = i })
    .GroupBy(x => x.Index / maxGroupSize)
    .Select((g, i) => new { GroupIndex = i, Group = g })
    .ToDictionary(x => x.GroupIndex, x => x.Group.Select(xx => xx.Controller).ToList());

The idea is to first group the elements by indexes, then divide them by an int maxGroupSize(in your case 3). Then convert each group to a list.
Answer: Not sure if there's a more elegant solution, but something like this should work:
var dict = new Dictionary<int, List<Controller>>();

int x = 0;
while (x < controllerList.Count)
{
   var newList = new List<Controller> { controllerList[x++] };

   for (int y = 0; y < 2; y++) // execute twice
      if (x < controllerList.Count)
         newList.Add(controllerList[x++]);

   dict.Add(dict.Count, newList);
}

To make it more general, you could also create newList empty to start, and then change y < 2 to y < GROUP_SIZE where GROUP_SIZE is whatever sized groups you want. Could even then extract this to an extension method:
public static Dictionary<int, List<T>> ToGroupedDictionary<T>
   (this IList<T> pList, int pGroupSize)
{
   var dict = new Dictionary<int, List<T>>();

   int x = 0;
   while (x < pList.Count)
   {
      var newList = new List<T>();

      for (int y = 0; y < pGroupSize && x < pList.Count; y++, x++)
         newList.Add(pList[x]);

      dict.Add(dict.Count, newList);
   }

   return dict;
}

And then you can do this:
var groups = new[]
{
   "Item1",
   "Item2",
   "Item3",
   "Item4",
   "Item5",
   "Item6",
   "Item7",
   "Item8"
}.ToGroupedDictionary(3);

Comment: You are confusing `dictKey` with the index into `list`…

Grouping list elements to dictionary


Where to see the dbfs before recording an audio in cubase

Question: When setting to record drums, for example, there is the db default setting on the left for 0 db.
But there is the setting for recording audio volume which is recommended at -6dbfs.
Where do Ι get this information from? How do Ι set this?
The audio levels before recording is confusing...
Answer: Sadly I don't get your question exactly... However, the reason why anyone would say you should record at -6dB's is just because you don't want any clipping of your audio signal.
I do a lot of orchestral music with virtual instruments for example. The software that's used is named Kontakt 5. In the settings I can choose if the instruments should be loaded by default with 0dB or -6dB.
If I would head this over to a mixing engineer, he would ask me to provide the stems with a maximum of -6dB to give him enough headroom to do his 'magic'. He will use a lot of plugins like Compressors, EQ's, Limiters which can and will make the track louder. In this case he has 6dB's of range he can work with. If he would throw all that on a 0dB track, it would just start clipping and you get unwanted distortion. He would also have no room to balance the tracks among each other if they're already at 0dB.
So, your question - How do you set it? - Well, just record quieter :P
If you record your audio with a microphone and your stereo out shows that your volume is at 0dB, then just turn down the volume of your microphone until you're at the volume you want.
Comment: Thanks !! you understood exactly what i asked and answered very elegantly:-)


How to configure Obfuscar, The Open Source Obfuscation Tool

Question: I m trying to use the obfuscar free tool to protect my code from reverse engineering. I'm trying to obfuscate the provided example Basic Example. The problem that I can't find how to configure it.
Here's my config.xml
<configuration>

  <startup><supportedRuntime version="v4.0"
     sku=".NETFramework,Version=v4.0,Profile=Client"/>
  </startup>

  <Obfuscator>

    <Var name="InPath"  value="C:\Users\user\Desktop\Obfuscar_2.0.0\Examples\BasicExample\BasicExampleExe\bin\Debug" />
    <Var name="OutPath" value="C:\Users\user\Desktop\Obfuscar_2.0.0\Examples\BasicExample\BasicExampleExe\bin\Debug" />

    <Module file="$(InPath)\BasicExampleExe.exe" />
    <Module file="$(InPath)\BasicExampleLibrary.dll" />
    <Var name="KeepPublicApi" value="true" />
    <Var name="HidePrivateApi" value="true" />

  </Obfuscator>

</configuration>

Comment: You will have to study some MSBuild script, and then read `release.proj` to see how to get everything working.
Comment: This seems to be (yet) another example of a programmer completely leaving the intended user - in this case other coders! - completely at sea. If you're going to spend all that time and effort creating an application/utility, for god's sake, tell people how to use it. Every second project I see on GitHub is the same. [Alights soapbox]
Comment: @CoderDennis That link is now a 404. See my other comment ...
Comment: @SteveCinq I never did get this or any other open source obfuscators to work. I've deleted my comment that had a broken link.
Comment: @CoderDennis I have got it going - probably took more of my time than `Eazfuscator` cost in the end! It mostly works quite well but it can't handle re-signing with pfx which is a bit annoying. So I added a post-event to re-sign using `SignTool` and it's now fine. I never got the source code worked out, tho. Why people don't publish complete, tested, working solutions I'll never understand. BTW, I thought `Eazfuscator` was really good and "eaz"(!) to use. That's my fall-back.
Answer: I had the same question... the example Release.proj build file they provide in the Git attempts to build the Obfuscar binary from scratch. So you need to change two lines of the Release.proj file, assuming you're going to be using the pre-compiled Obfuscar binary file.
First, change the path to the ObfuscarExe path to where you have the binary saved similar to this:

<PropertyGroup>
        <ObfuscatorExe>C:\Program Files (x86)\Obfuscar\obfuscar.Console.exe</ObfuscatorExe>
        <ObfuscatorProject>$(BasePath)\obfuscar.xml</ObfuscatorProject>
        <ObfuscatorInput>$(BasePath)\Obfuscator_Input</ObfuscatorInput>
        <ObfuscatorOutput>$(BasePath)\Obfuscator_Output</ObfuscatorOutput>
</PropertyGroup>

Second, comment out the command to compile the Obfuscar solution:
<ItemGroup>
    <CompileSolution Include="$(BasePath)\BasicExample.sln" />

</ItemGroup>

Comment: When I follow these instructions I just get an error: "BasicExample\Release.proj" (default target) (1) ->
  BasicExample\Release.proj(28,2): error MSB4067: The element <#text> beneath element  is unrecognized.


In tetrahedron ABCD, prove that $r<\frac{AB\cdot CD}{2AB+2CD}$

Question:
Given tetrahedron $ABCD$, let $r$ be the radius of the sphere inscribed tetrahedron. Prove that $$r<\dfrac{AB\cdot CD}{2\,AB+2\,CD}$$

This is difficult question, my friends and I could not find any hint to solve it.
In the case that $ABCD$ is a regular tetrahedron, the inequality is easy to prove.  Let $\ell$ be the side length of $ABCD$.  Then, if $M$ is the centroid of $\triangle ABC$ and $I$ is the center of the insphere of the tetrahedron, then
we have
$$MA=\frac{1}{\sqrt{3}}\,\ell\,,$$
and
$$DM=\sqrt{\frac{2}{3}}\,\ell\,.$$
Since $r=DI$, we have
$$AI=DI=DM-DI=\sqrt{\frac{2}{3}}\,\ell-r\,.$$
Hence, by the Pythagorean Theorem,
$$r^2=IM^2=AI^2-MA^2=\left(\sqrt{\frac{2}{3}}\,\ell-r\right)^2-\frac{1}{3}\,\ell^2\,.$$
So
$$r=\frac{1}{2\sqrt{6}}\,\ell<\frac{1}{4}\,\ell=\frac{AB\cdot CD}{2\,AB+2\,CD}\,.$$
Answer: It is clear when $\vec{AB} \parallel \vec{CD}$, the tetrahedron $ABCD$ is degenerate and $r = 0$, the inequality will be trivially true.
Let us consider the case $\vec{AB} \not\parallel \vec{CD}$.  Under this assumption, one can choose a coordinate system such that

the incenter is centered at origin.
$AB$ is lying in the plane $z = u > 0$.
$CD$ is lying in the plane $z = -v < 0$.

Let $p = |AB|$, $q = |CD|$ and $\displaystyle\;\tau = \frac{v}{u+v} \in (0,1)$.
Let $E, F, G, H$ be the intersection of the edge $AC$, $BC$, $AD$, $BD$ with the plane $z = 0$. The intersection of the tetrahedron $ABCD$ with the plane $z = 0$
will be a quadrilateral with these 4 points as vertices.
It is easy to see

$\vec{EF} \parallel \vec{GH} \parallel \vec{AB}$ and $|EF| = |GH| = p\tau$.
$\vec{EG} \parallel \vec{FH} \parallel \vec{CD}$ and $|EG| = |FH| = q(1-\tau)$.

The quadrilateral is actually a parallelogram with sides $p\tau$ and $q(1-\tau)$.
The intersection of the insphere with the same plane will be a circle of radius $r$. It is clear this circle lies inside above parallelogram.
Since the distance between the line $EF$ and $GH$ is at most $q(1-\tau)$ and the distance between the line $EG$ and $FH$ is at most $p\tau$, we have
$$2r \le \min( p\tau, q(1-\tau) )$$
Treat the RHS as a function of $\tau \in [0,1]$, it is maximized when
$$p\tau = q(1-\tau) \iff \tau = \frac{q}{p+q}$$
This give us
$$2r \le \max_{t\in[0,1]}\min(p t, q(1-t)) = \frac{pq}{p+q} \quad\implies\quad 2r \le \frac{|AB||CD|}{|AB|+|CD|}\tag{*1}$$
This is pretty close to what we want to prove. To show above inequality is actually strict, we need two observations.

The insphere touches the surface of the tetrahedron at 4 points, one at each face. Furthermore, the corresponding face is perpendicular to the radial direction there.
In order for the equality to $(*1)$ to hold, we need
$p\tau = q(1-\tau) = 2r$. On the plane $z = 0$, the parallelogram is actually a square and the circle of radius $r$ need to touch the 4 sides of it.

Combine these two observations, we find in order for the equality to hold, the face holding $EF$ need to parallel to that holding $GH$ and the face holding $EG$ need to parallel to that holding $FH$. Their normal vectors are all orthogonal to the $z$-direction. These four faces are now bounding an infinite long cylinder instead of a tetrahedron. This is absurd and we can conclude
$$2r < \frac{|AB||CD|}{|AB|+|CD|}$$
Update
At the end is a picture which hope to illustrate the configuration. The vertices of the tetrahedron is located at
$$A,B,C,D = (2,0,2), (-2,0,2), (2,-2,-2), (-2,2,-2)$$
Both $\vec{AB}$ and $\vec{CD}$ are lying in some planes perpendicular to $z$-axis. The insphere is centered at $\left(0,0,2\left(\frac{3-\sqrt{5}}{3+\sqrt{5}}\right)\right)$ with radius $r = \frac{4}{3-\sqrt{5}}$. If one cut the tetrahedron with the plane $z = 2\left(\frac{3-\sqrt{5}}{3+\sqrt{5}}\right)$ which passes through the incenter, one obtain a parallelogram $EGHF$ ( $F$ is behind the insphere and not visible from this viewpoint ). The intersection of the insphere with that plane is a circle of radius $r$ which is contained within the parallelogram $EGHF$.
$\hspace 0.75in$
Answer: Let $MN$ be the common perpendicular line of $AB$ and $CD$ with $M$ a point in $AB$ and $N$ in $CD$. The volume $V$ of the tetrahedron $ABCD$ can be calculated in two ways:
$$\begin{align}
 V &= \frac16 \times AB \times CD \times MN \times \sin(\alpha) \\
   &= \frac13 \times r \times (S_{\triangle ABC} + S_{\triangle BCD} + S_{\triangle CDA} + S_{\triangle DAB})
\end{align}$$
where $\alpha$ is the angle between $AB$ and $CD$.
Notice that
$$ S_{\triangle ABC} = \frac12 \times AB \times MC > \frac12 \times AB \times MN, $$
and this is true for all other $3$ triangles. Thus
$$\begin{align}
 V &= \frac13 \times r \times (S_{\triangle ABC} + S_{\triangle BCD} + S_{\triangle CDA} + S_{\triangle DAB}) \\
   &> \frac16 \times r \times (AB \times MN + CD \times MN + CD \times MN + AB \times MN) \\
&= \frac13 \times r \times MN \times (AB  + CD)
\end{align}$$
It follows that
$$\begin{align}
 r \times MN \times (AB  + CD) &< 3V \\
   &= \frac12 \times AB \times CD \times MN \times \sin(\alpha) \\
&\leqslant \frac12 \times AB \times CD \times MN
\end{align}$$
So finally
$$ r < \frac{AB \times CD}{2(AB  + CD)}.$$


$V(I(X)) \cap V(I(Y)) = \emptyset \Leftrightarrow\exists f \in K[x_1,...,x_n] : f(x)=0 \forall x \in X \text { and } f(x)=1 \forall x \in Y$

Question:
For $A\subset K[x_1,...,x_n]$, let $V(A)$ be the affine variety.
  For $B \subset K^n$, let $I(B)$ be the vanishing ideal of $B$.
  I want to show the following equivalence for $X,Y \subset K^n$:
  $$V(I(X)) \cap V(I(Y)) = \emptyset \Leftrightarrow \exists f \in K[x_1,...,x_n] : f(x)=0 \ \forall \ x \in X \text{ and } f(x)=1 \ \forall \ x \in Y.$$

Unfolding the first statement, I got the equivalence
$$\forall (\xi_1,...,\xi_n)\in K^n \ \forall f\in I(X) \ \forall h \in I(Y) : (g+h)(\xi_1,...,\xi_n)\neq 0, \\  \text{since} \ V(I(X)) \cap V(I(Y)) = V(I(X)+ I(Y)).$$ How can I go on from here?
Answer: We know that $V(I)\cap V(J)= V(I+J)$. Assume that $V(I+J)=\emptyset$. By Nulstellensatz we must have $I+J=(1)$. So there exists $f\in I$, $g\in J$ with $f+g=1$. Note that $f=0$ on $V(I)$ and $1$ on $V(J)$.


jsp:include param array

Question: I would like to pass an array as a parameter in a jsp:include. Code below does not work:
<jsp:include page="header.jsp">
    <jsp:param name="stylesheets" value="login.css" />
    <jsp:param name="stylesheets" value="login2.css" />
</jsp:include>

What is the right way to do this, so that ${param.stylesheets} = "login.css, login2.css"?
Answer: You need to access it by ${paramValues.stylesheets} instead. It returns a String[].
Comment: Be aware that user can append "?stylesheets=http://badserver.com/somethingbad.css" and someone, who uses this link, could see altered page which could lead to security vulnerability. And if you include javascript files this way, it could be much worse.
Comment: You deserve the highest of fives.

jsp:include param array


HTTPS for configured site in ISPConfig returns No Data Received

Question: Currently I have ISPConfig installed. I see a problem whenever I try to access a domain with ssl(https://) it always return No data received even though I checked for SSL in the ISPConfig admin panel. I have already changed my ISPConfig to use the correct certificates and it works perfectly. I don't notice any logs being made in apache2 after the error and I'm using the same SSL for the domain and my ISPConfig. Any guidance would be well appreciated!
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: Turns out AT&T Uverse uses wireless STB's that carry an access point that connects to the router and to the outside world with port 443. So whenever it is connected it conflicts with anything else running on port 443.


Como fazer upload de imagens e exibi-las usando jquery?

Question: Como faço para fazer upload de imagens e exibi-las dentro de uma div, e quando o usuário  fizer um novo upload esses imagens serem substituídas.
Ex: o usuário faz o upload de imagens img1.jpg, img2.jpg caso ele faça o upload de novas imagens img3.jpg, img4.jpg as primeira imagem devem desaparecer.  No código abaixo as imagens são adicionadas mas as primeiras imagens ainda continuam.

    <input type="file" multiple id="gallery-photo-add">

Answer: Tenta fazer assim:
  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
        var filesAmount = input.files.length;
        $(placeToInsertImagePreview).empty(); // remove as imagens antigas
        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();
            reader.onload = function(event) {
                $($.parseHTML('')).attr('src',
                event.target.result).appendTo(placeToInsertImagePreview);
            }
            reader.readAsDataURL(input.files[i]);
        }
    }

};


disbale xml button in android

Question: <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
    <string android:enabled="false" name="Close">Close</string>
    <string android:visable="false" name="Create">Create</string>
</resources>

i just added android:enabled="false" to my string .. and still i can't click the button
Comment: You can't put enabled or disabled on a string resource.  You can do that for xml drawables in a statelist drawable, but not strings.
Answer: (You can't put enabled or disabled on a string resource.)
Here is an example of how to enable and disable a button
Button mybutton= findViewById(R.id.button);

// To disable the button
mybutton.setEnabled(false);

// To enable the button
mybutton.setEnabled(true);

You can enable or disable as in the previous example.
Or you can show and hide the button
Button mybutton= findViewById(R.id.button);

// To hide the button
mybutton.setVisibility(View.INVISIBLE);

// To show the button
mybutton.setVisibility(View.VISIBLE);

disbale xml button in android


Multi-tenant in Laravel4

Question: I'm building a multi-tenant app, using the subdomain to separate the users.
e.g. .myapp.com
I want to give each tenant their own database too.
How can I detect the subdomain and set the database dynamically?
Also, the code below is from the official documentation and shows us how we can get the subdomain when setting up a route. But how do we pass the subdomain value to a controller function?
Route::group(array('domain' => '{account}.myapp.com'), function()
{

    Route::get('user/{id}', function($account, $id)
    {
        //
    });

});

Answer: The best way to achieve this would be in a before filter that you apply to the route group.
Route::group(['domain' => '{account}.myapp.com', 'before' => 'database.setup'], function()
{
    // Your routes...
}

This before filters gets a $route parameter and a $request parameter given to it, so we can use $request to get the host.
Route::filter('database.setup', function($route, $request)
{
    $account = $request->getHost();
}

You could then use the account to adjust the default database connection using Config::set in the filter. Perhaps you need to use the default connection first up to fetch the users database details.
$details = DB::details()->where('account', '=', $account)->first();

// Make sure you got some database details.

Config::set('database.connections.account', ['driver' => 'mysql', 'host' => $details->host, 'database' => $details->database, 'username' => $details->username, 'password' => $details->password]);

Config::set('database.connections.default', 'account');

During runtime you create a new database connection and then set the default connection to that newly created connection. Of course, you could leave the default as is and simply set the connection on all your models to account.
This should give you some ideas. Please note that none of this code was tested.
Also, each method on your controllers will receive the domain as the first parameter. So be sure to adjust for that if you're expecting other parameters.
Comment: In the second part of your code, $route->getHost(); returned the string "{account}.myapp.com" instead of the value of the subdomain. Where could I have done wrong?
Comment: Ah, you might have better luck with `$request->getHost()`.

Multi-tenant in Laravel4


How to write a self join query in drupal 7 using db_select

Question: I want to write a self join query, However I dunno how to write it in drupal 7 using db_select().
The query will look like this

SELECT * FROM msg where sender = receiver

Both sender and receiver fields are part of the msg table.
Comment: we can achieve it using the following query.

db_select('msg')
  ->fields('msg')
  ->where('sender = receiver');
Answer: A query using db_select is a lot slower than a 'vanilla' db_query call...for a query as simple as the one you're doing just run it through db_query:
$query = db_query('SELECT * FROM msg where sender = receiver');

Answer: Its possible with the following query,
db_select('msg')
  ->fields('msg')
  ->where('sender = receiver');


Python fill missing data

Question: So I have a table that is kind of data like this
theta    phi    x   y

0       0      1   2
0       1      2   3
--------------------
90      360    4   5

theta values runs from 0 to 90 and for each theta phi runs from 0 to 360,
but some of the phi s are missing here and there in the table and I have to fill those
values. I'm trying to use pandas for this job like this,
import pandas as pd
cols=['theta','phi','x','y']
data = pd.read_csv('data.dat', sep=" |\t", header=None,names=cols,engine='python')

def fill_up(i):
    df=data[data['theta']==i]
    df.set_index('phi',inplace=True)
    df= df.reindex(range(0,361)).reset_index()
    df=df[cols]
    df.interpolate(inplace=True)
    return df

df=pd.concat([fill_up(i) for i in xrange(0,91)])
df.to_csv("new.txt",sep=' ', index=False, header=False)

as you can see I'm creating a seperate data frame for each theta values and concatnating them finally. Is there any way to achieve this without creating a different dataframe or achieving this more efficiently? Also should I take care for any memory overflow as the datafile can be several mb?
Comment: Is it ok to fill those nan values with random numbers in the range 0 to 360? Do you  want to keep the existing non-nan values intact?
Comment: No I need to interpolate the nan values from the non nan
Answer: I think you can do it by setting 'theta' and 'phi' as index with set_index, then reindex with pd.MultiIndex.from_product with all the values of 'theta' and 'phi' you expect, fill nan values with interpolate and finally reset_index such as:
new_data = (data.set_index(['theta','phi'])
                 .reindex(pd.MultiIndex.from_product( [range(91),range(361)],
                                                      names=['theta','phi']))
                 .interpolate().reset_index())

Note the range(91) and range(361) to create all the values for theta and phi.
EDIT for blank line, you can do:
new_data = (data.set_index(['theta','phi'])
                 .reindex(pd.MultiIndex.from_product( [range(91),range(362)],
                                                      names=['theta','phi']))
                 .interpolate().reset_index())
new_data.loc[new_data['phi'] ==361] = ''

Note that the range for phi is range(362) to add a row that you make "blank" with the next command line, replacing all the rows where phi = 361 by blank
Or, with the new_data as in the original solution, you can create a blank dataframe with specific indexes that you can concat to new_data and sort_index after
blanck_frame = pd.DataFrame(data='', columns=new_data.columns
                            index=new_data.loc[new_data['phi'] ==360].index+0.5)
new_data = pd.concat([new_data,blanck_frame]).sort_index()
# you can add  .reset_index(drop=True) at the end if you want integer indexes

Comment: Thanks for your answer. Now for some purposes I need to add one blank line after each theta block in the result data file, can you help me with that.
Comment: @Eular the notion of blank line is a bit ambigous, see my EDIT for doing it the way I understand. I would recommand the second option :)

Python fill missing data


fetching user name

Question: how to fetch user name and this types of information's as a php variable, which can be added as PHP code in block.
As a example, a Welcome message like,
Hi, $data['user'] Welcome to my site

It's output should like this:
Hi, user name Welcome to my site

above code is not working but i think you understand what i want to do. Any idea?
Answer: The username is attached to the global $user object so you can get it like this:
global $user;
$username = $user->name;

And then output it like this:
print 'Hi, ' . $username . ' Welcome to my site';

Comment: something going wrong, because every time i add this code in a block, nothing appear it shows only this code .. so exactly what i should write in a block?
Comment: Sounds like you're trying to put PHP code into the body of a custom block? You'll need to enable the PHP filter module and choose that as the input format for the block body
Comment: from where i can enable  PHP code? Thanks
Comment: from module (core module)
Comment: but i can not fetch users profile picture. How to fetch users profile picture?
Comment: i have tried this but it shows user number `$userphoto = $user->picture;`

fetching user name


better exposed filters and bootstrap 3. Problems with alignment

Question: I have Drupal 7 and the BEF to filter a view. My site is running the Drupal Bootstrap framework V3. The regular 'basic' theming for the exposed filters works, but I would like to use checkboxes and the JQuery slider.
I have a problem with the formatting on check-boxes and sliders.
I've googled it, but didn't find anything relevant.
Thanks in advance
Comment: Hello and welcome. We cannot write missing themes for you. Either report incompatibility in module and theme issue queues, or start fixing it yourself, and ask when you will hit specific problem.
Comment: Bit harsh! This forum is for Drupal questions and this is clearly a Drupal question. If all questions that ultimately relate to coding issues, there would be no questions! This little module: https://github.com/rogercodina/bef_bootstrap_fix mentioned in https://www.drupal.org/node/2121203#comment-9588835 works a treat.
Answer: https://www.drupal.org/node/2121203 gives some answers...

Look at bootstrap/theme/process.inc at function
  _bootstrap_process_input and comment out or remove the 'select' in there.

Still looking for the "ultimate solution" myself as well.
Comment: Great little module to fix this: https://github.com/rogercodina/bef_bootstrap_fix


Friend function of Coordinate class for polar-to-rectangular conversion

Question: I have no clue how to do this i've been working on it for hours. There is only one example of friend classes in my textbook.
This is the question"Construct a class named Coord containing two double-precision variables
named xval and yval, used to store the x and y values of a point in rectangular coordinates.
The class methods should include constructor and display methods and a friend function
named convPol(). The convPol() function should accept two double-precision numbers, r
and theta, representing a point in polar coordinates and convert them into rectangular coordinates.
For conversion from polar to rectangular coordinates, use these formulas:
x = r cos(theta)
y = r sin(theta)"
This is what i've come up with but I know i'm doing it wrong I just don't have a good reference point since there's only one lousy example in the whole textbook and is almost completely different. to be more specific I don't know where to use coord&(how to reference the number) and I know I shouldn't have used pointers. Can somebody point me in the right direction please?
This is my code:
#include <iostream>
#include <cmath>
using namespace std;
//ƒclassƒdeclarationƒsection
void ConvPol(double r,double theta, double& xval, double& yval)
{
double x,y;
 xval=r*cos(theta);
 yval=r*sin(theta);
 return;
}

class Coord
{
  //ƒfriendsƒlist
  friend double ConvPol(Coord&);
  private:
  double xval;
  double yval;
  public:

    Coord (double = 0, double = 0);  //ƒconstructor
    void display();
};
//ƒclassƒimplementationƒsection
Coord::Coord(double x, double y)
{
  xval = x;
  yval = y;

}
void Coord::display()
{
cout <<xval<<","<<yval;
  return;
}
//ƒfriendƒimplementations
void time(double, double, double&, double&);

int main()
{ double xval,yval;
  ConvPol(1,5,xval,yval);
  Coord a(xval,yval);
  a.display();
  return 0;
}

Comment: The declaration of `ConvPol`, as a friend in the class `Coord`, does not match the requirements.  Try `friend void ConvPol(Coord& point, double rho, double theta);`
Comment: Unless you have a specific question/problem/error, this is offtopic here and should be moved to http://codereview.stackexchange.com
Comment: Also, the [tag:r] tag is for the R programming language. Not when you have a variable called R ;-)
Comment: You don't need the `friend` mechanism for a function like `convPol`; the name `convPol` is not self-descriptive and suffers from the needless-arbitrary-shortening sickness; a coordinate class shouldn't have any "display methods" (how do you decide on the user interface API?). In short this is a low quality assignment, teaching ungood things. Where is it from?
Comment: I'm just confused on using the friend list.  I'm still working on the program. I've got it to do what its supposed to but I was using pointers. @Cheers This question is from a textbook "A first book of c++ by Gary Bronson", used by my college.
Answer: Looks like you are confused.  Here's my understanding:
class Coord
{
  friend void ConvPol(Coord& point,
                      double rho, // length
                      double angle);
};

void ConvPol(Coord& point, double rho, double angle)
{
  point.x = rho * cos(angle);  // Assign to the point member x
  point.y = rho * sin(angle);  // Assign to the point member y.
}

According to the requirements, the ConvPol function converts from polar coordinates (rho, angle) to Cartesian coordinates (x,y).  So, the function needs rho and angle.
Since the function is free-standing (not in a method), it needs a Coord instance to receive the converted values.  It is passed by reference because the parameter will be modified (per the contents of the function).
The function does not return anything, so it has a return type of void.
Because the function is a friend of Coord, the function can access the data members directly as if there wasn't any access rights (like a struct).
Comment: Thanks Thomas,  this is very helpful. I'll work on the problem and post back later. This section was roughly 2 pages in my book with only one odd example, again appreciate it.
Comment: This problem was actually not that hard with your explanation. Thank you Thomas, you really cleared things up!!


Turning categorized output into continuous

Question: I'm using a NaiveBayes algorithm that generates categorized probabilities as output instead of continuous values, which is what I need for this webapp I'm working on. Unfortunately I can't switch algorithms right now, what would be the most adequate way/formula at this point to turn the output into a single real number?
The data looks like this (Javascript object):
{
    14:0.01,
    15:0.02,
    17:0.04,
    18:0.06,
    19:0.08,
    20:0.04,
    21:0.04,
    22:0.13,
    23:0.01,
    24:0.09,
    25:0.03,
    26:0.03,
    27:0.08,
    28:0.01,
    29:0.03,
    30:0.03,
    31:0.03,
    33:0.05,
    35:0.01,
    36:0.03,
    38:0.02,
    39:0.01,
    41:0.01,
    42:0.01,
    45:0.01
}

The prediction in this case should be closer to 26. But if I use the mean I get 28.04, which is not bad, but I'm quite certain there's a more sane way to calculate this without using just means given the underlying algorithm and the feeling the result is more like bell shaped.
Comment: How do you get total probability exceeding 1 (and by a long way)? If you have 90% chance of one outcome, all other - mutually exclusive - outcomes should add to 10%, shouldn't they? (Either that or you left out something important in your question.)
Comment: You're right, the data I was looking at was beyond corrupted, sorry. I've just edited the question with correct data and calculations.
Answer: It sounds like you have a distribution, and want to turn it into a point estimate.  The mean is certainly one way to do this, but there are many others.  To decide which method is best, you need to specify an error measure on the estimate, otherwise known as a loss function.  If the error measure is squared error, then the mean is the optimal point estimate.
Your question also seems to ask if there is a better choice of distribution than putting a point mass at each of the given values.  Naïve Bayes by itself doesn't specify how one should interpolate these values, so you would have to apply some density estimator.   For example, a kernel density estimator or interpolation of the empirical CDF.  But I don't think there is much to gain from this.


How to Record Team meeting From as azureBot

Question: i am using this code to join and record ongoing meeting, I am able to join the meeting but not able to record it. I am using following code for join and recording.They are asking for compliance policy and third party "callcabinet" for enabling recording. i just enabled calling policy but should i have to get subscription of "callcabinet" also. Please help me in how to record team meeting using my azure bot. Please help me, this is my humble request.
<code> public async Task<Call> JoinScheduledMeeting(string meetingUrl)
        {
            try
            {
                MeetingInfo meetingInfo;
                ChatInfo chatInfo;

                (chatInfo, meetingInfo) = JoinInfo.ParseJoinURL(meetingUrl);

                var call = new Call
                {
                    CallbackUri = $"{this.configuration[Common.Constants.BotBaseUrlConfigurationSettingsKey]}/callback",
                    RequestedModalities = new List<Modality>()
                    {
                        Modality.Audio
                    },
                    MediaConfig = new ServiceHostedMediaConfig
                    {
                    },
                    ChatInfo = chatInfo,
                    MeetingInfo = meetingInfo,
                    TenantId = (meetingInfo as OrganizerMeetingInfo)?.Organizer.GetPrimaryIdentity()?.GetTenantId()
                };

                var statefulCall = await graphServiceClient.Communications.Calls
                        .Request()
                        .AddAsync(call);

                var clientContext = "clientContext-value";

               var status = RecordingStatus.NotRecording | RecordingStatus.Failed | RecordingStatus.Recording;

                await graphServiceClient.Communications.Calls[statefulCall.Id]
                    .UpdateRecordingStatus(status, clientContext)
                    .Request()
                    .PostAsync();

                return statefulCall;
            }
            catch (Exception e)
            {
                return null;
            }
        }
</code>
Comment: I don't know if you are still working on this problem, but I have added the `microsoft-teams` tag. Hopefully, someone from the team supporting SO will see this and can provide more guidance. Unfortunately, I don't know what else you can try.
Comment: @SAURABHMISHRA - are you assigning a recording policy to a set of users? The recording bot will not be allowed to record unless a user with a recording policy joined the call or meeting.
https://learn.microsoft.com/en-us/microsoftteams/teams-recording-policy#compliance-recording-policy-assignment-and-provisioning
Comment: I'm assuming this is to record an MS Teams meeting, but could you clarify?
Comment: If this is for MS Teams, you may want to check out this option - [record-calls-and-meetings-the-updaterecordingstatus-api-in-microsoft-graph-is-now-generally-available](https://devblogs.microsoft.com/microsoft365dev/record-calls-and-meetings-the-updaterecordingstatus-api-in-microsoft-graph-is-now-generally-available/). It doesn't feature a BotFramework bot, but the code looks like you could substitute a BF bot in.
Comment: Yes.  this is to record an MS Teams meeting using azure bot. I just want to know how i can record ms team meeting using azure bot+botframework+graph api. There is no any relevant articles which can guide me. i dont want to use any third party for recording. i want to make my own  bot to record ms team meeting. Please help me with this.
Comment: The article you send, i went through that but it did not help. i am using UpdateRecordingStatus as you will see in my code.
Comment: this error message is coming in code:

 Microsoft.Graph.ServiceException: 'Code: 8506
Message: API call not allowed for non-Compliance Recording call
Inner error:
 AdditionalData:
 date: 2022-02-17T04:46:09
 request-id: cc852547-ee8d-44cd-9163-00ff7ba85ae6
 client-request-id: cc852547-ee8d-44cd-9163-00ff7ba85ae6
ClientRequestId: cc852547-ee8d-44cd-9163-00ff7ba85ae6
'
Comment: please provide me the right guidance for recording bot. I am trying to not use any third party vendor for recording. I just want my own bot to do that. Can i do that without any vendor??  Please help me with this.
Comment: we have created the policy which you shared and followed all those steps mentioned in reference url but i have one query in following command:
( New-CsOnlineApplicationInstance -UserPrincipalName email@example.com -DisplayName ComplianceRecordingBotInstance -ApplicationId fcc88ff5-a42d-49cf-b3d8-f2e1f609d511).
Can you please let us know what will be the prerequisites for UserPrincipalName(firstname.lastname@example.com). Does this domain required policy certification to be enabled first before we do this step.
Comment: @SAURABHMISHRA - Yes. You have to enabled policy certification first.
Comment: Do we have to take vendor certification from Microsoft??
Comment: @SAURABHMISHRA - Yes you have to take vendor certification. For vendor certification send mail to email@example.com.
Answer: You have to assign a recording policy to a set of users.
The recording bot will not be allowed to record unless a user with a recording policy joined the call or meeting.
You have to enabled policy certification first.
You have to take vendor certification. For vendor certification send mail to email@example.com.
Doc Reference - Compliance recording policy assignment and provisioning
Comment: I have added the compliance recording policy but still recording is not able to start using azure bot.
Comment: To build your own recording bot, you need to get your solution certified.


Getting a menu delivered via REST

Question: I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.
I can successfully return this example json using this function when I hit the URL.
public function get(EntityInterface $entity) {
  $result = array();
  for ($i = 0; $i < 10; $i++) {
    $temp = array(
      'title' => 'Test ' . $i,
      'href' => '#/' . $i
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.
I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.
How do I get menu item titles and paths based on the menu machine name?
EDIT
Ok, sort of figured it out.
public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $renderable = \Drupal::menuTree()->build($tree);
  $result = array();

  foreach (end($renderable) as $key => $val) {
    $temp = array(
      'menu_item' => $val,
      'route' => $key
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

Right now that will output:
[
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Home",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"standard.front_page"
  },
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Communities",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
  }
]

any idea why url or original_link are empty?
Answer: This was the correct answer:
public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $result = array();

  foreach ($tree as $element) {
    $link = $element->link;
    array_push($result, array(
        'title' => $link->getTitle(),
        'url' => $link->getUrlObject()->getInternalPath(),
        'weight' => $link->getWeight()
      )
    );
  }
  return new ResourceResponse(json_encode($result));
}

Getting a menu delivered via REST


Google API PHP Update File

Question: I'm trying to update the content of the file. Use the PHP function:
<code>function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
    try {
        // First retrieve the file from the API.
        $file = $service->files->get($fileId);

        // File's new metadata.
        $file->setTitle($newTitle);
        $file->setDescription($newDescription);
        $file->setMimeType($newMimeType);

        // File's new content.
        $data = file_get_contents($newFileName);

        $additionalParams = array(
            'newRevision' => $newRevision,
            'data' => $data,
            'mimeType' => $newMimeType
        );

        // Send the request to the API.
        $updatedFile = $service->files->update($fileId, $file, $additionalParams);
        return $updatedFile;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

....
$data = retrieveAllFiles($service);

$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);

$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
</code>
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
Comment: Try to send the same request in API explorer and see if you are able to see the update correctly. Here is the link for API explorer: https://developers.google.com/apis-explorer/#p/
Answer: In additionalParams need to add :
<code>'uploadType' => 'multipart',
or
'uploadType' => 'media',
</code>
Hope it helps!

Google API PHP Update File


Como acessar o "this" de uma classe com uma função externa?

Question: Quero criar uma função, dentro de uma classe, que é definida externamente, mas não consigo acessar o this da classe.
Exemplo:

class minhaClasse {
  constructor(objeto){
    this.meuNumero = objeto.meuNumero
    this.minhaFuncao = objeto.minhaFuncao;
  }
}

var meuObjeto = new minhaClasse({
  meuNumero: 4,
  minhaFuncao: ()=>{
    console.log(this.meuNumero)
    //log esperado: 4

    this.meuNumero++;
    console.log(this.meuNumero)
    //log esperado: 5
  }
})

meuObjeto.minhaFuncao();
Answer: Troque o arrow-function:
minhaFuncao: () => {

por function normal:
minhaFuncao: function () {

Assim:

class minhaClasse {
  constructor(objeto){
    this.meuNumero = objeto.meuNumero
    this.minhaFuncao = objeto.minhaFuncao;
  }
}

var meuObjeto = new minhaClasse({
  meuNumero: 4,
  minhaFuncao: function () {
    console.log(this.meuNumero)
    //log esperado: 4

    this.meuNumero++;
    console.log(this.meuNumero)
    //log esperado: 5
  }
})

meuObjeto.minhaFuncao();

Apesar de ter virado moda usar arrow-function e de ter gente achando que esse é o novo modo de se fazer as coisas é um engano, na verdade arrow-function tem um motivo especifico para existir, fora facilitar um pouco o uso do return, o arrow proporciona acessar o contexto do local que é "declarado" como se pertencesse ao mesmo contexto, ou seja, se tiver um this fora da função ele será acessível (o que não é o caso do que você usou, é diferente)
Por exemplo:

function Foo()
{
     this.foo = 1000;

     function bar() {
          return this.foo; //Não vai funcionar, será undefined
     }

     this.response = bar();
}

let teste = new Foo;
console.log(teste.response);

Enquanto com arrow vai ficar acessivel:

function Foo()
{
     this.foo = 1000;

     var bar = () => {
          return this.foo; //Vai funcionar, será 1000
     };

     this.response = bar();
}

let teste = new Foo;
console.log(teste.response);

Isso também poderia ser um return implícito":
var bar = () => this.foo;

Ou seja, function () não é obsoleto, nem deixou de ser usado, é simplesmente que ambos tem hora e lugar para usar, como foi no caso do seu código, o correto a usar é function ()
Comment: Meu deus, não acredito que era algo tão simples.
Muito obrigado.
Comment: @LuísHNrique por nada, atualizei a resposta com detalhes sobre ambos, arrow e function... se puder marque a resposta como correta. Grato


Extension of Pearson's chi-squared test to sequences of multinomial random variables

Question: Background
Suppose we observe $n$ IID Bernoulli variables and our null hypothesis is that their common probability is $p$.
For denote by $\mathbb{1}_{\{i\}}$ the outcome of observation $i$.
Then by the central limit theorem
$\frac{\frac{1}{\sqrt{n}}\sum_{i=1}^n (\mathbb{1}_{\{i\}} - p)}{\sqrt{p \cdot (1 - p)}} \rightarrow N(0, 1),$
which can be used for hypothesis testing.
Suppose now that the null hypothesis is instead that each variable has an individual probability of success, $p_i$ (they are still independent). Then a simple argument allows us to use Lyapunov's version of the CLT and can thus conclude
$\frac{\sum_{i=1}^n (\mathbb{1}_{\{i\}} - p_i)}{\sqrt{\sum_i p_i \cdot (1 - p_i)}} \rightarrow N(0, 1),$ which can then be used to test this composite hypothesis.
Question
If instead we have $k$ categories and our null hypothesis is that the probabilities for each is $p_k$ and we have observed the $n_i$ occurrences of each outcome $i$ then we can use the Chi-Square Goodness of Fit test stating that if the $n_i$ sum to $n$ then
$\sum_{i=1}^k \frac{(n_i - n \cdot p_i)^2}{n \cdot p_i} \rightarrow \chi^2(k - 1)$.
Analogously to above, instead I want to form a null hypothesis where I conduct $n$ experiments, but for each of them the $k$ categories have separate probabilities $\{(p_1^1, p_2^1, \ldots p_k^1), (p_1^2, p_2^2, \ldots p_k^2), \ldots, (p_1^n, p_2^n, \ldots p_k^n) \}.$
Is there a generalization of the Chi-Square Goodness of Fit test applicable to test this kind of hypothesis?
Looking briefly at the proof the case for the standard case gives me a feeling that it should be possible, but surely I can't be the first one asking this?
Comment: This *is* the standard test.  You merely have arranged $nk$ bins into a rectangular array and there are $n$ independent linear constraints on the rows of the array.
Comment: That's correct.
Comment: @whuber Hm, ok.
Checking that I understood you correctly: You mean I view it as I have $nk$ categories and compute the $\chi^2$-statistic where I have a single observation per category (equal to either zero or one) and the null hypothesis is that this is distributed as  $\chi^2 (nk - n)$?
Comment: Thanks. Clearly a sign of my not understanding the test in details since I just swallowed the standard assumption that the probabilities for the respective bins must sum to one.
Comment: I go into this in more detail at https://stats.stackexchange.com/a/17148/919, laying out the necessary conditions and providing a cautionary example.
Comment: @whuber Sure? Did the following experiment to get a feeling:

3 different outcomes, hypothesized probability 1/3, 1/3, 1/3. Actual probability 1/3 + epsilon, 1/3, 1/3 - epsilon.

Draw such a variable n times (from the correct distribution), compute the p-value corresponding to chi^2 in two different ways.

1: Counts and expected counts in 3 different bins, distribution with 3-1=2 degrees of freedom.
2: Form grid of n*3 bins and form counts and expecteds in them, distribution with n*3 - n degrees of freedom.

1 yields extreme p-val for n=1000, 2 yields p close to 0.5 regardless of n
Answer: Could not find an answer to this as a theorem so had to formulate and prove one by myself.
I have $n$ variables $\{X_{i}\}_{i=1}^n$ each attaining a value in $\{1, \ldots k\}$ and my null hypothesis is that $P(X_i = j) = p_i^j$
Then for each $j \in \{ 1, \ldots k \}$ Lyapunov's version of CLT yields
$Z_j := \frac{\sum_{i=1}^n (\mathbb{1}_{\{X_i = j\}} - p_i^j)}{\sqrt{\sum_{i=1}^n p_i^j \cdot (1 - p_i^j)}} \rightarrow N(0, 1).$
So we have $k$ standard normal variables and to proceed we need to figure out their covariance matrix, $\text{cov}(\overline{Z})$.
Straightforward computations yield
$\text{cov}(Z_r, Z_s) = \left\{ \begin{array}{ll} 1 && \text{if } r = s\\
\frac{-\sum_{i = 1}^{n} p_i^r \cdot p_i^s}{\sqrt{(\sum_{i = 1}^{n} p_i^r \cdot (1 - p_i^r)) \cdot (\sum_{i = 1}^{n} p_i^s \cdot (1 - p_i^s))}} && \text{otherwise} \end{array} \right.$
By construction $\text{cov}(\overline{Z})$ is symmetric and real hence by the spectral theorem there are orthonormal eigenvectors of it forming a basis of $\mathbb{R}^k$. Letting $V$ be the matrix of such eigenvectors and $D$ the diagonal matrix of corresponding eigenvalues we have
$\text{cov}(\overline{Z}) = V D V^{\top}$.
Furthermore it's easily seen that
$\text{cov}(V^{\top} \overline{Z}) = V^{\top}\text{cov}(\overline{Z}) V = D$.
Denote the elements of $V^{\top} \overline{Z}$ by $(\xi_i)_i$, the elements of $D$ by ${(d_{i,j})}_{i, j}$ (of course $d_{i,j} = 0$ for $i \neq j$) and define the vector
$\overline{W} = (\frac{\xi_i}{\sqrt{d_{i,i}}} )_{\{i: d_{i,i} \neq 0\}}$.
It's now clear that the elements of $\overline{W}$ are independent standard normals, with length $L = \text{rank}(\text{cov}(\overline{Z}))$.
Hence the distribution of $\| \overline{W} \|^2$ is $\chi^2(L)$ according to the null hypothesis and this squared norm is what we'll compute when conducting our testing.


Reduced-row echelon form associated to three lines in the plane

Question: Let $\ell_1,\ell_2$ and $\ell_3$ be three lines in the plane $\mathbb{R}^2$. For $i = 1, 2, 3$, let the line $\ell_i$ have equation $a_i x + b_i y = c_i$.
Is it possible for the matrix $$
\left(\begin{array}{ccc}
a_1 & b_1 & c_1  \\
a_2 & b_2 & c_2  \\
a_3 & b_3 & c_3 \\
\end{array}\right)
$$ to have reduced row echelon form equal to
$$
\left(\begin{array}{ccc}
0 & 0 & 1  \\
0 & 0 & 0  \\
0 & 0 & 0 \\
\end{array}\right) ?
$$
Comment: Not possible because the third column is for the third variable (say) $z$, which in your case happens to be $1$
Answer: If you extract row 1 from the matrix you have $0x + 0y = 1$ which is not possible, meaning the system of line equations is inconsistent.  Geometrically that means that the three lines do not have a common intersection point.
The three lines you described in the comment below have matrix form:
$ \left( \begin{array}{c}
1 & 0 & 0 \\
0 & 1 & 0 \\
1 & 1 & 0 \end{array} \right)$
I am not sure what you are asking in your comment...
Comment: The three lines having respective equation x = 0, y = 0, x + y = 0 have no common intersection yet the reduced row echelon form has first row
(1 0 0), second row (0 1 0) and third row (0 0 1).
Comment: It is possible that the system is inconsistent yet the reduced row echelon form is not equal to the matrix with first row (0 0 1), second row (0 0 0) and third row (0 0 0).
Comment: if any rows have of an augmented matrix which is in reduced echelon form are all zeros except for the last column, then the solution is inconsistent. Think about what that is saying.  That row would be $0x + 0y = 1$ which is impossible, therefore the system is inconsistent.
Comment: Agreed, the system is inconsistent. Still, that does not rule out that the reduced row echelon form has first row (0 0 1) and all zeroes for the second and third rows.


Bar counting metronome

Question: Does anyone know whether a bar counting metronome exists?
I'm focusing on singing and playing the guitar at the same time and feel a visual bar counter would help me to keep in time. I was hoping for example one could program the metronome to perhaps change the tone of the metronome click after a period of bars that you set, say 8 bars.  Better still it could have a light display which changed colour at the set points. I've had a little look on Google but can't seem to find anything?
Comment: Is this for rehearsing or performance? Many arranger keyboards have measure counters. If you want to develop your time, practice with metronomes that _don't_ play the clicks all of the time, so your brain has to start producing the beats itself. For example, a click on only every third or fourth beat.
Comment: Thanks Piiperi, that's certainly an idea although I'm not sure it would work entirely in my case. I want a guide to keep my guitar playing/strumming tighter. What I find is that when I'm singing at the same time as playing my guitaring can have tendency to just follow the vocals. This can be a problem when a particular verse fits rather awkwardly with a strumming pattern. Therefore whilst I like your idea i'm  not sure it'll work to just define specific chord breaks. That said I'm going to give it a go. Thanks
Answer: I don't know of any such thing, but you could program a simple drum pattern to change the sound every so often. You could do this with the free version of just about any DAW or "drum machine" software.
Comment: Thanks DMB. That's a good idea. That may well work. I do have a daw I just need to learn to programme it. :)
Answer: I think but am not certain that some metronomes, or metronome apps for phones/tablets,  can be set to have multiple pattern sounds, such as heavy down beat, light beats 2,3,4 (in 4/4 time), and different sound for beat divisions.  If you can find one of those, just "reassign" the heavy down beat to your measure bar, set the "light beats" to the downbeat in each measure, and the "beat division" sounds to the light beats in each measure.
Comment: Forgive me if I misunderstand your answer, but OP is looking for a metronome which can display a certain number of bars, not just go 'ping, click, click, click'. So a pattern over say, 8 bars, then another sound to herald the next 8, etc.
Comment: @Tim my solution won't **display** but I'm taking advantage of having at least three distinct sounds to use.
Comment: Thanks Carl and Tim. Yes Tim that's certainly the case but I will see if there's a way to get Tim's idea to work. Thanks both. :)
Answer: You can try out SongPartTrackingMetronome on my wellhoefer.info site, it does exactly what you want: http://wellhoefer.info/metro
"SongPartTrackingMetronome is a simple programmable visual and acoustic metronome with bar-based song part tracking capabilities that guide the user through a song."
Comment: Hi Hans-Peter, welcome to Music.SE! I invite you to edit your answer to include some of the necessary information from the link. That way, if the link ever goes dead (what we call "link rot"), your answer is still helpful and can help individuals find your recommendation.
Comment: @Soren - please remember, if you are posting links to your own site, you must list the attribution.

Bar counting metronome


Favicon .ico vs hospedagem

Question: Existe alguma forma ( Site ) de eu hospedar um arquivo .ico sem que seja no ' servidor ' da aplicação, digo fazer como normalmente fazemos o upload de uma imagem .jpg / .png em sites como Imgur ?
Em grande parte da minha pesquisa antes de fazer está pergunta, o google confundia o ico com outros termos e por conseguinte os resultados não eram o que eu esperava, porém oque encontrei até agora foi :
Is there a free service where i can host a favicon ( .ico ) file ? ( Todas opções citadas estão quebradas )
Using .ico in img tag ( Sem relação )
Favicon: como criar e hospedar imagens .ico ( Novamente sem relação )
Dentre outros meios ( Como a comunidade front-end ) que também não souberam me informar uma ( Boa ) opção ...
Comment: Pergunta: por quê não hospedar o arquivo no próprio servidor?
Comment: o iconj.com pareceu funcionar em um teste preliminar que fiz
Comment: talvez relacionado: https://stackoverflow.com/questions/15497010/how-do-i-delete-tumblrs-default-favicon
Comment: Como no primeiro link que encontrei em minha pesquisa, é para um blog no tumblr.
Comment: Vlw, e o site que enviou no primeiro comentário não funciona, ele só converte a imagem para `.ico` e na segunda aba que deveria hospedar ele manda um link que redireciona pro favicon deles mesmos. ( O link to Stf ajudou ! )
Answer: Primeiro vou lhe indicar um serviço, todavia o motivo da resposta é explicar algo sobre os favicons que poderá lhe ser útil.
"Hospedagem" (Host) favicons
Pesquisando encontrei esta http://www.iconj.com/icon_generator.php, além de "hospedar" ele também converte sua imagem para ícone.
Ícones e Imagens como favicon
Navegadores antigos costumavam usar apenas .ico, isto quando suportado, pois existiam navegadores que nem suportavam, então a preferencia sempre foi usar este formato, no entanto a maioria dos navegadores modernos como pode ver na lista suportam png: http://caniuse.com/#feat=link-icon-png

Ou seja, o .ico não é mais a única opção, você pode hospedar em diferentes sites ou usar diferentes domínios para armazenar imagens .png e apontar elas no seu site:
<link rel="icon" type="image/png" href="http://3rd.site.com/img/favicon.png">

iOS Safari e os favicons
Você deve ter notado que os favicons não estão disponíveis no Safari para iOS, nem mesmo o formato .ico, no entanto o Safari tem uma tag link própria para ícones quando você salva nos favoritos ou para o "Home" e é compatível com muitas versões do Android, são as tags:

<link rel="apple-touch-icon" href="icone-grande.png"> quando adicionar aos favoritos ou adicionar ao Home (junto aos aplicativos)

<link rel="apple-touch-icon-precomposed" href="icone-grande.png"> o -precomposed faz com que o ícone não recebe o efeito de "gloss" no ícone.

As imagens devem ser PNG conforme a documentação, esses ícones ficam semelhante a isto (exemplo usando o site do Youtube) na Home (esquerda) e na hora de adicionar aos favoritos ou a "lista de leitura" (direita):

Nota: na verdade eu acho que reconhece sim <link rel="icon">, apesar do caniuse dizer que não, mas a imagem fica "feia", no entanto funciona (ao menos aonde testei) se não tiver o apple-touch-icon definido.
Comment: Muito bom, eu já tinha visto isso em Android e iOS, mas não tinha procurado as tags ( Pois esqueci ), vlw.

Favicon .ico vs hospedagem