Cronometro entre duas datas AngularJs

Question: Suponhamos que tenho duas datas:
2015-11-13T08:00:00 e 2015-11-13T10:00:00, como podem ver tem uma diferença de duas horas entre essas datas. Gostaria de colocar um cronometro em minha view que mostre essa diferença.
Tentei adaptar esse exemplo: http://codepen.io/garethdweaver/pen/eNpWBb/.
Porém quando o altero ele para de funcionar.
Como faço esse cronometro, ou então por onde começar?
Answer: Criei uma diretiva em Angular JS para isso:
 angular.module('iCountdown', [])
    .directive("iCountdown", function () {
        return {
            restrict: "EAC",
            scope: {
                setStartDate: "@",
                setEndDate: "@",
                expireMessage: "@",
                startMessage: "@",
                formatView: "@",
                setTemplateView: "@",
                consideredCurrentDate: "@",

            },
            replace: true,
            template: "

",
            link: function (scope, element) {
                var insertDate = function() {
                    scope.setMessageExpired(scope.expireMessage);
                    scope.setMessageInitial(scope.startMessage);
                   if (angular.isDefined(scope.setStartDate) && angular.isDefined(scope.setEndDate)) {
                       params.dateStart = scope.setStartDate;
                       params.dateEnd = scope.setEndDate;
                       if (angular.isDefined(scope.setTemplateView)) {
                           params.templateView =  scope.setTemplateView;
                           params.activeCurrentDate = scope.consideredCurrentDate;
                       }
                    }
                    scope.start();
                };

                scope.$watch('setDateEnd', function() {
                   insertDate();
                }, true);

                var _end = new Date();
                var _start = new Date();
                var _second = 1000;
                var _minute = _second * 60;
                var _hour = _minute * 60;
                var _day = _hour * 24;

                var params = {
                    second:_second,
                    minute:_minute,
                    hour: _hour,
                    day: _day,
                    interval: null,
                    messageFinal: 'expired!',
                    messageInitial: 'please whait...',
                    format:'Y-m-d H:i:s',
                    dateEnd: null,
                    dateStart: null,
                    currDate: null,
                    templateView: null,
                    activeCurrentDate:'false'
                };

                scope.getCurrentStartDate = function() {

                    var _dt = new Date();
                     var _current = [
                                 [_dt.getFullYear(),
                                  ((_dt.getMonth()+1) < 10 ? '0' + (_dt.getMonth()+1) : (_dt.getMonth()+1)),
                                  (_dt.getDate() < 10 ? '0' + _dt.getDate() : _dt.getDate())
                                 ].join('-'),
                                 [(_dt.getHours() < 10 ? '0' + _dt.getHours() : _dt.getHours()),
                                  (_dt.getMinutes() < 10 ? '0' + _dt.getMinutes() : _dt.getMinutes()),
                                  (_dt.getSeconds() < 10 ? '0' + _dt.getSeconds() : _dt.getSeconds())
                                 ].join(':')
                               ].join(' ');
                    return _current;

                }

                scope.setMessageExpired = function(message) {
                    params.messageFinal = message;
                };

                scope.setMessageInitial = function(message) {
                    params.messageInitial = message;
                };

                scope.setId = function(id) {
                    params.id = id;
                    scope.viewElement.setAttribute("id", id);
                };

                 scope.setDateStarter = function(strDate) {
                    params.protype.dateStart = strDate;
                };

                scope.setDateFinal = function(strDate) {
                   params.protype.dateEnd = strDate;
                };

               var createElementDate = function(strDate) {

                    var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
                    var dateArray = reggie.exec(strDate);
                    return new Date(
                        (+dateArray[1]),
                        (+dateArray[2])-1, // Careful, month starts at 0!
                        (+dateArray[3]),
                        (+dateArray[4]),
                        (+dateArray[5]),
                        (+dateArray[6])
                    );
                };

                scope.remaining = function() {
                    if (!params.currDate)
                    {
                       if (params.activeCurrentDate == 'true') {
                           params.dateStart = (createElementDate(scope.setStartDate).getTime() < createElementDate(scope.getCurrentStartDate()).getTime()) ? scope.getCurrentStartDate() : params.dateStart;
                       }
                        params.currDate = createElementDate(params.dateStart);
                    }

                    _start = params.currDate;
                    _end = createElementDate(params.dateEnd);

                    if (!(_end instanceof Date) || isNaN(_end.valueOf()) ) {
                        element[0].innerHTML = 'A data final não foi definida,' +
                            ' adicione uma data conforme o exemplo: yyyy-mm-dd hh:mm:ss!';
                         return;
                    }
                    if (!(_start instanceof Date) || isNaN(_start.valueOf()) ) {
                        element[0].innerHTML = 'A data inicial não foi definida,'+
                            ' adicione uma data conforme o exemplo: yyyy-mm-dd hh:mm:ss!';
                        return;
                    }

                     if (!params.currDate)
                    {
                        element[0].innerHTML = 'A data inicial é inválida!';
                        return;
                    }
                    params.currDate.setSeconds(params.currDate.getSeconds() + 1);

                    var distance = _end - _start;

                    if (distance < 0) {
                        clearInterval(params.interval);
                        element[0].innerHTML = params.messageFinal;
                        return;
                    }
                    var i=0;
                    var checkInterval = setInterval(function() {
                      if (createElementDate(scope.getCurrentStartDate()).getTime() < createElementDate(scope.setStartDate).getTime()) {
                      element[0].innerHTML = params.messageInitial;
                      return;
                      } else {
                         clearInterval(checkInterval);
                      }
                    },1);

                    var days = Math.floor(distance / params.day);
                    var hours = Math.floor((distance % params.day) / params.hour);
                    var minutes = Math.floor((distance % params.hour) / params.minute);
                    var seconds = Math.floor((distance % params.minute) / params.second);
                    var elementsTime = [];
                    elementsTime[0] =((days < 10) ? '0' : '') + days;
                    elementsTime[1] =((hours < 10) ? '0' : '') + hours;
                    elementsTime[2] =((minutes < 10) ? '0' : '') + minutes;
                    elementsTime[3] =((seconds < 10) ? '0' : '') + seconds;
                    element[0].innerHTML =  scope.setFormatViewTime(elementsTime);

                };

                scope.setFormatViewTime = function(elementsTime) {
                    var view = scope.formatView
                        .replace(/%d/gi, elementsTime[0])
                        .replace(/%h/gi, elementsTime[1])
                        .replace(/%i/gi, elementsTime[2])
                        .replace(/%s/gi, elementsTime[3]);

                    if(angular.isDefined(params.templateView) && params.templateView != null && params.templateView != "") {
                        return params.templateView.replace(/%t/gi, view);
                    } else {
                       return view;
                    }
                };

                scope.setFormatDate = function(format) {
                    params.format = format;
                };

                scope.start = function () {

                    if (!(_end instanceof Date) || isNaN(_end.valueOf()) ) {
                        element[0].innerHTML = 'A data final não foi definida, '+
                            'adicione uma data conforme o exemplo: yyyy-mm-dd hh:mm:ss!';
                         return;
                    }
                    if (!(_start instanceof Date) || isNaN(_start.valueOf()) ) {
                        element[0].innerHTML = 'A data inicial não foi definida, '+
                            'adicione uma data conforme o exemplo: yyyy-mm-dd hh:mm:ss!';
                        return;
                    }
                    if (_start > _end) {
                        element[0].innerHTML = 'A data inicial não pode ser maior que a data final!';
                        return;
                    }
                    params.interval = setInterval(this.remaining, params.second);

                };
            }
        };
    });

A diretiva no HTML:

Aqui o exemplo funcionando
Comment: Opa, analisando a diretiva creio que ela irá anteder minha necessidade. Porém só uma dúvida, como uso ela direto no controller passando as duas datas como parâmetro?
Comment: Deu certo, muito obrigado. Uma ultima dúvida, se eu quiser mudar a cor da mensagem de "fim" de jogo onde tenho que alterar?
Comment: cara, vc embute uma template. nessa template vc passa id class, etc...
http://jsfiddle.net/ivanferrer/1cyxoytv/48/ vc pode passar a mensagem como  html "fim do jogo".
Comment: A sim, entendi. Valeu :D
Answer: Instanciando new Date você pode ter um código mais limpo, como o que eu fiz:
No projeto que utilizei precisei somar o timezone também. O vm antes da variável é o controller var vm = this;
    vm.dataInicial = undefined;
    vm.cronometro = '00:00:00';

    vm.tick = function() {
        if(vm.dataInicial) {
            var dataAgora = Date.now();
            var timezone = new Date().getTimezoneOffset();

            vm.cronometro = new Date(new Date(dataAgora).getTime() - new Date(vm.dataInicial).getTime());
            vm.cronometro.setMinutes(vm.cronometro.getMinutes() + timezone);
        }
        $timeout(vm.tick, 1000);
    };

    $timeout(vm.tick, 1000);

Quando eu consulto um atendimento pendente e preciso da data inicial diferente de Date.now() eu faço a linha abaixo:
vm.dataInicial = new Date(parseInt(response.data.DataInicio.substr(6)));

No HTML ficou bem simples de chamar:

{{vm.cronometro | date: 'HH:mm:ss'}}

Cronometro entre duas datas AngularJs


Conjecture about prime numbers and fibonacci numbers

Question: I have done a few (not extensive) numerical tests that led me to this conjecture:
$$2m+1 \text{ is prime} \iff \exists n:\frac{F_{n}^{2m+1}+F_{n+1}^{2m+1}}{F_{n}+F_{n+1}} \text{ is prime}$$
where $m \ge 1$ and $n \gt 1$.
Therefore, according to the conjecture, if $2m+1$ is composite then $\frac{F_{n}^{2m+1}+F_{n+1}^{2m+1}}{F_{n}+F_{n+1}}$ is composite too for any $n \gt 1$. However, I can't see an easy application of known identities to prove this or the full conjecture.
Any idea?
UPDATE 1 (generalization)
This might not be related to Fibonacci numbers, because it seems to work also with e.g. $\frac{(2n+1)^{2m+1}+(3n+1)^{2m+1}}{5n+2}$ so there might be a generalization. The generalization could be: ${2m+1} \space \text{is prime} \space \iff \exists a,b \space\text{coprime} \space : \frac{a^{2m+1}+b^{2m+1}}{a+b} \space\text {is prime}$.
UPDATE 2 (bound for $n$)
Maybe the conjecture could be simplified with an upper bound for $n$, although I don't have any idea which bound could be good.
UPDATE 3 (easier direction proved)
If $2m+1=uv$, $u,v \gt 1$, then $\frac{a^{uv}+b^{uv}}{a+b}=\frac{a^{uv}+b^{uv}}{a^u+b^u}\frac{a^{u}+b^{u}}{a+b}$, where both fractions on the RHS are integers greater than $1$, therefore $\frac{a^{uv}+b^{uv}}{a+b}$ cannot be prime.
UPDATE 4
The more difficult direction will probably remain a conjecture, since there already exist conjectures of this kind e.g.:
$n \space \text{is prime} \implies \exists b: \frac{b^n+1}{b+1} \space \text{is prime}$
(see OEIS A103795).
Comment: Very interesting problem. If the conjecture is correct, I hope to see a full proof of it in the future.
Comment: I have not found the necessary prime for $m=26$ yet.
Comment: Wanted to add that we have a very nice (general) formula:
$$\frac{a^{2m+1}+b^{2m+1}}{a+b} = a^{2m}+b^{2m}-ab(a^{2m-2}+b^{2m-2})+a^2b^2(a^{2m-4}+b^{2m-4})-\dots (-1)^ma^mb^m$$
This can be proven by induction. This also answers your first question @Peter.
Comment: @Peter yes, the fraction is always a positive integer: $a^q+b^q = (a+b)(a^{q-1}-a^{q-2}b+a^{q-3}b^2-\cdots+b^{q-1})$ for $q$ odd. Regarding the infinite many $n$ yes, it might be very difficult to prove.
Comment: @Peter I think there are some primes which are "more difficult", even using generic coprimes $a,b$, for example $29,41,53$ seem to need bigger $a,b$.
Comment: Your left side depends only on $m$ but your right side depends only on $n$ ($m$ is "bound").
Comment: @aschepler now it is has been edited and fixed.
Comment: Maybe a consequence of Dirichlet's thm?
Comment: Is the fraction always a positive integer ?
Comment: Also , where can we stop ? We have infinite many $n$'s to check if no $n$ does the job.
Comment: I am not sure about the statement of this proof. For the prime numbers statement you used the $\exists$ (exists) symbol for $n$ but when talking about composite numbers you say for any $n>1$. Also as @Peter pointed out where can we stop?
Comment: @Ahsan Yousaf $\exists n \gt 1:\frac{F_{n}^{2m+1}+F_{n+1}^{2m+1}}{F_{n}+F_{n+1}} \text{ is prime} \implies 2m+1 \text{ is prime}$ is equivalent to $2m+1 \text{ is composite} \implies \forall n \gt 1:\frac{F_{n}^{2m+1}+F_{n+1}^{2m+1}}{F_{n}+F_{n+1}} \text{ is composite}$. Regarding when we can stop see "UPDATE 2" in the question.
Answer: I wrote one Mathematica code
<code>satisfiedLHSm = (Array[Prime, 100] - 1)/2   //
  Select[#, IntegerQ] &
f[m_, n_] :=
  PrimeQ[(Fibonacci[n]^(2 m + 1) +
      Fibonacci[n + 1]^(2 m + 1))/(Fibonacci[n] + Fibonacci[n + 1]) ];
satisfiedRHSm =
 Flatten[Table[{m, n}, {m, 1, 23, 1}, {n, 200}], 1] //
    Select[#, f @@ # &] & // Map[#[[1]] &, #] & // Union
</code>
satisfiedLHSm looks like
$$
\{1, 2, 3, 5, 6, 8, 9, 11, 14, 15, 18, 20, 21, 23 \cdots\}
$$
satisfiedRHSm looks like
$$
\{1, 2, 3, 5, 6, 8, 9, 11, 14, 15, 18, 20, 21, 23 \cdots \}
$$
Looks like the conjecture is correct, ... at least for small $m$.


How can i set different language for 2 different domain?

Question: How can i set different language for 2 different domain?
I have 2 different domain for single drupal installation
www.example.en
www.example.fr
i want to display 2 different language based on the user coming from any domain?
Answer:
Go to http://example.com/admin/config/regional/language/configure
Enable URL
Save
Go to Configure
Select Domain

Keep configuring it all.
Comment: I have tried that, but language not switching based on that.


Renomear os níveis de um fator baseado em um data frame

Question: Suponha que eu tenha o data frame iris, presente na memória do R:
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Suponha também que eu possua também um data frame chamado flores, com a seguinte estrutura:
flores <- data.frame(Especies=c("setosa", "virginica", "versicolor"),
                     Nome=c("Flor 1", "Flor 2", "Flor 3"))
    Especies   Nome
1     setosa Flor 1
2  virginica Flor 2
3 versicolor Flor 3

Eu gostaria de substituir os ocorrências de iris$Species pelas de flores$Nome. Ou seja, eu gostaria que cada ocorrência de setosa em iris$Species fosse substituída por Flor 1; cada ocorrência de virginica em iris$Species fosse substituída por Flor 2; e cada ocorrência de versicolor em iris$Species fosse substituída por Flor 3.
Utilizar algo como if ou ifelse está fora de questão, pois o conjunto de dados com o qual estou trabalhando possui milhares de ocorrências de espécies diferentes. Seria impossível digitar todas as opções com as quais eu tenho que trabalhar.
Answer: Creio que o código seguinte resolve a questão.
No entanto, tive uns problemas com as colunas envolvidas, porque são de classe factor. Em primeiro lugar, inclui o argumento stringsAsFactors na criação da data frame flores. E de seguida transformei a coluna Species em character.
flores <- data.frame(Especies=c("setosa", "virginica", "versicolor"),
                     Nome=c("Flor 1", "Flor 2", "Flor 3"),
                     stringsAsFactors = FALSE)

iris$Species <- as.character(iris$Species)

for(s in unique(iris$Species)){
    iris$Species[iris$Species == s] <- flores$Nome[flores$Especie == s]
}

iris$Species <- factor(iris$Species)    # voltar a factor

Se a coluna Nome de flores tiver que ser factor então deverá usar
iris$Species[inx] <- as.character(flores$Nome[flores$Especie == s])

dentro do ciclo for.
Answer: Eu faria um left_join e em seguida apagaria a variável. Por exemplo:
> library(dplyr)
> flores <- data.frame(Especies=c("setosa", "virginica", "versicolor"),
+                      Nome=c("Flor 1", "Flor 2", "Flor 3"))
>
> iris <- left_join(iris, flores, by = c("Species" = "Especies")) %>%
+   select(-Species) %>%
+   rename(Species = Nome)
>
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  Flor 1
2          4.9         3.0          1.4         0.2  Flor 1
3          4.7         3.2          1.3         0.2  Flor 1
4          4.6         3.1          1.5         0.2  Flor 1
5          5.0         3.6          1.4         0.2  Flor 1
6          5.4         3.9          1.7         0.4  Flor 1

Usar case_when também poderia ser uma opção, mas não se você já tiver esse data.frame de nomes.
Em tempo, existe a função fct_recode do pacote forcats:


Eigevectors of an Idempotent Matrix: A^2 = A [Strang P310 6.2.25]

Question: Source: P4 of http://www.minho-kim.com/courses/11sp71007/data/hw05-solution.pdf

$\Large{{1.}}$ I perceive : Because $A\mathbf{a_i = 1a_i}$ for all $1 \le i \le n$,
thus $1$ is an eigenvalue of $A$
and $\mathbf{a_i}$ are eigenvectors of $A$ for all $1 \le i \le n$.
Yet how does this imply the green:
 $E_1 = \text{ eigenspace corresponding to the eigenvalue } 1 = \operatorname{span}(\mathbf{a_1}, \cdots, \mathbf{a_n})$ ?
Since $A = \begin{bmatrix}
    \mathbf{a_1} & \cdots & \mathbf{a_n} \\
    \end{bmatrix}$ where $\mathbf{a_i}$ is a column vector,
I apprehend that $\operatorname{span}(\mathbf{a_1}, \cdots, \mathbf{a_n}) = colspace(A)$.
$\Large{{2.}}$ What's the intuition? Does the geometric interpretation of eigenvectors figure here?
Comment: 1) Think about the possible eigenvalues of the matrix $A$. 2) A linear transformation that has the property $A^2 = A$ is called a "projection."
Answer: By symmetry between $0$ and $1$, there is a second error in the question: not only should $A=I$ be excluded, but also (for part b) it should have excluded $A=0$, since then $1$ is not en eigenvalue (can you spot the error in the "proof" that $1$ is an eigenvalue?).
The fact that the span of the columns (which is the image of the linear map defined by the matrix) must be all of the eigenspace for$~\lambda=1$ is simply because every eigenvector for $1$ is obviously in the image of the linear map (as it is its own image).
As for intuition, there is not much more to offer than that eigenspaces for different eigenvalues (here $0$ and $1$) are always in a direct sum, and that by rank-nullity the sum fills up the whole space here. This proof is not the most insightful one possible for $A^2=A$ implies $A$ diagonalisable. (But Strang wants to push null and column spaces wherever he can.)
Answer: Suppose $A^2=A$.
Then $(I-A)^2 = (I-A)$, and
$x = Ax+(I-A)x$ for all $x$.
In other words, $\mathbb{F}^n = {\cal R} A + {\cal R}(I-A)$.
It is straightforward to verify that ${\cal R}(I-A) = \ker A$ and
$\ker A \cap {\cal R} A = \{0\}$.
Let $v_1,...,v_k$ be a basis for $\ker A$, and $v_{k+1},...,v_n$ be a
basis for ${\cal R} A$. Then $v_1,...,v_n$ is a basis for $\mathbb{F}^n$.
(Note: It is possible that $\ker A = \{0\}$, or $\ker A = \mathbb{F}^n$, in which case one or other basis is empty. This will result in $A$ being the identity or zero operator, respectively.)
We have $Av_i = 0$ for $i=0,...,k$ and $A v_i = v_i$ for $i=k+1,..,n$, and so $A$ is diagonal in this basis, and the diagonal entries are either zero or one.


Obtaining an estimate for the Lagrangian $L=H^*$ from the Hamiltonian $H$

Question: This is from C. Evans' PDE book, page 130. The convex function $H:\mathbb{R}^n\to\mathbb{R}$ is $C^2$ and satisfies $$ H\big(\frac{p_1+p_2}{2}\big) \leq \frac{1}{2}H(p_1) + \frac{1}{2}H(p_2) - \frac{\theta}{8}|p_1-p_2|^2. $$ The lagrangian $L$ is defined as the Legendre transform of $H$: $$ L(v)=(H^*)(v)=\max_{p\in\mathbb{R}^n}p\cdot v - H (p). $$  It's a fact that the statements $p\cdot v = L(v) + H(p), $ $ p=DL(v), $ $v=DH(p)$ are equivalent.
One must show that from the above estimate it follows that $$ \frac{1}{2}L(v_1)+\frac{1}{2}L(v_2)\leq L\big(\frac{v_1+v_2}{2}\big) + \frac{1}{8\theta}|v_1-v_2|^2.$$ I haven't been able to show this. Below is a screenshot of the book's page.
Thank you.
Comment: If one applies the Legendre transformation to $(36)$, one arrives closer to $(37)$. Alas I have no idea yet how to handle $\lVert p_1 - p_2\rVert^2$.
Comment: @epimorphic using $v_1$ and $v_2$ such that $L(v_j)=p_j\cdot v_j - H(p_j), j=1,2.$
Comment: I would have expected $L(v_i)$ in equation $(37)$ of the book.
Comment: @mvw newer editions have $v_1, v_2$ instead of $q_1, q_2.$
Comment: Isn't it straightforward to show that the hessian $ L_{v_i,v_j} = H_{p_i,p_j}^{-1} $? So the lower bound on the norm of $ H_{p_i,p_j} $ becomes an upper bound on the norm of $ L_{v_i,v_j} $ from which the convexity follows.
Comment: @user226970 I see how that works out now, thanks. I saw a hint in some notes that points to another way of doing it so I'll hold out to see if anyone comes up with an alternative.
Comment: What was the hint?
Answer: As your hint says, for every $q_1, q_2 \in \mathbb R^n$ there exist $p_1, p_2 \in \mathbb R^n$ such that $L(q_j) = p_j \cdot q_j - H(p_j)$ for $j \in \{1,2\}$. Combining with the inequality for $H$,
\begin{align}
\frac{1}{2} L(q_1) + \frac{1}{2} L(q_2)
&= \frac{p_1 \cdot q_1 + p_2 \cdot q_2}{2} - \frac{1}{2} H(p_1) - \frac{1}{2} H(p_2) \\
&\leq \frac{p_1 \cdot q_1 + p_2 \cdot q_2}{2} - H\left(\frac{p_1+p_2}{2}\right) - \frac{\theta}{8} \lvert p_1 - p_2\rvert^2.
\end{align}
Note that
\begin{align}
\frac{p_1 \cdot q_1 + p_2 \cdot q_2}{2} - H\left(\frac{p_1+p_2}{2}\right)
&= \frac{p_1 - p_2}{2} \cdot \frac{q_1 - q_2}{2} + \frac{p_1 + p_2}{2} \cdot \frac{q_1 + q_2}{2} - H\left(\frac{p_1+p_2}{2}\right) \\
&\leq \frac{p_1 - p_2}{2} \cdot \frac{q_1 - q_2}{2} + \max_{p \in \mathbb R^n} \left(p \cdot \frac{q_1 + q_2}{2} - H(p)\right) \\
&= \frac{p_1 - p_2}{2} \cdot \frac{q_1 - q_2}{2} + L\left(\frac{q_1 + q_2}{2}\right),
\end{align}
which means
$$
\frac{1}{2} L(q_1) + \frac{1}{2} L(q_2)
\leq L\left(\frac{q_1 + q_2}{2}\right) - \frac{\theta \lvert p_1 - p_2\rvert^2 - 2(p_1 - p_2) \cdot (q_1 - q_2)}{8}.
$$
The desired inequality for $L$ is now immediate from the fact that
$$
\left\lvert \sqrt\theta (p_1 - p_2) - \frac{q_1 - q_2}{\sqrt\theta}\right\rvert^2
\geq 0.
$$
Comment: Wonderful, thanks.
Comment: @Weltschmerz Apart from the sign error, that is :P


GWT CellTable Cells readOnly/disabled/non-editable

Question: I want to make that some cells of the rows can be non-editable.
by now my solution is when i create the columns, if one is readOnly, y make a TextCell, if not, i go with the default Cell wich can be EditTextCell,DatePickerCell,etc.
The problem with this is that i can't make some rows readOnly and others not. Or they are ALL the fields readOnly or they are not.
How can i do to make this for example
TABLE:
Data1       |     Data2         | Data3
--------------------------------------
readOnly  | non-readOnly  | readOnly
readOnly  | readOnly      | non-readOnly
when i mean "readOnly" it can be "enabled" or make it a "TextCell"
                    celda = new TextInputCell();
                    Column<ObjetoDato, String> columna = new Column<ObjetoDato, String>(celda) {
                        @Override
                        public String getValue(ObjetoDato object) {
                                if(actual.getValorDefault()!=null && object.getValor(actual.getNombreCampo()).isEmpty()){
                                    object.setValor(actual.getNombreCampo(), actual.getValorDefault());
                                    return actual.getValorDefault();
                                }

                                return object.getValor(actual.getNombreCampo());
                        }
                    };
                    tabla.agregarColumna(columna, actual.getCaption());
                    columna.setFieldUpdater(new FieldUpdater<ObjetoDato, String>() {
                              @Override
                            public void update(int index, ObjetoDato object, String value) {
                                object.setValor(actual.getNombreCampo(), value);
                                new Scripter(object,actual.getComportamiento(),true);
                                tabla.actualizar();
                                Sistema.get().getIG().actualizarTotales();
                              }
                    });

I tried creating my cutom cell already and replacing the TextImputCell, but the methods never trigger
celda = new FabriCel();

and
public class FabriCel extends TextInputCell {
private String campo;

public FabriCel(String campo){
    this.campo=campo;
}
 @Override
 public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater){
     Boolean editable = false;///get it from your model

     if(editable != null && !editable){
         event.preventDefault();
     }else{
         super.onBrowserEvent(context, parent, value, event, valueUpdater);
     }
 }

Also this
@Override
public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) {
    Boolean editable = false;///get it from your model
    if(editable){
        Log.log();
        sb.appendHtmlConstant("
"  +value+"
");
    }else{
        Log.log("No entra");
        super.render(context, value, sb);
    }

}

Thanks!
Answer: You have to create one custom cell. In that, you have tell runtime like it should be readonly or no-readonly. just example.
        private class CustomCell extends EditTextCell {
            public void render(com.google.gwt.cell.client.Cell.Context context,
            String value, SafeHtmlBuilder sb) {
            Data data=context.getKey();
            if(data.isReadOnly()){

            sb.appendHtmlConstant("
"  +value+"
");
                        }else{
                            super.render(context, value, sb);

                        }

                }
            }

In given bean, there is some condition which says readonly or no-readonly.
And create column  like
Column<Data, String> nameColumn = new Column<Data, String>(new CustomCell()) {

        @Override
        public String getValue(Data object) {
            return object.getName();

        }
    };

Comment: As I given answer you have to create custom cell. and instead of put direct instance of `EditTextCell`, you have to add custom cell.can you put some code?
Comment: If I am not wrong then as I post code your requirement match with it. why are you using `TextInputCell` instead of `EditTextCell`? that I do not understand. when do you want to call `onBrowserEvent` / `render` ? run in debug mode and check with debug point!!
Comment: I finally make it work! helped by https://developers.google.com/web-toolkit/doc/latest/DevGuideUiCustomCells and you i make it happen.
Answer: A way to do this is to override the onBrowserEvent event of your Editable Cells and consume the event if the cell is not editable.
            final EditTextCell cell = new EditTextCell(renderer)
            {
                @Override
                public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater)
                {
                    Boolean editable = false;///get it from your model

                    if(editable != null && !editable)
                    {
                        event.preventDefault();
                    }
                    else
                    {
                        super.onBrowserEvent(context, parent, value, event, valueUpdater);
                    }
                }
}

Comment: I don't understand how to change the cell in runtime. I can't get onBrowserEvent to trigger. I'm nos using DOm elements also...
Comment: If you start typing on the cell the events will go on the onBrowserEvent. Anyway you have mixed the 2 answers.
Answer: I had the same need; and tested out various combinations of overriding render, isEditing, resetFocus, and edit on EditTextCell (I didn't try the onBrowserEvent solution).
When I only overrode render (to show an HTML value if non-editable); I got errors resetting focus (as discussed here). This continued even if I overrode resetFocus. When I only override isEditing, the cell would flash to editing when clicked, and then flash back. What worked perfectly was overriding edit. I triggered based on adding a tag to the value passed in by Column.getValue, you can trigger however you like, but it turned out to be as simple as:
private static class LockableEditTextCell extends EditTextCell {
    @Override
    protected void edit(Context context, Element parent, java.lang.String value) {
      if (!value.startsWith(LOCKED_CELL_VALUE)) {
        super.edit(context, parent, value);
      }
    }
  }


How to extract Json data into pandas df?

Question: Trying to extract the news title from this page. The data shown on screen looks like json format. Each nodeid is a news entry. However, the following codes do not work:
import pandas as pd
urlco = "https://www.mpfinance.com/fin/getlisting.php?block=daily&startissue=20200118&fixiss=1"

print(urlco)
dfA = pd.read_json(urlco)
print(dfA)

Answer: The issue here is that the json you're trying to load isn't in the correct format for an automatic pandas load. Some light manipulation yields the desired results.
The following code should work:
import pandas as pd
import json, urllib

url = "https://www.mpfinance.com/fin/getlisting.php?block=daily&startissue=20200118&fixiss=1"

response = urllib.request.urlopen(url)
data = json.loads(response.read())

df = pd.DataFrame.from_records(data.get('listing'))

# print(df.head(2))
    nodeid  docissue    docsection  sectionname     docparent   parentname  ordertext   heading1    heading2    alt     summary     time    time2   pubdate     pubdate2    link    tag     author  imprate     realnativeads   bimage  video   videoplayer
0   1579286154686   20200118    S00002  財經  S00001  報章內容    eaa1    中國出生率70年最低 失人口紅利 勞動人口連降8年 人均收入增速低過GDP       中國出生率70年最低 失人口紅利 勞動人口連降8年 人均收入增速低過GDP   【明報專訊】國家統計局昨日公布2019年主要經濟數據,全年GDP增速6.1%,守住6%至6.5%的官方目標區間,GDP總...     2020-01-18 04:30:00         2020年1月18日  2020-1-18   ../fin/daily2.php?node=1579286154686&issue=20200118     經濟;             False   https://fs.mingpao.com/fin/20200118/s00002/0fe56067030fcabe89cf843bc312b479.jpg
1   1579286155903   20200118    S00002  財經  S00001  報章內容    eaa2    去年GDP增6.1% 第4季保六靠投資         去年GDP增6.1% 第4季保六靠投資     【明報專訊】國家統計局昨日公布2019年中國經濟數據,去年第四季GDP增速6%,與第三季持平,全年GDP則增長6.1%,...     2020-01-18 04:30:00         2020年1月18日  2020-1-18   ../fin/daily2.php?node=1579286155903&issue=20200118     經濟;             False   https://fs.mingpao.com/fin/20200118/s00002/0fe58f80b880233386a37a7fb11ea929.jpg     ```

Answer: you can try this:
import json
import pandas as pd
from urllib.request import urlopen
urlco = "https://www.mpfinance.com/fin/getlisting.php?block=daily&startissue=20200118&fixiss=1"
response = urlopen(urlco)
response = response.read().decode('utf-8-sig')
result = json.loads(response)
df = pd.DataFrame(result['listing'])
print(df.head())

          nodeid  docissue docsection sectionname docparent parentname  \
0  1579286154686  20200118     S00002          財經    S00001       報章內容
1  1579286155903  20200118     S00002          財經    S00001       報章內容
2  1579286156356  20200118     S00002          財經    S00001       報章內容
3  1579286156402  20200118     S00002          財經    S00001       報章內容
4  1579286156808  20200118     S00002          財經    S00001       報章內容

  ordertext                               heading1 heading2  \
0      eaa1  中國出生率70年最低 失人口紅利 勞動人口連降8年 人均收入增速低過GDP
1      eaa2                    去年GDP增6.1% 第4季保六靠投資
2      eaa3                   人行全周淨投放9000億 創單周歷史新高
3      eab1                    去年港銀貸款增6.7% 料今年息差受壓
4      eab2                         招行業績快報 去年多賺15%

                                     alt  ...     pubdate   pubdate2  \
0  中國出生率70年最低 失人口紅利 勞動人口連降8年 人均收入增速低過GDP  ...  2020年1月18日  2020-1-18
1                    去年GDP增6.1% 第4季保六靠投資  ...  2020年1月18日  2020-1-18
2                   人行全周淨投放9000億 創單周歷史新高  ...  2020年1月18日  2020-1-18
3                    去年港銀貸款增6.7% 料今年息差受壓  ...  2020年1月18日  2020-1-18
4                         招行業績快報 去年多賺15%  ...  2020年1月18日  2020-1-18

                                                link  tag author imprate  \
0  ../fin/daily2.php?node=1579286154686&issue=202...  經濟;
1  ../fin/daily2.php?node=1579286155903&issue=202...  經濟;
2  ../fin/daily2.php?node=1579286156356&issue=202...  經濟;
3  ../fin/daily2.php?node=1579286156402&issue=202...  經濟;
4  ../fin/daily2.php?node=1579286156808&issue=202...  經濟;

  realnativeads                                             bimage video  \
0         False  https://fs.mingpao.com/fin/20200118/s00002/0fe...
1         False  https://fs.mingpao.com/fin/20200118/s00002/0fe...
2         False
3         False  https://fs.mingpao.com/fin/20200118/s00002/0fe...
4         False

   videoplayer
0
1
2
3
4

[5 rows x 23 columns]


Python: import requests gets a lot errors MacOS

Question: New to programming and followed this course: https://www.youtube.com/watch?v=4F2m91eKmts&feature=emb_logo
When things went to Webscraping, got errors:
Code says:
import requests
from bs4 import BeautifulSoup
page = requests.get('https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999')

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.find_all('a'))

Return is:

File "/Users/.../python/cleverprogrammer/webscraping.py", line 1, in

      import requests   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/init.py",
  line 112, in
      from . import utils   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/utils.py",
  line 26, in
      from ._internal_utils import to_native_string   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/_internal_utils.py",
  line 11, in
      from .compat import is_py2, builtin_str, str   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/compat.py",
  line 59, in
      from http import cookiejar as cookielib   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/cookiejar.py",
  line 39, in
      from calendar import timegm ImportError: cannot import name 'timegm' from 'calendar'
  (/Users/.../python/cleverprogrammer/calendar.py)

Is there some problem with the way Requests are installed? Maybe use of pipenv is not the correct way?
And why does it call for calendar.py file and 'timegm'? Calendar.py is different file from the same course, in same folder.
What are the steps, that I can take, to get rid of these messages and get working Requests?
Thanks in advance.
Comment: Looks like you have your own local file named `calendar.py` that is interfering with the standard Python module of the same name.  Rename your file, or adjust your `PYTHONPATH` so that the local version of `calendar.py` isn't on it.
Comment: Damn, that was easy. Changed calendar.py name and code works. And I already thought that i messed up my Mac. :) thanks a lot.
Comment: The message tells you which file is used: `(/Users/.../python/cleverprogrammer/calendar.py)`
Comment: Are you not using virtual environments?
Comment: No. I am familiar with concept of venv, but haven't yet learned how to do apply them to my work. I'll need to figure out, how to set my vscode built in terminal to use that venv for every project. From your point of view, is it ok not to work in venv while learning or you should always use them?
Comment: Always use a virtual environment. Quick-and-dirty instructions I wrote up can be found at https://snarky.ca/a-quick-and-dirty-guide-on-how-to-install-packages-for-python/.
Answer: I am not getting any errors when trying out your code. It looks infallible. I suggest that you check what module of python you are working with, and consider updating to python 3.0+ if possible.
Try this
import calendar
print calendar.__file__

It will show you the module it's lodaing.
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/calendar.pyc

Comment: More of a comment than an answer, but a great suggestion.


django vs jsp for production scale applications

Question: I have done large scale production grade web application using JSP, understand the difficulties of jvm tuning, web containers and how to scale content (static and dynamic). In the recent years there is not much development in JSP with the exception of JSTL and I am not sure whether this will change in near future; I am considering Django as an alternative to host production grade, high scaling application.
Considering my java/JSP experience what are the pros and cons i should be aware of when it comes to DJango particularly when it comes to scaling and performance
Answer: Django itself is framework based on python. If you are about to use it in production then it is fine. Similar way JSP stands for JAVA server pages it is used with java related frameworks. i.e MVC architecture, servlets, etc.
Now moving to your question, Both technologies are highly scalable and used for robust solution. The main difference is language, readability and speed of execution.
Below are some differences between both technologies

Django is based on python which is scripting language/ interpreted language so code is interpreted which is quite slower than compiled language. Code is written in python which provides high readability. But when it comes to scalability it is highly scalable.
JSP/ Servlet is based on java which is compiled language. So the code is compiled which gives bonus of faster execution. JSP/ Servlet architecture is also highly scalable but the coin side is readability. But it is also used for building scalable enterprise applications.

To conclude, both technologies are highly scalable and efficient to make robust applications.


Adding a field without the field_ prefix (Drupal 7)

Question: I am using the organic groups module which adds a field with machine name: group_audience to the user entity which can be seen at:
<code>/config/people/accounts/fields
</code>
Somehow after install some other modules, this field disappeared.  I would like to add it back the field's machine name was simply group_audience instead of field_group_audience.
When I try and create a new field with the Drupal 7 interface builder it always prepends field_ to any field that is create.  How can I create a field that does not have the field_ prefix?
Answer: The Organic Groups module has a nifty API method for this. You just need to do a:
<code>og_create_field(OG_AUDIENCE_FIELD, 'user', 'user');
</code>
This first checks if the field exists and creates it if it doesn't, then checks if an instance of the field has been attached to the user entity and creates it if it doesn't.
You can check this answer out to understand where and how you can run this snippet from.
Answer: You can add fields without prefixes  with drush field-create command or by using Remove field name prefix module.


Continue to receive new events for completed REQUEST_STREAM in rsocket

Question: Given an Rsocket endpoint (Spring)
    @MessageMapping("chat.{chatId}")
    Flux<Message> getChats(@DestinationVariable String chatId) {
        Mono<Chat> data = chatRepository.findById(chatId);
        return data.map(chatGroup -> chatGroup.getMessages())
                .flatMapMany(Flux::fromIterable);
    }

   public interface ChatRepository extends FirestoreReactiveRepository<Chat> {

   }

and a client connecting to it via websocket: JS (Rsocket 1.x)
const makeConnector = () => {
      return new RSocketConnector({
        setup: {
          dataMimeType: 'application/json',
          keepAlive: 100000,
          lifetime: 100000,
          metadataMimeType: 'message/x.rsocket.routing.v0',
        },
        transport: new WebsocketClientTransport({
          url: 'ws://localhost:7000/rsocket',
        }),
      });
};

client()
  .connect()
  .then((socket) => {
    const requester = socket.requestStream(
      {
        data: undefined,
        metadata: Buffer.concat([
          Buffer.from(String.fromCharCode('chat.chatId'.length)),
          Buffer.from('chat.chatId'),
        ]),
      },
      10,
      {
        onError: (e) => console.log('error getting data', e),
        onNext: (payload, isComplete) => {
          const parsedData: Chat = JSON.parse(payload.data.toString());
          requester.request(5); // request the next 5 chats
        },
        onComplete: () => {
          console.log('complete');
        },
        onExtension: () => {
          console.log('on extension');
        },
      }
    );
  });

When the requestStream data is completed. (ie. complete is printed in console)
Then the new events are no longer received after complete. Is it possible to listen to new events if a stream is completed?
I went around this using an intervals, but this introduce new issues such as duplicate chats being received. I can filter it on the frontend side, but there must be a better way to do this
return Flux.interval(Duration.ofSeconds(5)).flatMap(x -> {
   return chatService.findChats(matchId);
});

Comment: Your current backend code takes a snapshot of received messages at a given time, and send it back. If you require a livestream of messages, then you should change your strategy, and not get messages back from the database. You need a "change feed" or a message queue or a  hot flux somewhere, from which you can poll messages to send them back. But without more details about your backend app (how messages are received and treated), it is difficult to provide a right answer.
Comment: @amanin thank you. I used `FirestoreReactiveRepository` (https://googlecloudplatform.github.io/spring-cloud-gcp/reference/html/index.html#reactive-repositories) to query the database

It is not possible to listen to active events with this approach. To listen to updates a listener needs to be registered via native `onSnapshot` (https://firebase.google.com/docs/firestore/query-data/listen#java) or adding a listener into the `Firestore` provided spring bean
Answer: RSocket-JS does not provide by default any "re-subscription" mechanism when a connection is closed : Meaning when your connection is closed or completed, you can not receive events on this connection anymore.
In RSocket, when the WebSocket connection status is 'CLOSED' or 'ERROR', the subscription is cancelled. Meaning you can't receive any new events anymore.
You can see it in their RSocketClient.js, line 91 : https://github.com/rsocket/rsocket-js/blob/master/packages/rsocket-core/src/RSocketClient.js
If you would like to continue receiving new events after your current connection was closed, you need to create another one.
To do it, you can inspire you from the example provided by RSocket here : https://github.com/rsocket/rsocket-js/blob/master/packages/rsocket-examples/src/ReconnectExample.js
Personally, I used it in the current project I'm working on, but I re-worked it a bit, in order to add a few additional things :

A maximum number of retry, in order to still kill the connection in case of a big issue.
An exponential time interval before each retry, including some randomness to avoid all WebSocket clients to reconnect at the same time (and avoid a flooding of requests at server side).

You can find the complete implementation I did here : https://github.com/icure-io/icure-medical-device-js-sdk/blob/master/src/utils/rsocket.ts


Question regarding a proof for a subspace problem in Lang

Question: $Statement\;of\;the\;Problem:$ Determine the dimension of the subspace of ${\mathbf{R^4}}$ consisting of all $X\in\mathbf{R^4}$ such that: $$x_1+2x_2=0 \;\;and\;\; x_3-15x_4=0$$
$My\;Question:$ Let $V=\mathbf{R^4}$ and $W=\mathbf{R^2}$. Let $L:V\rightarrow W$ be the mapping defined by $L(X)=(x_1+2x_2,x_3-15x_4)$ where $X=(x_1,x_2,x_3,x_4)$ is in $V$. I managed to prove that the answer to the problem is 2 by proving that $L$ is surjective (onto) and therefore has a dimension of 2, which in turn gives the kernel a dimension of two though. Originally, before I could get to that proof though, I tried to see about a case by case basis for what each possible value of $dim\;Im\;L$ could be and then try to prove that it was two (the list of possible values being 0,1,2). However, when I tried to do proof by contradiction, I ran into a soft wall. $\mathbf{Issue\;1)}$ As for the case where $dim\;Im\;L=0$, I couldn't find out a way to say that this couldn't be true as that would mean the kernel of $L$ is all of $V$ which is just obviously not true by inspection. $\mathbf{Issue\;2)}$ As for $dim\;Im\;L=1$, I could never really get a proof that worked to disprove this case.
As for Issue 1, is it strong enough to just say that $dim\;Im\;L\neq0$ by inspection, or do I need to look for a more formal way to say this to be stronger? As for Issue 2, anyone got any ideas how to disprove $dim\;Im\;L=1$
[Note: If anyone wants to see I've done a proof that contains the fact that $L$ is surjective, I'll be happy to provide that as well to prove that I've already solved the problem]
Comment: A proof by contradiction is not the best choice. Instead, just find a basis (i.e., find two vectors in $\mathbb{R}^4$ which are linearly independent and span the space of solutions to the given system of equations). Your other proof strategy (using image and kernel) is fine.
Comment: @quasi : Ok, not something I considered before (pause for me to bang head on wall in shame...). But to ask, that would assume that you know that it's only two vectors that you need to look for in the first place. How do you prove that it's only two vectors that you need to look for? Playing Devil's Advocate and forgetting obvious intuitive factors that lead to 2 as an obvious first choice (e.g. the fact that the coordinates can be solved in terms of each other to give two independent degrees of freedom), what would be the argument that says that one vector couldn't generate the subspace?
Comment: The variables $x_2$ and $x_4$ are _free_. You can choose them arbitrarily. Once chosen, $x_1$ and $x_3$ are determined. Exactly two degrees of freedom.
Comment: And then find a basis that makes that intuition rigorous.
Answer: Hint:
Show that the vectors
$$u = (-2,1,0,0)$$
$$v = (0,0,15,1)$$
are in the solution set of the system, are linearly independent, and their span is the set of all solutions.
Comment: It's more like this: If you assume one nonzero vector, $w$ say, generates the space, then both $u$ and $v$ would have to be in $\langle{w}\rangle$ (the span of $\{w\}$). But that means $u,v$ would be parallel to $w$, hence parallel to each other, which is clearly not the case. Alternatively, given that you've verified that $u,v$ are linearly independent, the invariance of dimension principle guarantees that the span of the set $\{u,v\}$ can't be generated by one element.
Comment: Ok. I think I get it now. Even if you were to assume 1 vector did span the space, that can always be decomposed into two linearly independent vectors, each dictated by one coordinate. So you still get a dimension of two. Thank you very much.
Comment: I like that too. :) Elegant.


Sum of bounded in probability random variables

Question: I'm self-studying probabilistic order notation, and I wanted to show some properties to get used to it. But now I'm having trouble showing that the sum of two random variables that are bounded in probability is bounded in probability (also known as tight, or $O_p(1)$).
Let $X_n = O_p(1)$ and $Y_n = O_p(1)$, then for any $\epsilon > 0$, there exists $M$ such that $\sup_n P(|X_n| > M) < \epsilon/2$ and $\sup_n  P(|Y_n| > M) < \epsilon/2$. Now I'd like to show that $\sup_n P(|X_n + Y_n| > M) < \epsilon$, but I haven't succeeded so far. I couldn't go further than $P(|X_n + Y_n| > M) \le P(|X_n|+|Y_n| > M)$.
Thanks!
Answer: The secret is to observe the following
$$\{|X_n| + | Y_n| > M \} \subset \{ |X_n| \ge M/2 \} \cup \{|Y_n| \ge M/2 \}$$
otherwise,  $|X_n| + | Y_n| $ would be strictly less than $M$.
Then
$$P(|X_n| + | Y_n| > M ) \le P(|X_n| \ge M/2) + P(|Y_n| \ge M/2)$$
now you use properties of sup for a set of positive numbers and the inequality that you suggested.
Hope this can help.


Unable to execute stored procedure created in SQLCLR

Question: I have create a stored procedure in SQLCLR (SQL Server Database Project, VS2012). I publish the stored procedure successfully to the database. But when I run the stored procedure in the database, I get an error.

Cannot load dynamically generated serialization assembly. In some hosting environments assembly load functionality is restricted, consider using pre-generated serializer. Please see inner exception for more information.

Note: after publishing, no xmlserializer.dll is created. Even generate serialization assembly is set to ON.
Answer: Are you using WCF within your SQLCLR assembly (or some other web services client)?
If so, you need to use the XML Serializer Generator tool to create the serialization assembly manually and then add it to SQL Server along with your original assembly.
There are more detailed instructions at the above link, but the command you'll need (which can be added as a post-build step for your project) is something along the lines of:
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /force "$(TargetPath)"

Then in SQL Server:
CREATE ASSEMBLY [(ProjectName).XmlSerializers.dll] from '(ProjectName).XmlSerializers.dll'

More details about sgen are available here.
Comment: first of thank you very much for your support. Yes i'm using a WCF But even after creating xmlserializer.dll file and registering it in SQL server, same error is coming.
Comment: So you have `SomeAssembly.dll` and `SomeAssembly.XmlSerializers.dll` loaded?  If so, it seems your WCF contract may involve types from other assemblies for which you'll also need to generate a serialization assembly.


logistic regression in r outside range [0,1]

Question: lreg02 <- glm(formula = hizortalama ~ hiz24saatonce + dummysezon1 + dummysezon2 +
  dummysezon3 + dummydilim1 + dummydilim2 + dummydilim3 + yon + yonestimated +
  nem6max + nem24max + nem6range + nem12range + nem24range + nem6var + nem24var +
  basinc6max + basinc24max + basinc6range + basinc12range +
  basinc6var + basinc24var + temp6max + temp12max +
  temp6range + temp12range + temp24range + temp6var + temp24var,
  family = binomial("logit"), data = dftrain)
pred <- predict(lreg02,dftest)

i am using glm function an i choose binomial as family, but in prediction i get results outside the range [0,1] any suggestions ?
Comment: How about `predict(lreg02, dftest, type = "response")`? By default, predictions are on the scale of the linear predictor.
Comment: The manual page for `predict.glm`, which is the function you are implicitly invoking here, explicitly states about the `type` argument that "The default is on the scale of the linear predictors; the alternative 'response' is on the scale of the response variable. Thus for a default binomial model the default predictions are of log-odds (probabilities on logit scale) and type = "response" gives the predicted probabilities."
Comment: my bad. using predict does not work here
Comment: @baris did you read the comment above?
Answer: By default, predict.glm returns predicted values on the scale of the link function (linear predictor). On that scale, we fully expect values to lie beyond the 0-1 limits of the response.
You have a couple of options:

if you only want the predicted values you can use predict(model, type= "response"), which will apply the inverse of the link function to the predicted values to map them back on to the scale of the response variable.
if you want standard errors to form confidence intervals, you are better off working on the scale of the link function where you can form CI using the usual method from linear models and then manually map the predicted values and confidence interval limits back on to the response scale by applying the inverse of the link function yourself.

If you want to do 2. above, you can grab the inverse link function from the fitted model using:
linkinv <- family(model)$linkinv

This is a function and hence you can do:
pred <- predict(model, newdata)
linkinv(pred)

to do the mapping.
The family(model)$linkinv stays the same no matter what GLM you fit in R if it has implemented the family concept in the same way as glm(). the gam function in mgcv for example follows this way of working so this works the same with that package as with glm().
Comment: Do you have any idea how to access the link function from glmmTMB models given `family(modelname)$linkliv` returns `NULL`?


${1 \over \sqrt{3}} \sum\limits _{r=0}^4 \tan \left( \frac{\pi}{15}+\frac{r\pi}{5} \right)=$?

Question: $$\sum _{r=0}^4 \tan \left( \frac{\pi}{15}+\frac{r\pi}{5} \right)=k \sqrt{3}$$. Then evaluation of $k$
solution i try
$$\tan(12^\circ)+\tan(48^\circ)+\tan(84^\circ)+\tan(120^\circ)+\tan(156^\circ)$$
$$=\tan(12^\circ)+\tan(48^\circ)+\tan(84^\circ)+\tan(156^\circ)+\sqrt{3}$$
$$=\frac{\sin(60^\circ)}{\cos(12^\circ)\cos(48^\circ)}+\frac{\sin(240^\circ)}{\cos(84^\circ)\cos(156^\circ)}-\sqrt{3}.$$
plz help me how to simplify denominator.
Comment: @jacky, Could u follow my last link
Comment: See https://math.stackexchange.com/questions/346368/sum-of-tangent-functions-where-arguments-are-in-specific-arithmetic-series OR https://math.stackexchange.com/questions/823619/calculate-tan9-circ-tan27-circ-tan63-circ-tan81-circ/823655#823655
Comment: @DavidG.Stork Please do not use titles consisting only of math expressions; these are discouraged for technical reasons -- see [Guidelines for good use of $\LaTeX$ in question titles](http://meta.math.stackexchange.com/a/9730). (Having said that, thanks for taking your time to help with editing and improving posts on this site.)
Comment: thanks lab bhattacharjee and David. plez explain how do  i calculate my sum( which i have left)
Comment: thanks Lab bhattacharjee got it
Answer: $$S=\tan(12^\circ)+\tan(48^\circ)+\tan(84^\circ)+\tan(120^\circ)+\tan(156^\circ)$$
$$S=\tan(12^\circ)+\tan(48^\circ)+\tan(84^\circ)+\tan(156^\circ)+\sqrt{3}$$
$$S=\frac{\sin(60^\circ)}{\cos(12^\circ)\cos(48^\circ)}+\frac{\sin(240^\circ)}{\cos(84^\circ)\cos(156^\circ)}-\sqrt{3}.$$
$$S=\frac{\sqrt{3}}{\cos (60^\circ)+\cos(36^\circ)}-\frac{\sqrt{3}}{\cos(240^\circ)+\cos(72\circ)}-\sqrt{3}$$
use $\displaystyle \cos (36^\circ)=\frac{\sqrt{5}+1}{4}$ and $\displaystyle \cos(72^\circ)=\sin(18^\circ)=\frac{\sqrt{5}-1}{4}$
$$=4\sqrt{3}\bigg[\frac{6}{4}\bigg]-\sqrt{3}=5\sqrt{3}$$


Third tab is not shown on actionbar with fragments

Question: I want to create an app with three tabs. I have three fragments, three xml files, one main activity, one main xml and a tablistener class. The app shows the first two tabs properly, but the third tab is not shown. There is no error in the code.
Note: I'm using support library.
MainActivity:
public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupTabs();
    }

    // To setup tabs using ActionBar and fragments

    private void setupTabs() {

        // setup the ActionBar

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(true);

        //define which tabs you would like to display
        //and attach listeners for each tab:

        ActionBar.Tab tab1 = actionBar
                .newTab()
                .setText("First")
                .setTabListener(new SupportFragmentTabListener<FirstFragment>(R.id.main,this,
                        "first", FirstFragment.class));

        actionBar.addTab(tab1);
        actionBar.selectTab(tab1);

        ActionBar.Tab tab2 = actionBar
                .newTab()
                .setText("Second")
                .setTabListener(new SupportFragmentTabListener<SecondFragment>(R.id.main,this,
                        "second", SecondFragment.class));
        actionBar.addTab(tab2);

        ActionBar.Tab tab3 = actionBar
                .newTab()
                .setText("Third")
                .setTabListener(new SupportFragmentTabListener<ThirdFragment>(R.id.main, this,
                        "third", ThirdFragment.class));

        ActionBar.Tab tab4 = actionBar
                .newTab()
                .setText("Fourth")
                .setTabListener(new SupportFragmentTabListener<FourthFragment>(R.id.main, this,
                        "fourth", FourthFragment.class));
    }
}

TabListener:
public class SupportFragmentTabListener<T extends Fragment>
        implements TabListener {

    private Fragment mFragment;
    private final FragmentActivity mActivity;
    private final String mTag;
    private final Class<T> mClass;
    private final int mfragmentContainerId;

    public SupportFragmentTabListener(FragmentActivity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mfragmentContainerId = android.R.id.content;
    }

    public SupportFragmentTabListener(int fragmentContainerId, FragmentActivity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mfragmentContainerId = fragmentContainerId;

    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction sft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            sft.replace(mfragmentContainerId, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            sft.replace(mfragmentContainerId, mFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction sft) {
        if (mFragment != null) {
            // Detach the fragment, because another one is being attached
            //sft.remove(mFragment);

            sft.replace(mfragmentContainerId,mFragment);

        }else{
                // If not, instantiate and add it to the activity:
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                sft.add(android.R.id.content, mFragment,mTag);

            }
        }

    public void onTabReselected(Tab tab, FragmentTransaction sft) {
        // User selected the already selected tab. Usually do nothing.
    }
}

ThirdFragment:
public class ThirdFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.grade_table, container, false);

        TextView ff = (TextView) rootView.findViewById(R.id.textView2);

        return rootView;
    }
}

Comment: You didn't actionBar.addTab(tab3); after you created it;
Comment: ow thanks.sorry for wastıng tıme
Answer: You need to add the tab after creating it. You forgot to write:
actionBar.addTab(tab3);

and
actionBar.addTab(tab4);


$S = \frac{1}{(1-a)(1-ab)(1-b)}$ or $S = \frac{1}{(1-a)(1-b)(1-c)(1-ab)(1-ac)(1-bc)}$ etc.

Question: From How to compute the sum $ 1+a(1+b)+a^2(1+b+b^2)+a^3(1+b+b^2+b^3)+\cdots$ was shown that :
$$ 1+a(1+b)+a^2(1+b+b^2)+a^3(1+b+b^2+b^3)+\cdots=\frac{1}{(1-a)(1-ab)}$$
Does permutations such as
$S = \frac{1}{(1-a)(1-ab)(1-b)}$ or $S = \frac{1}{(1-a)(1-b)(1-c)(1-ab)(1-ac)(1-bc)}$ etc. lead to some sort of similar simple expansions?
Answer: Concerning the first one and taking into account that $$\frac 1 {1-x}=\sum_{n=0}^\infty x^n$$ you would find that $$ \frac{1}{(1-a)(1-ab)(1-b)}=$$$$\left(1+b+b^2+b^3+b^4+b^5+b^6+b^7+b^8+b^9+b^{10}+\cdots\right)+$$ $$a
   \left(1+2 b+2 b^2+2 b^3+2 b^4+2 b^5+2 b^6+2 b^7+2 b^8+2 b^9+2
   b^{10}+\cdots\right)+$$ $$a^2 \left(1+2 b+3 b^2+3 b^3+3 b^4+3 b^5+3
   b^6+3 b^7+3 b^8+3 b^9+3 b^{10}+\cdots\right)+$$ $$a^3 \left(1+2 b+3
   b^2+4 b^3+4 b^4+4 b^5+4 b^6+4 b^7+4 b^8+4 b^9+4
   b^{10}+\cdots\right)+$$ $$a^4 \left(1+2 b+3 b^2+4 b^3+5 b^4+5 b^5+5
   b^6+5 b^7+5 b^8+5 b^9+5 b^{10}+\cdots\right)+$$ $$a^5 \left(1+2 b+3
   b^2+4 b^3+5 b^4+6 b^5+6 b^6+6 b^7+6 b^8+6 b^9+6
   b^{10}+\cdots\right)+$$  $$a^6 \left(1+2 b+3 b^2+4 b^3+5 b^4+6 b^5+7
   b^6+7 b^7+7 b^8+7 b^9+7 b^{10}+\cdots\right)+$$ $$a^7 \left(1+2 b+3
   b^2+4 b^3+5 b^4+6 b^5+7 b^6+8 b^7+8 b^8+8 b^9+8
   b^{10}+\cdots\right)+$$ $$a^8 \left(1+2 b+3 b^2+4 b^3+5 b^4+6 b^5+7
   b^6+8 b^7+9 b^8+9 b^9+9 b^{10}+\cdots\right)+$$ $$a^9 \left(1+2 b+3
   b^2+4 b^3+5 b^4+6 b^5+7 b^6+8 b^7+9 b^8+10 b^9+10
   b^{10}+\cdots\right)+$$ $$a^{10} \left(1+2 b+3 b^2+4 b^3+5 b^4+6
   b^5+7 b^6+8 b^7+9 b^8+10 b^9+11
   b^{10}+\cdots\right)+$$ $$\cdots$$ where appear some nice patterns.


Parcelable Android

Question: Preciso fazer o Parcelable desta classe, mas está dando o erro:

class not found when unmarshalling

Poderiam me ajudar?
Minha classe:
    public class Internship implements Parcelable {
        private Enterprise enterprise;
        private int id;
        private String publicationTime;
        private String startDate;
        private String end_date;
        private String requirements;
        private String benefits;
        private int semester;
        private String title;
        private String observation;
        private ArrayList<Course> courses = new ArrayList<Course>();

        public Internship(){

        }

        public Internship(Parcel in){
           this.enterprise = in.readParcelable(Enterprise.class.getClassLoader());
           this.id = in.readInt();
           this.publicationTime = in.readString();
           this.startDate = in.readString();
           this.end_date = in.readString();
           this.requirements = in.readString();
           this.benefits = in.readString();
           this.semester = in.readInt();
           this.title = in.readString();
           this.observation = in.readString();
           in.readList(courses, Course.class.getClassLoader());
       }

       public ArrayList<Course> getCourses() {
           return courses;
       }

       public void addCourseToCourses(Course course) {
           this.courses.add(course);
       }

       public Enterprise getEnterprise() {
           return enterprise;
       }

       public void setEnterprise(Enterprise enterprise) {
           this.enterprise = enterprise;
       }

       public int getId() {
           return id;
       }

       public void setId(int id) {
           this.id = id;
       }

       public String getPublicationTime() {
           return publicationTime;
       }

       public void setPublicationTime(String publication_time) {
           this.publicationTime = publication_time;
       }

       public String getStartDate() {
           return startDate;
       }

       public void setStartDate(String start_date) {
           this.startDate = start_date;
       }

       public String getEnd_date() {
           return end_date;
       }

       public void setEnd_date(String end_date) {
           this.end_date = end_date;
       }

       public String getRequirements() {
           return requirements;
       }

       public void setRequirements(String requirements) {
           this.requirements = requirements;
       }

       public String getBenefits() {
           return benefits;
       }

       public void setBenefits(String benefits) {
           this.benefits = benefits;
       }

       public int getSemester() {
           return semester;
       }

       public void setSemester(int semester) {
           this.semester = semester;
       }

       public String getTitle() {
           return title;
       }

       public void setTitle(String title) {
           this.title = title;
       }

       public String getObservation() {
           return observation;
       }

       public void setObservation(String observation) {
           this.observation = observation;
       }

       public static final Parcelable.Creator<Internship> CREATOR = new Parcelable.Creator<Internship>() {
            public Internship createFromParcel(Parcel in){
            return new Internship(in);
       }

       public Internship[] newArray(int size){
            return new Internship[size];
       }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(publicationTime);
        dest.writeString(title);
        dest.writeString(startDate);
        dest.writeString(end_date);
        dest.writeString(requirements);
        dest.writeString(benefits);
        dest.writeInt(semester);
        dest.writeString(observation);
        dest.writeList(courses);
     }
 }

Answer: Você pode implementar esse Parcelable da seguinte maneira:
  public Internship(Parcel in){
       this.enterprise = in.readParcelable(Enterprise.class.getClassLoader());
       this.id = in.readInt();
       this.publicationTime = in.readString();
       this.startDate = in.readString();
       this.end_date = in.readString();
       this.requirements = in.readString();
       this.benefits = in.readString();
       this.semester = in.readInt();
       this.title = in.readString();
       this.observation = in.readString();
         if (courses == null)
        {
          courses = new ArrayList<Course>();
        }
        parcel.readTypedList(courses, Course.CREATOR);//alterado
        this.courses = in.readParcelable(Course.class.getClassLoader());//alterado
        }

     public static final Parcelable.Creator<Internship> CREATOR = new Parcelable.Creator<Internship>() {
        public Internship createFromParcel(Parcel in){
        return new Internship(in);
        }

   public Internship[] newArray(int size){
        return new Internship[size];
       }
     };

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(publicationTime);
    dest.writeString(title);
    dest.writeString(startDate);
    dest.writeString(end_date);
    dest.writeString(requirements);
    dest.writeString(benefits);
    dest.writeInt(semester);
    dest.writeString(observation);
    dest.writeTypedList(courses); // alterado
 }

Comment: Perfeita a resposta cara, consegui implementar. Muito obrigado!
Comment: Estamos aqui pra isso, @ViníciusVenanciodosSantos

Parcelable Android