I am trying to solve a non-linear equation. In the matlab program, I'm stuck up.

Question: One of the problems could be that, I want a matrix of order 33 but the output is 44, with first row and first column consisting of zeros. Can someone help !
n=5; m=5; T=1;
for i=2:n-1
for q=2:m-1
uexact(i,q,T)=exp(i+q-3*T);
<code>end
</code>
end
uexact =
<code>     0         0         0         0
     0    2.7183    7.3891   20.0855
     0    7.3891   20.0855   54.5982
     0   20.0855   54.5982  148.4132
</code>
Comment: We're mathematicians.  We're _all_ stuck up.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Use
$uexact(i-1,q-1,T)=exp(i+q-3*T);$
instead.
Even though your original code does only assign values to columns 2-5 and rows 2-5, Matlab automatically assumes that there must be a column 1 and row 1 to which it assigns 0 as a default value.
Comment: getting a 4*4 matrix with this modification
Comment: Run $clear\ all$ first
Comment: Thank you, it worked :) I have some other error now, but this one got better.
Comment: Great. But please post the next programming question not to math.stackexchange. there are dedicated forums for programming in there stackexchange forum family, e.g. https://stackoverflow.com/
Comment: Can you please tell how can i write [ b11 b12 0 0; b21 b22 0 0; 0 0 b11 b12; 0 0 b21 b22][u11 u21 u12 u22] into [b11 b12 0 0; 0 0 b11 b12; b21 b22 0 0; 0 0 b21 b22][u11 u12 u21 u22]? Actually i am getting the second matrix but i want to get first system.. Is there any way please!
Comment: @ppratiikshaa I don't really understand what you want to say, but it sounds like as if you pose a new question. So, what about posting it in a new thread? It would be best to post this thread in a programming forum, as already stated


How to transpile ECMA6 import of jQuery to a UMD wrapper with Babel?

Question: I'm trying to use Babel to transpile ECMA6 import of jQuery to a UMD wrapper.
My ECMA6 sources look as follows:
import {jQuery as $} from jquery;

<payload>

and Babel transpiles this to:
(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports !== "undefined") {
    factory(require('jquery'));
  } else {
    var mod = {
      exports: {}
    };
    factory(global.jquery);
    global.metisMenu = mod.exports;
  }
})(this, function (_jquery) {
  'use strict';

  var _jquery2 = _interopRequireDefault(_jquery);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  <payload>(_jquery.jQuery);

  })

This code works fine in Node.js environment as require('jquery') takes jquery from node_modules.
However, in browser environment global.jquery (which is equivalent to window.jquery) is not defined - jquery imports itself as $ or jQuery, but not as jquery.
Are there any Babel settings to fix this?
My current .babelrc
{
    "presets": [
        ["env", {
            "modules": "umd",
            "loose": true
        }]
    ]
}

Answer: You should use the globals option in the transform-es2015-modules-umd plugin:
{
  "plugins": [
    ["transform-es2015-modules-umd", {
      "globals": {
        "jquery": "jQuery"
      }
    }]
  ]
}

See the docs.


How do I loop a request for user input until the user enters the correct info?

Question: I am a beginner who is trying to learn Ruby. I have learned some of the easier stuff so far, but I seem to be stuck in trying to combine a couple of things I've learned.
What I am trying to do is to ask the user a question and tell them to enter either 1 or 2. A simple if statement would let me respond with one option if they enter 1, and another option if they enter 2. However, if they enter something entirely different like a different number, a string, etc., how can I prompt them to try again and have it loop back to the original question?
What I have so far looks something like this.
prompt = "> "
puts "Question asking for 1 or 2."
print prompt
user_input = gets.chomp.to_i

if user_input == 1
   puts "One response."
elsif user_input == 2
   puts "Second response."
else
   puts "Please enter a 1 or a 2."
end

This is where I'm stuck. How do I make it go back to the "Question asking for 1 or 2." until the user enters a 1 or 2? I know it's probably a loop of some kind, but I can't seem to figure out which kind to use and how to incorporate asking for user input repeatedly (if necessary) until getting the desired input. Any help would be greatly appreciated. Thanks.
Comment: Wow, you guys are freakin awesome. Thank you so much! I'm going to try out all of these and see how they go. I'm not anywhere near experienced enough to know which one is better for what I'm trying to do, but they all seem to get the job done. I'm just starting out so this site and this kind of quick help from experienced people makes such a big difference. I'll definitely be on here a lot as I learn and I'll definitely stick around to help out the noobs once I'm good at it. heheh Thanks again!
Answer: You're right that you need to run your code in a loop. Using a while loop with gets.chomp as a condition, you can carry on asking for user input until you decide you've got what you want.
In this case, you want to validate the answer to the question and ask again if it's invalid. You don't need to change a great deal, except making sure you break out of the loop when the answer is correct. If the answer is wrong, print the prompt again.
This is a slightly refactored version that uses case instead, but it shows what you need to do. There is no doubt a cleaner way to do this...
prompt = "> "
puts "Question asking for 1 or 2."
print prompt

while user_input = gets.chomp # loop while getting user input
  case user_input
  when "1"
    puts "First response"
    break # make sure to break so you don't ask again
  when "2"
    puts "Second response"
    break # and again
  else
    puts "Please select either 1 or 2"
    print prompt # print the prompt, so the user knows to re-enter input
  end
end

Answer: Try using the until method like this:
prompt = "> "
print prompt

user_input = nil
until (user_input == 1 or user_input == 2)
    puts "Please enter a 1 or 2."
    user_input = gets.chomp.to_i
end

if user_input == 1
   puts "One response."
elsif user_input == 2
   puts "Second response."
else
   puts "Please enter a 1 or a 2."
end

Answer:     user_input = 0
    until [1,2].include? user_input do
        puts "Please enter a 1 or a 2.>"
        user_input = gets.chomp.to_i
    end
    if user_input == 1
        puts "One response."
    else
        puts "Second response."
    end

You can try this to make your code clean.
Answer: While the title of this question is somewhat unrelated, please see the trick that is used here: Ruby Retry and ensure block is not working
The use of error detection and unique retry keyword available in Ruby allows you to easily do a retry-loop compacted together with nice an error handling.
However, mind that the example I pointed is not really the best. There are some minor issues. For example, you should not catch Exception, rather simple rescue => e would be enough. But the overall idea should be rather clear.


Como pegar valores de uma linha que estão em uma lista jstl e enviar para dentro dos respectivos input text na mesma pagina jsp?

Question: Boa tarde pessoal!Estou usando "Jsp, servlets, e jstl". Tenho uma lista onde tenho um link chamado alterar, ao clicar Pego os valores daquela linha da lista e envio para a mesma jsp onde tem um form  com os campos para poder ser feita a alteração, até o momento só estou conseguindo fazer os valores aparecerem na url pagina, mas não consigo exibi-los nos campos da jsp.
Estou enviando os campos  desta forma

E recebendo na outra jsp desta forma

   <input type="text" name="id_turma" id="id_turma" readonly="true" class="form-control" placeholder="Registro da turma" required="" value="${param.turma_id}"/>

    <input type= "text" name="nome_turma" id="tur_nome" class="form-control" placeholder="Nome da turma" required="" value="${param.tur_nome}" />

está e a URL que está chegando na outra pagina
http://localhost:43183/Chamada_online/view/v_configura_turma.jsp?&id_turma=1&nome_turma=TESTE5
Desde já agradeço!! Ainda estou aprendendo a usar o stackoverflow caso minha pergunta esteja mal formatada editarei de pronto :)
Answer: Boa tarde pessoal, não consegui fazer de forma direta , então simplesmente peguei o  id da linha selecionada e fiz uma nova consulta no banco onde recuperei os valores e  inserir os mesmos no input text para fazer as alterações.
Minha jsp na requisição da linha da  lista ficou desta forma.

Meu servlet ficou desta forma ,ele recebe um parâmetro  onde  é escolhida a função a ser executada.
String funcao = request.getParameter("funcao");

Executo a função recebe onde a mesma envia  para o método DAO onde é feita a pesquisa por id e recebendo os valores da  mesma como retorno para o servlet e na sequência  enviado  para a jsp preenchendo os campos.
O como ficou meu servlet  abaixo.
if(funcao.equals("recebe")){
                    int turma_id = Integer.parseInt( request.getParameter("id_turma"));
                    tb = tur.turma_busca_pk(turma_id);
                    request.setAttribute("turma", tb);
                    RequestDispatcher rd = request.getRequestDispatcher("configura_turma.jsp");
                    rd.forward(request, response);

Meu método DAO segue abaixo caso ajuda  mais gente em pesquisa por id.
ele recebe o id e faz a consulta no banco de dados recebendo 8 parâmetros de retorno.
public TurmmaBean turma_busca_pk (int id_turma){
    TurmmaBean turma = new TurmmaBean();
    String sql  ="select * from turma where tur_turma_id ="+id_turma;
    try {
    ps = con.prepareStatement(sql);
    rs = ps.executeQuery(sql);
   if (rs.next()){

            turma.setTurma_id(rs.getInt("tur_turma_id"));
            turma.setTur_nome(rs.getString("tur_nome"));
            turma.setTur_diciplina(rs.getString("tur_diciplina"));
            turma.setTur_ini_dia( new java.sql.Date (rs.getDate("tur_inicio").getTime()));
            turma.setTur_fim_dia(new java.sql.Date(rs.getDate("tur_fim").getTime()));
            turma.setTur_hora_inicio(rs.getTime("tur_hora_inicio"));
            turma.setTur_hora_fim(rs.getTime("tur_hora_fim"));
            turma.setTur_dia_semana(rs.getString("tur_dia_semana"));

   }
           rs.close();
           ps.close();
      } catch (Exception e) {
          throw new RuntimeException("Erro 1_D   " + e);
      }

return turma;
}

Desde já muito obrigado  galera!!!! :) Boas festas de fim de 2018.


Show that an hermitian operator is represented by an hermitian matrix.

Question: Let $\hat{A}$ be an hermitian operator.
I have to show that $\overline{A_{\alpha\beta}}=A_{\beta\alpha}$
So, if an operator is hermitian then $\hat{A} = \hat{A}*$
I started with this:
$\hat{A}*=\sum_{\alpha\beta}\overline{|u_{\alpha}\rangle A_{\alpha\beta}\langle u_{\beta}|}=\sum_{\alpha\beta}|u_{\beta}\rangle\overline{A_{\alpha\beta}}\langle u_{\alpha}|$
I don't know how to continue
Answer: Now note that $$\hat A=\sum_{\alpha\beta}|u_\beta\rangle A_{\beta\alpha}\langle u_\alpha|$$This must be equal to your final expression $\sum_{\alpha\beta}|u_{\beta}\rangle\overline{A_{\alpha\beta}}\langle u_{\alpha}|$ by Hermitianness of $\hat A$. Compare coefficients one by one. For instance by multiplying the two sums from the left by arbitrary basis bras $\langle u|$ and from the right by arbitrary basis kets $|u\rangle$.


Error in uploading marks Expected string but received array

Question: Estou com um projeto de gestão escolar, e na aba de "enviar chamadas" quando clico no botão para enviar o form com as presenças dos alunos da o erro "Error in uploading marks Expected string but received array", já ouvi falar que é um problema com a lib validator para as validações, porém não estou conseguindo resolver esse erro.
uploadMarks:
    const Validator = require('validator');
const isEmpty = require('./is-empty');

const validateFacultyUploadMarks = (data) => {
    let errors = {}
    data.subjectCode = !isEmpty(data.subjectCode) ? data.subjectCode : '';
    data.exam = !isEmpty(data.exam) ? data.exam : '';
    data.totalMarks = !isEmpty(data.totalMarks) ? data.totalMarks : '';

    if (Validator.isEmpty(data.subjectCode)) {
        errors.subjectCode = 'Subject Code field is required';
    }

    if (Validator.isEmpty(data.exam)) {
        errors.exam = 'Exam field is required';
    }
    if (Validator.isEmpty(data.totalMarks)) {
        errors.totalMarks = 'Total marks field is required';
    }

    return {
        errors,
        isValid: isEmpty(errors)
    };

}

module.exports = validateFacultyUploadMarks

teacherController:
uploadMarks: async (req, res, next) => {
        try {
            const { errors, isValid } = validateFacultyUploadMarks(req.body);

            // Check Validation
            if (!isValid) {
                return res.status(400).json(errors);
            }
            const {exam, totalMarks, marks, department, year } = req.body
            const isAlready = await Mark.find({ exam, department})
            if (isAlready.length !== 0) {
                errors.exam = "You have already uploaded marks of given exam"
                return res.status(400).json(errors);
            }
            for (var i = 0; i < marks.length; i++) {
                const newMarks = await new Mark({
                    student: marks[i]._id,
                    exam,
                    department,
                    marks: marks[i].value,
                    totalMarks
                })
                await newMarks.save()
            }
            res.status(200).json({message:"Marks uploaded successfully"})
        }
        catch (err) {
            console.log("Error in uploading marks",err.message)
        }

    },

is-Empty:
const isEmpty = value =>
    value === undefined ||
    value === null ||
    (typeof value === 'object' && Object.keys(value).length === 0) ||
    (typeof value === 'string' && value.trim().length === 0);

module.exports = isEmpty;

Answer: De acordo com a biblioteca Validator, o método isEmpty espera receber uma string como parâmetro.

No trecho que você disponibilizou, você está enviando para Validator.isEmpty() algum array

data.subjectCode
data.exam
data.totalMarks

Em:
const validateFacultyUploadMarks = (data) => {
 let errors = {}
 data.subjectCode = !isEmpty(data.subjectCode) ? data.subjectCode : '';
 data.exam = !isEmpty(data.exam) ? data.exam : '';
 data.totalMarks = !isEmpty(data.totalMarks) ? data.totalMarks : '';

 if (Validator.isEmpty(data.subjectCode)) {
    errors.subjectCode = 'Subject Code field is required';
 }

 if (Validator.isEmpty(data.exam)) {
    errors.exam = 'Exam field is required';
 }
 if (Validator.isEmpty(data.totalMarks)) {
    errors.totalMarks = 'Total marks field is required';
 }

 return {
    errors,
    isValid: isEmpty(errors)
 };
}

O erro é capturando no bloco try catch pela chamada da função
 const { errors, isValid } = validateFacultyUploadMarks(req.body);

Sugiro revisar qual dessas variáveis não é uma string ou não utilizar o método Validator.isEmpty, optando por usar a sua própria implementação de isEmpty para checagem.
Comment: Eu removi o validator e deixei só o isEmpty para checagem , só que agora ele dá erro 400(Bad request)
Comment: Verifica qual dado está inválido. O erro 404 ta sendo forçado caso `!isValid` por sua função `uploadMarks`. Poste o trecho de como ficou a atualização com a remoção do `isEmpty`.


Posição de Texto em gráfico de pizza no ggplot2

Question: Tenho a seguinte tabela
Var1              Freq        Percentual
Até 50 anos       4657         2.98%
De 51 a 60 anos   32009        20.47%
De 61 a 70 anos   57368        36.68%
De 71 a 80 anos   46075        29.46%
Mais de 80 anos   16299        10.42%

E preciso de um gráfico de pizza que os percentuais de cada faixa etária fique na posição correta
graf.faixa.etaria <- ggplot(tabela.faixa.etaria, aes(x ="", y=Freq, fill=Var1)) + geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start = 0, direction = -1) +
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    panel.background = element_blank(),
    axis.text.x=element_blank(),
    legend.title = element_blank()) +
  geom_text(data = tabela.faixa.etaria, aes(x ="", y=Freq, label = Percentual)) +
  labs(title = "Gráfico 6: Faixa de Idade dos Inativos",
       subtitle = "Fonte: Base de Dados SIGRH")
graf.faixa.etaria

Answer: Fiz a inclusão da função position_stack() dentro de geom_text()
graf.faixa.etaria <-
  ggplot(tabela.faixa.etaria, aes(x ="", y=Freq, fill=Var1)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start = 0, direction = -1) +
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    panel.background = element_blank(),
    axis.text.x=element_blank(),
    legend.title = element_blank()) +
  geom_text(data = tabela.faixa.etaria,
            aes(x ="", y=Freq, label = Percentual),
            position = position_stack(vjust = 0.5)) +
  labs(title = "Gráfico 6: Faixa de Idade dos Inativos",
       subtitle = "Fonte: Base de Dados SIGRH")
graf.faixa.etaria


What should be the curriculum for an adult piano lesson

Question: I am an adult(37) learning piano with a teacher since 6 months. It is a 30 min lesson a week where each lesson, we go through a couple of pages of Nancy and Randall Faber's adult piano adventures. If I were to do a second lesson every week, what should be the content?
I feel the book does not give enough understanding of theory and composition, should the second lesson be exclusively piano music theory, or just plain music theory?
Answer: Personally, I don't rely on a particular book from which to make up lesson content. It's facile. There are so many facets to learning piano, from learning a scale, then having to make up a tune using it, harmonising it, sight-reading something in that key, etc., etc.
For me, every lesson must contain a different challenge, especially for adults, but kids like it as well. Problem for me with a 'lesson book' is that I can feel where the student needs to go next - the book doesn't have much idea, as we are all individuals.
The second lesson maybe should be with a different teacher with different views! Yes, theory is fine, but a section of theory with the practical approach following. Take a mode - Dorian. Find out where it came from, what it is, but then for homework, come up with a tune using the Dorian mode. Stuff like that.


Double counting within sequences and arrangements

Question: Say we are forming sequences of numbers in the interval [0-9], lengths of (2x) where x is a value from [1,5].  So we form sequences of 2, 4, 6, 8, and 10 numbers.
A successful sequence is a sequence where at least half of the elements, (at least x of the elements), are the same number consecutively.  What is the total of 2, 4, 6, 8, and 10 number sequences that are successful?
Example: 2234 is successful.  3131 is not. 12 is successful. 2233 is successful. 2223 is successful.
Solution attempt:  My original plan was to choose 1 of the 10 numbers to have x times in a row, so 10 choices.
My second step was to choose the starting location of the x-length piece, and the x-length piece can be started at either the first position, all the way up to the x+1 position in the 2x length sequence.  So there are x+1 choices for the starting point of the x-length sequence.
My third step was to choose 1 of 10 letters for each of the remaining x slots, but now I realize I am double counting.
For example, the sequence 1122 could be obtained by choosing 11 as our x length sequence, placing it in the first slot, and happening to choose 2s to fill the remaining slots.
1122 could also be obtained by choosing 2 for the x length sequence, placing it in the third (x+1) slot, and happening to choose 1s to fill the rest.
I am assuming this is some sort of summation for values of x 1,2,3,4,5 or 2x, 2,4,6,8,10.  However, I am unsure of how to account for double counting in a way that is applicable to the general pattern of the scenario.  This isn't exactly something I feel should be solved with brute force.  Any help would be greatly appreciated.
Comment: So a sequence is 'successful' if and only if it contains a subsequence of length $x$, which is entirely made up of one integer from [0..9]?
Comment: For example, is 345558 successful?
Comment: Yes, this is correct.
Comment: At least length x, so 345555 is also successful.
Comment: Did you delete your answer? I had intended to mark it accepted but you seem to have removed it.
Comment: Yes. I was unsure of it so I checked for $x=2$ in python and it turned out to be incorrect. I'l put it back when it's fixed.
Answer: Here  we  use generating functions  to derive  the  number of successful sequences of length $2x$ containing $x$ consecutive  equal  characters,  $x\in\{2,3,4,5\}$ over a $10$ character alphabet.
But before that we consider the special, simple case $x=1$.

Case   $x=1$:  Each word   having length $2x=2$ is a successful sequence. So  there  are
  \begin{align*}
10^2=\color{bue}{100}
\end{align*}
  different words.

We continue by stating a generating function which counts words of a $10$ character alphabet with no consecutive equal characters at all.
These words are called Smirnov or Carlitz words. See example III.24 Smirnov words from Analytic Combinatorics by Philippe Flajolet and Robert Sedgewick for more information.

The generating function $A(z)$ counting Smirnov words over a $10$ character alphabet is according to the reference
  \begin{align*}
  A(z)&=\left(1-\frac{10z}{1+z}\right)^{-1}
\end{align*}
The coefficient of $z^n$ of $A(z)$ gives the number of Smirnov words of length $n$.

Based upon $A(z)$ we generate all words over the $10$ character alphabet which contain for $x\in \{2,3,4,5\}$ no more than $x-1$ consecutive equal characters. This means each character can be replaced with one up to $x-1$ characters.
\begin{align*}
z\longrightarrow z+z^2+z^3+\cdots+z^{x-1}=\frac{z(1-z^{x-1})}{1-z}
\end{align*}
in the  generating function $A(z)$.

We obtain this way a generating function $B(z)=A\left(\frac{z(1-z^{x-1})}{1-z}\right)$ with
  \begin{align*}
B(z)&=\left(1-\frac{10\cdot \frac{z(1-z^{x-1})}{1-z}}{1+\frac{z(1-z^{x-1})}{1-z}}\right)^{-1}=\frac{1-z^x}{1-10z+9z^x}\\
\end{align*}
  The coefficient of $z^{2x}$ of $B(z)$ gives   the  number  of words which contain  less than $x$ consecutive equal characters.

The number of all words over a $10$ character alphabet  is given by
\begin{align*}
\sum_{n=0}^\infty (10z)^j=\frac{1}{1-10z}
\end{align*}

We conclude the generating function $C_x(z)$ with
  \begin{align*}
C_x(z)=\frac{1}{1-10z}-\frac{1-z^x}{1-10z+9z^x}\qquad\qquad x\in\{2,3,4,5\}
\end{align*}
  counts the words which contains runs of length $x$, i.e. words having at least $x$ consecutive equal characters.

The number of successful sequences of length $2x$ is
\begin{align*}
[z^{2x}]C_x(z)\qquad\qquad x\in\{2,3,4,5\}
\end{align*}

In the following we obtain the series expansions below with some help of Wolfram Alpha
Case x=2:
The number of successful sequences of length $2x=4$ is
  \begin{align*}
[z^4]C_2(x)&=[z^4]\left(\frac{1}{1-10z}-\frac{1-z^2}{1-10z+9z^2}\right)\\
&=[z^4]\left(10z^2+190z^3+2710z^4+34390z^5+\cdots\right)\\
&=\color{blue}{2710}
\end{align*}
Case x=3:
The number of successful sequences of length $2x=6$ is
  \begin{align*}
[z^6]C_3(x)&=[z^6]\left(\frac{1}{1-10z}-\frac{1-z^3}{1-10z+9z^3}\right)\\
&=[z^6]\left(10z^3+190z^4+2800z^5+36910z^6+\cdots\right)\\
&=\color{blue}{36910}
\end{align*}
Case x=4:
The number of successful sequences of length $2x=8$ is
  \begin{align*}
[z^8]C_4(x)&=[z^8]\left(\frac{1}{1-10z}-\frac{1-z^4}{1-10z+9z^4}\right)\\
&=[z^8]\left(10z^4+190z^5+2800z^6+37000z^7+459910z^8+\cdots\right)\\
&=\color{blue}{459910}
\end{align*}
Case x=5:
The number of successful sequences of length $2x=10$ is
  \begin{align*}
[z^{10}]C_5(x)&=[z^{10}]\left(\frac{1}{1-10z}-\frac{1-z^5}{1-10z+9z^5}\right)\\
&=[z^{10}]\left(10z^5+190z^6+2800z^7+37000z^8+460000z^9+5499910z^{10}+\cdots\right)\\
&=\color{blue}{5499910}
\end{align*}

Adding all   the results we finally obtain

The  number of successful sequences is
  \begin{align*}
100+\sum_{j=2}^5[z^{2j}]C_j(x)&=100+2710+36910+459910+5499910\\
&=\color{blue}{5999540}
\end{align*}
Answer: As you ask for a sequence of length x, there are not many ways to have two sequences of distinct numbers in a sequence of length 2x. Precisely, you can chose 10 numbers for the first sequence, and 9 for the second, so 90 in total.
What is more difficult are longer sequences of the same number, for instance 1112 is counted 2 times, and 1111 even 3 times.
To avoid double counting these sequences, count the number of sequences of length x, and subtract the number of sequences of length x+1. A sequence of length x+k is now counted exactly once: you add it k+1 times when you count the sequences of length x, and subtract it k times when you subtract the sequences of length x+k.
To have the answer you want, you still have to count the possibilities of x and x+1 sequences for every x, subtract the possibilities of two sequences of different numbers and add all together, but I assume this is not considered as brute force.
Answer: Consider a valid string containing $x$-tuple of twos, and an extra $n\ (0\leq n\leq x)$ number of twos. Thus you end up with exactly $(x-n)$ non-two symbols(of which there are $9^{x-n}$ possibilities) in the string. The $x$-tuple could be anywhere in the $(x-n+1)$ positions between/beyond these symbols.
The only positions left to be enumerated now are for the extra $n$ twos; these can go into any combination of $(x-n+2)$ places between the objects we have so far. Take a look at the partition adjacent to the $x$-tuple on the left and the one on the right. It should not matter if we assign $2$ twos to the one on the left and a single two to the one on the right, the end result is that you end up with a $(x+3)$-tuple of twos. (**Old explanation: This means we are overcounting by a factor of two. So remember to divide the above binomial coefficient by $2$. **Not true when n=0; also not true if both the partitions are assigned zero.)
So the two partitions may be combined into one. Note that multiple twos may occupy a single position here, so we are looking for the number of weak compositions of $n$ twos into $(x-n+1)$ partitions, which is:
$$
\binom{n+(x-n+1)-1}{n} = \binom{x}{n}
$$
Now put everything together:
$$
10\sum_{n=0}^{x} 9^{x-n}(x-n+1) \binom{x}{n}
$$
This still overcounts by exactly 90. (verified for each of $x=1,2,3,4$)
If you do a few examples by hand you'll notice that it double counts every case where a sequence consists of two parts: an $x$-tuple of one symbol, and an $x$-tuple of another symbol. For example, $x=2, n=0$: The sequence 2233 will be counted twice; once while counting sequences with $x$-tuple of $2$'s and again while counting $x$-tuple of $3$'s.
Accounting for every such permutation, we have:
$$
10\sum_{n=0}^{x}\left\{ 9^{x-n}(x-n+1) \binom{x}{n} \right\} - \left(10 \right)_2
$$


Why is Mean squared error a good loss function?

Question: I am currently studying the statistics behind machine learning and my question is why the mean squared error is a good selection for the loss function? Does it have good statistical properties (unbiased, consistent)? Or practical advantages?
Someone told me that it is unbiased but I still do not see why it is even a estimator, since it is rather a function which evaluates your point estimator. I would appreciate any type of clarification since I could not find anything online about this topic.
Comment: Related [Why square the difference instead of taking the absolute value in standard deviation?](https://stats.stackexchange.com/questions/118/why-square-the-difference-instead-of-taking-the-absolute-value-in-standard-devia)
Comment: Unbiased for what?
Comment: [Mean and Median properties](https://stats.stackexchange.com/questions/7307/mean-and-median-properties)
Comment: There are no silver bullets. There is no "one metric to rule them all". We are mechanics in the garage, and we look to have toolboxes with a decent diversity of tools where we have decent familiarity with each of them. Every metric is a dog metric. There is always a place where each of them falls on its own sword. There is always a place where each of them stands tall. It takes familiarity with both the place and the metric to determine the fit, that is why it is a practice, a little bit of artisanship.
Comment: I totally agree with all the comments. I just got that question in an interview and then the interviewer said something about likelihood, unbiased and estimator and that a lot of people forget about the statistical properties of MSE (he studied in cambridge). But I could not find anything related. That is why I asked here.
Answer: Based on your last comment about "likelihood", "unbiased", and "estimator", I think I know what your interviewer meant.
When you assume $iid$ Gaussian error terms, which is a common assumption, in linear regression, minimizing square loss gives the same solution as maximum likelihood estimation of the regression parameters. That is:
$$
\hat\beta_{MLE}=\hat\beta_{OLS}=(X^TX)^{-1}X^Ty
$$
Further, even under milder conditions (don't even need Gaussian error terms), the Gauss-Markov theorem says the OLS solution is the best linear unbiased estimator (BLUE), where "best" means lowest variance (among linear and unbiased estimators).
If you drop either the linear requirement or the unbiased requirement, you can get lower variances, however. For those (and probably other) reasons, square loss might not be the best estimation method. As another comment remarked, there is no silver bullet.
Comment: +1.  This is a very good answer from a statistical perspective.  It is also worth noting that the loss is a convex function and ,assuming $X$ is not rank deficient, has unique minimum making optimization a straightforward problem to solve.  Additionally, MSE is a proper scoring rule, as compared to something like accuracy or AUC (I know we're talking about linear regression, but we could just as easily fit a logistic regression by minimizing the brier score.  There are just problems with the gradient were we to do that).  Lots of reasons to like MSE.
Comment: thank you both very much. I think this is exactly what he meant. :)


Sprite Sheet Animation Cocos2dx

Question: I've been working really hard for weeks now trying to get sprite sheet animation to work, and it isn't. I've tried, using this wiki page, http://www.cocos2d-x.org/wiki/Sprite_Sheet_Animation, and I've tried to make my own code, and neither have gotten e remotely close to where I want to be and I really have no idea what I'm doing here. Any help will be welcomed, and greatly appreciated. Thanks in advance.
Comment: What exactly did you try, and how exactly didn't it work?
Comment: The link you mention is pretty spot on. I have used it a few times recently and I'm working great.
Answer: For sprite sheet animation you have to make a plist for all your images.
Download texture packer : https://www.codeandweb.com/texturepacker
After installing the texture packer, add sprites to it and publish it.
It will create a plist.
Add that plist and png to the resources folder of your project.
Now add the following code to the init() of your GameLayer :
<code>SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("BowArrow.plist");
for (int i = 1; i <= 9; i++) {
     frame = String::createWithFormat("Bow%d.png", i);
     frames.pushBack(
     SpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(
     frame->getCString()));
 }
</code>
Now you have all the sprites of plist in a framecache and you can run animation on them in the way you want.
I hope it helps.
Answer: You can make animations using GIF, i made so in my game and never had performance issues, you can make a GIF from web GIF Maker

Sprite Sheet Animation Cocos2dx


Nuxt.js - Globally import custom NPM packages

Question: Nuxt's plugins/modules system is extremely complicated and as such I've not been able to accomplish this very simple task, even after looking at some other answers here on SO. I've installed the NPM package csv-parse (found here), then I created a file in my project's plugins directory named csv-parse.js, in which I put the following code:
import Vue from 'vue';
import CsvParse from 'csv-parse';
Vue.use(CsvParse);

Then I added { src: "~/plugins/csv-parse", mode: "client" } to the plugins array in my nuxt.config.js (I only need to use this package client-side).
As far as Nuxt's documentation and the other SO answers will have you believe, you should now be able to use this package globally in your components, but no one cares to show how to use it in your component. Here's what I've tried:
// @/components/Hospitals/Crud.vue
...

...

Can someone please clear the mystery of how to globally use custom NPM packages in a Nuxt project?
Comment: For a quick explanation: modules are official packages (usually well maintained) by the community, and which are plug and play. There is a list here: https://modules.nuxtjs.org/ (it probably do not have them all but a good amount still). Plugins provide a way to import any kind of JS code (Vue or vanilla) into your project, before Vue instance is up. It's basically to import any code that is not designed for Nuxt out of the box.
Answer: You followed the answers well and imported the package successfully here IMO (on client side only).
For your main question, people do not explain how to use it globally because it's usually dependant of the package itself. For a quick demo, here is my vue-vee-validate.js file
import Vue from 'vue'
import { ValidationProvider, ValidationObserver } from 'vee-validate'

export default ({ app }) => {
  Vue.component('ValidationObserver', ValidationObserver)
  Vue.component('ValidationProvider', ValidationProvider)
}

Following the official docs, it should be imported like this and used like that in my Nuxt project (after the plugin install)
<ValidationProvider v-slot="v">
  <input v-model="value" type="text">
</ValidationProvider>

So, even if the initial setup is not exactly the same because you're bringing it into Nuxt, the end result is the same. If you can achieve to make it work in any basic ES6 project, you can use the same way after a plugin import in Nuxt.

So here, for your node-csv-parse, if you can achieve to make it work in a NodeJS project, you may use it as easily here too. Yep, you read it correctly, your project is aimed towards Node at first. And therefore, it should not work in the browser. You can probably try to use it with Browserify or to find an alternative (browser-ready) package that does that.
Still, in node it should work as told in the docs
var csv = require('csv');
var generator = csv.generate({seed: 1, columns: 2, length: 20});

So, Browserify should help use it in a similar manner when transformed into a browser compatible bundle (and imported in your csv-parse.js file).

PS: CSV operations may be heavy and could maybe use some backend for the computing, then sent to the frontend maybe ?
PS2: Nuxt is still a NodeJS server at the end, so you could maybe just run your CSV operations on the server side only, then give it somehow to your client. Not sure how to do that.
Comment: Thanks for taking the time. In the end I gave up and just ended up importing it locally. As for executing csv operations in the client - the problem is that I was to perform additional operations on the data set, and the functionality to perform the additional operations is only available on the client and not on the server.


PHP Startup: Timezone database is corrupt

Question: I have a CentOS 5.2 server. PHP is now at the 5.2.10 version (php-5.2.10-1.el5.remi.i386), and I have updated to 5.3, tzdata was updated too (tzdata-2009i-2.el5.noarch). Since the update, Apache refuse to start because PHP crash.
Here is the httpd/error.log
[Wed Jul 08 11:40:21 2009] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Wed Jul 08 11:40:24 2009] [notice] Digest: generating secret for digest authentication ...
[Wed Jul 08 11:40:24 2009] [notice] Digest: done PHP Strict Standards: PHP Startup: It is not safe to rely on the system's timezone settings.
Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected` 'Europe/Berlin' for 'CEST/2.0/DST' instead in Unknown on line 0
**PHP Fatal error: PHP Startup: Timezone database is corrupt - this should never happen! in Unknown on line 0**

Best regards, Cédric
Answer: It seems to be a bug opened on php.net: http://bugs.php.net/bug.php?id=48882
Here it is suggested to

add TZ=GMT in (apache) init.d script.

It should fix the problem.
Comment: Great! I read this bug report but miss the "export TZ=GMT" in /etc/init.d/http script. Thanks!
Answer: It's an old question, but here is the answer anyway:  in the question, the asker is using the suExec mechanism.  those using mod_chroot or the apache2 built in ChrootDir will encounter similar problems.
make sure that {chroot}/etc/localtime and {chroot}/usr/share/zoneinfo exist - that's it.
credit goes to:
http://www.phwinfo.com/forum/alt-comp-lang-php/315265-timezone-database-corrupt.html#post1410153
Answer: fixed it based on previous answer (CentOS v6):
nano /etc/init.d/httpd

but instead of UTC it's GMT+1:00. France may be GMT.
export TZ="Europe/Berlin"

and restart:
service httpd restart


Modulating from E Minor to C Minor

Question: I'm struggling to get from E Minor to a Bbsus chord. Once I get there, my modulation to C minor is good but I'm struggling to find something that moves me smoothly to the Bbsus. Any thoughts?
Comment: @mramosch I think if it doesn't say 2 it's 4. In classical music the suspension always held a note from a previous chord that becomes fa->mi in the new chord.
Comment: By the way Bb sus ***'what'*** - sus2/sus4 ??? - And which music style ? *'Jazzy'* with a lot of tensions allowed or more *'Classical'*, *'Pop'* ? - How many bars are available - slow or quickest possible modulation??? And above all *'for which instrument'* - solo or arrangement/orchestration?
Comment: In classical music there is also a suspension that holds a note from a previous chord that becomes re->mi in the new chord ;-) -> IV V I -> chords progression in C-major: C/F/ **A** -> D/G/ **A** -> D/G/ **B** -> E/G/ **C**
Comment: @mramosch nope that's called a _retardation_ not a suspension see http://www.musictheory.net/lessons/53
Comment: @Dom: I am referring to the analog phenomena that _@luserdroog calls a *'suspension'*... - just sus2 instead of sus4... - Or do you say this is a C(ret2)-chord instead of C(sus2)-chord ?
Comment: What genre is this?  if you just want to get from E minor to C minor you can do that through a diminished 7th.  It sounds like your real question is not getting to C minor but getting to Bb.
Comment: @mramosch Suppression only resolve downward in classically theory, retardation resolve upward which is why the default sus chord is a sus4 because this matches the traditional definition.
Comment: Suppression? Maybe we should bring *'depression*' into play... ;-)
Answer: I don't know why you need to use Bbsus, but I can think of two other ways you can modulate.

First, a way to modulate from E minor to C Minor is chromatically. Very simple, by flatting the E and B. Em is E,G,B and Ebm (III of C minor) is Eb,G,Bb. So, by this chromatic modulation, you find yourself to the C minor scale. *
And secondly, while on E minor, you can play Em (i),  G(III) which G is the V of C minor and simply play Cm afterwards.

These two tonalities are a bit afar; E minor has one sharp while C minor has three flats, so the two aforementioned methods might sound a bit off, but they are the quickest way there.
A more smooth, but longer way would be to follow the circle of fifths leftwise. E minor to A minor to D minor to G minor to C minor, but that would take more time.
Since you like the sound of Bb sus, you can approach it chromatically. Similarly to the first way described above, you can play Em (E,G,B) and flat the E and B to Eb and Bb respectively, remove the G and you have the Bbsus chord. This might not be really smooth. Another way would be to play some other chord from the E minor scale that contains  either the note E or the note B.
*Generally, chromatic modulations are used to approach tonalities that far apart.
Comment: I don't know that I *need* the Bbsus, but it takes me where I go and helps build to the dramatic last verse. Plus I just like the sound of it :-) I'd like to keep it if I can get there smoothly, If not, I'll reconsider. But thanks for your suggestions...I'll try them out and see if I can get anything to work. Thanks!
Comment: @Tracey I added a way to use Bbsus, but it would be the smoothest; it will sound similar to the first way I posted
Comment: Thanks! I'll have more musical play-time tonight than I had last night, so i'll play around with that and see what I come up with.
Comment: Eb-Bb sounds more like an Eb5 chord instead of Bbsus without the fifth to me.
Answer: Yes, you need a chromatic modulation, if you don't want to use another key for the modulation.
This is maybe the simplest one.
Comment: Where's the B-flat sus4 chord? Are the Bs in the second chord supposed to be flat?
Comment: The main question is how to modulate from e-minor to c-minor. The user had a question about Bb-sus chord, which is not found in e-minor neither very useful as a modulation tool to c-minor. Therefore, my explanation offers a solution to modulation from e-minor to c-minor.
Comment: I guess it depends on what part of the question one sees as the essential part. I was keying off of: "...I'm struggling to find something that moves me smoothly to the Bbsus. Any thoughts?"
Comment: I agree. But Bb-sus is already Eb-major which is very far away from e-minor, and therefore very close to c-minor. If you need to have Bb-sus in e-minor and still not entering c-minor: it is very hard task. I would like to see how Tracey's progressions are moving and where it stops.
Comment: @ToddWilcox you're right, my issue was/is getting to the Bbsus from E minor. I don't have time to figure out how to insert an image of the section but the progression is i (Em) - i (Em7/D in bass) - iv6 (this is where I'm struggling...changing E to Eb helps, I'm just not sure it's enough) - Bb sus - Bb - Cm. Sorry if that's confusing, I couldn't figure out how to insert the image :-)
Comment: Bb (yours sus: Bb4/5) is so-called the polar chord, it is the farthest available chromatic chord in a scale in the tonal system, since it is found on a tritone. There are numerous possibilities to come to that chord, but the following point you have to keep in mind: P-chord is very far away. If you use it as an exception (Liszt, Dvorak) you must therefore to return back to your original key (e-min). But if you want to use it as a modulative-chord (use it to go to the another key) it will sound very unstable. Therefore, you need to reach c-minor (or Eb-major) before entering Bbsus4 (Bb4/5).
Answer: Everything depends on how long there is to make the transition, the harmonic rhythm within that time, and the demands of whatever might be happening melodically. That is to say: how many chords do you have time for, how long can you give a listener to adjust to the new harmony, and what restrictions does the melody place?
A general approach, though, might be to construct the progression in reverse. For discussion's sake, the simplest, smoothest way to get to the Bbsus is from a chord with two common tones. Here is a chart of options in which the non-common tone is within a semitone of its destination:

D-F-Bb    potentially gives away the game (= BbMaj)
E-F-Bb    very dissonant
Eb-E-Bb   very dissonant
Eb-Gb-Bb  Ebmin, the IV chord of the destination
Eb-F-A    basically F7, so the V chord of the destination
Eb-F-B    a more dissonant version of the F7 chord

This approach could be extended all the way back to the starting Emin.
Here are a couple of options that use that approach in part, but also rely on just messing around with what sounds good (to my ear).
Emin -> GMaj -> Gmin -> EbMaj -> EbMin -> Bbsus
X: 1
T: Emin -> Bbsus #1
K: none
M: none
L: 1/1
[EGB] [DGB] [DG_B] [_EG_B] [_E_G_B] [_EF_B]

Emin -> Eb+ -> GMaj -> AMaj -> Dmin -> F7 -> Bbsus
X: 1
T: Emin -> Bbsus #2
K: none
M: none
L: 1/1
[EGB] [_EGB] [DGB] [^CEA] [DFA] [_EFA] [_EF_B]

Answer: By the way Bb sus 'what' - sus2/sus4 ??? - And which music style ? 'Jazzy' with a lot of tensions allowed or more 'Classical', 'Pop' ? - How many bars are available - slow or quickest possible modulation??? And above all 'for which instrument' - solo or arrangement/orchestration?

For a quicky from 'Em' to 'Cm' on the Piano just go 'Barbra Streisand':

| Em Em | F/G G || Cm(add9) | ...

The highest notes also

| e e | f g || g | ...

With the progression IV/V - V - I respectively IV/V - V - i (as seen from your new tonic) you can go absolutely everywhere in one bar. Major or Minor!  Em is already part of C - you just decide in the last moment to go 'minor'... ;-)
Comment: Bb sus usually refers to sus 4
Comment: Yup, sus 4. It's a handbell arrangement of Kingsfold, more on the classical side. I'm moving from a somewhat contrapuntal 3-part texture to chords, so it's relatively thin. The Bbsus is where it builds before moving to c minor, I just wasn't happy with how I got there. The addition of an Eb to a previously a minor chord helped some, I'm still pondering if it was enough. But thanks to everyone who has weighed in for the help.

Modulating from E Minor to C Minor


HttpMessageHandler cleanup cycle

Question: In my .NET5 WebApi application, I am continuously getting below in the log:
<code>[2022-03-07 13:34:34 DBG] Ending HttpMessageHandler cleanup cycle after 0.0348ms - processed: 0 items - remaining: 2 items
[2022-03-07 13:34:44 DBG] Starting HttpMessageHandler cleanup cycle with 2 items
[2022-03-07 13:34:44 DBG] Ending HttpMessageHandler cleanup cycle after 0.0064ms - processed: 0 items - remaining: 2 items
[2022-03-07 13:34:54 DBG] Starting HttpMessageHandler cleanup cycle with 2 items
[2022-03-07 13:34:54 DBG] Ending HttpMessageHandler cleanup cycle after 0.0031ms - processed: 0 items - remaining: 2 items
[2022-03-07 13:35:04 DBG] Starting HttpMessageHandler cleanup cycle with 2 items
[2022-03-07 13:35:04 DBG] Ending HttpMessageHandler cleanup cycle after 0.0044ms - processed: 0 items - remaining: 2 items
[2022-03-07 13:35:14 DBG] Starting HttpMessageHandler cleanup cycle with 2 items
[2022-03-07 13:35:14 DBG] Ending HttpMessageHandler cleanup cycle after 0.0121ms - processed: 0 items - remaining: 2 items
[2022-03-07 13:35:24 DBG] Starting HttpMessageHandler cleanup cycle with 2 items
</code>
This continues to happen, sometimes endlessly. Seems it's a cleanup cycle and takes up to long minutes to finish. Can anyone help me to understand why this is happening? and how to resolve it?
Comment: I haven't used or defined HttpMessageHandler from my application. In Startup.cs, I used service.AddHttpClient() and inject HttpClient from controller's constructor
Comment: Why two minutes? Timestamps show not even a second change and the message itselfs says it takes 0.0076ms(!).
Comment: @Christian.K - I have just added two lines for example. This happens continuously. Editing the post.
Comment: Could you please tell me how you use the HttpMessageHandler inside your application?
Comment: ya i'm having the same issue. the remaining count keeps climbing too. i register httpClient in startup.cs as a named client. I inject httpClientFactory into a typed client. the http requests use the factory to create the named client using CreateClient("name"). then the result client is used via using client.GetAsync() and the typed client is injected into the controller and a background service. the background service is logging these cleanup logs. seems like message handlers not getting released.
Comment: I'm have some problem (
Comment: same problem here, anyone found a solution?
Comment: @advapi -Please check my answer post
Answer: After searching a bit, I found that it's actually a log generated during Http cleanup cycle from .net. It's actually not a problem, rather some helpful logs.

The HttpMessageHandler class in .NET uses connection pooling to
improve performance when making multiple HTTP requests to the same
endpoint. When a request is made, the HttpMessageHandler creates a new
HttpClientHandler and HttpClient instance, and adds them to the
connection pool.
After the request is completed, the HttpMessageHandler instance will
release the HttpClient and HttpClientHandler instances back to the
connection pool. This process is known as cleanup.
You may see logs related to the cleanup cycle because some logging
frameworks will log whenever an object is disposed or finalized, which
happens during the cleanup process. These logs can be useful for
debugging or performance analysis, but they can also be noisy and
clutter up your logs.
If you are seeing an excessive number of cleanup cycle logs, it could
be a sign of a performance or resource usage issue. For example, if
you are creating and disposing of HttpMessageHandler instances too
frequently, you may be putting unnecessary strain on the connection
pool and causing excessive cleanup cycles. In that case, you may want
to consider reusing HttpMessageHandler instances or optimizing your
usage patterns to reduce the number of requests made.

HttpMessageHandler cleanup cycle


Can I easily export content?

Question: Let's say I have a Drupal 7 website, with 3 taxonomies and 3 articles.
<code> - Cars
   - Sport
     - Porshe
 - Family
   - Taurus
 - SUV
   - Navigator
</code>
No modules, no nothing, just this content and taxonomies.
Is is it a fairly simple process?
Answer: If you have nothing but that, yes, Drupal core migrate and migrate_drupal_ui module will easily do this.

Can I easily export content?


Limit Change to Read More Link in Node Teaser to One Content Type

Question: Building on this answer:
<code>/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#title'] = t('Read more custom text');
    }
}
</code>
does anyone know how to build the if statement to further limit the change in the read more link to a particular content type? I'm working in Drupal 8, not 7.
Answer: Add following to your THEMENAME.theme file
<code>/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function THEMENAME_preprocess_node(&$variables) {
    // ...
    if ($variables['teaser']) {
    $node_type = &drupal_static('node_type');
    $node_type = $variables['node']->getType();
  }
}

/**
 * Implements hook_preprocess_links().
 */
function THEMENAME_preprocess_links(&$variables) {
  $node_type = &drupal_static('node_type');
    if (isset($variables['links']['node-readmore'])) {
        // Change link title according to machine name of node_type
        if ($node_type == 'article') {
            $variables['links']['node-readmore']['link']['#title'] = t('Custom Text');
        }
    }
}
</code>
Clear Cache.
Answer: I was able to make this work by getting the bundle from the URL object that's part of the link:
<code>function THEMENAME_preprocess_links(&$variables) {
  if (isset($variables['links']) && (isset($variables['links']['node-readmore'])) && (isset($variables['links']['node-readmore']['link'])) && (isset($variables['links']['node-readmore']['link']['#url']))) {
    if ($entity = $variables['links']['node-readmore']['link']['#url']->getOption('entity')) {
      if (($bundle = $entity->bundle()) && ($bundle == 'article')) $variables['links']['node-readmore']['link']['#title'] = t('Read the article');
    }
  }
}
</code>


Equivalent definitions of linear dependence

Question: Say that I have a vector space $V$ and vectors $v_1, v_2, v_3$ which are linearly dependent. The definition of linear dependence is that I can find coefficients $a_1, a_2, a_3 \in F$, not all zero, so that
$$
a_1 v_1 + a_2 v_2 + a_3 v_3 = 0.
$$
Is this definition equivalent to the assertion that I can write any of these $v_i$ in terms of the other two?
If the $a_i$ is non-zero, this is straightforward to me. Say $a_1 \neq 0$. Then I subtract $a_1 v_1$ from both sides, divide by $a_1$, and rename the coefficients. In particular, I'd have
$$
v_1 = - \frac{a_2}{a_1} v_1 - \frac{a_3}{a_1} v_3,
$$
and I can define $b_1 = - \frac{a_2}{a_1}$ and $b_2 = - \frac{a_3}{a_1}$. Then I have
$$
v_1 = b_1 v_1 + b_2 v_3.
$$
If $a_1 \neq 0$, I'm not convinced that I can do this.
Let's say, for example, that $v_1$ and $v_2$ are linearly independent, but upon adding $v_3$, I get a linearly dependent set. The only non-zero coefficient would have to be $v_3$, so I should only be able to write $v_3$ in terms of $v_1$ and $v_2$.
Is there a more general statement of the equivalence?
Comment: "I can write any of the vectors in terms of the other two" implies linear dependence but is not equivalent to it. For example, $(1,0)$, $(2,0)$, and $(0,1)$ are linearly dependent, but you cannot write the third vector in terms of the other two. What you can say is that at least one of the vectors can be written as a linear combination of the remaining ones. And it may be exactly one: e.g., $(1,0)$, $(0,1)$, $(0,0)$.
Comment: You can also say that a sequence of vectors is linearly dependent if and only if one vector i. the sequence is a linear combination of the previous ones. But you cannot guarantee they *all* are.
Answer: Your idea does not work.  To visualize an example, consider three vectors in the $x$-$y$ plane (three vectors in a two-dimensional space necessarily constitute a linearly dependent set), and then add a fourth vector parallel to the $z$-axis.  There is no way to express the fourth vector as a linear combination of the first three, but the set of four vectors is linearly dependent.  In fact, the only time you can express $v_1$ as a linear combination of the remaining vectors of your set is precisely when there is a linear combination summing to $0$ in which $a_1 \neq 0$.
You're asking whether $v_1 \in \operatorname{span} \{v_2, \ldots, v_n \}$.  If it is, then you can express $v_1$ as a linear combination of the remaining vectors.  Otherwise, you can't.  In fact, that's the definition of span.  Your idea works, however, if you prove that $v_1$ is an element of a minimal linearly dependent set (i.e., no proper subset is linearly dependent).
By the way, you should get in the habit of thinking about sets of vectors, rather than individual vectors, being linearly dependent or linearly independent.  It's technically correct and will probably help keep you from going astray as you think about these issues.


Recovering linear regression values by given coefficients in R

Question: This is my exam preparation, which will be held completely in R. Teacher said that similar tasks will be there with very limited amount of time given for solving it. Here I need to recover linear regression values (i.e., where are a-i missing values) having only this R output. I don't have the input data so I can't just copy the command and reproduce the result.

My question is how can I make it using R? Are there any specific commands? Or could it be done only manually? If it is possible only by manual calculation than please explain how to do it more effectively.
Please, describe it in detail.
Thank you so much for your help and deep explanation.
Comment: @Tim "How can I make it using R" sounds exactly like a software question. If that question I quoted is not asking for R commands it needs to be reworded so it doesn't read like that's what it's asking for.
Comment: Please add `[self-study]` tag and check https://stats.stackexchange.com/tags/self-study/info
Comment: Welcome to CV! Software questions are generally off-topic here—you may have more luck on StackOverflow.
Comment: Here's a hint `t` = `Estimate`/`Std. Error` You're welcome
Comment: @SeanEaster this is **not a software question** and it is **on-topic**, it asks about strictly statistics stuff. I do not understand the two votes for moving it to SO. What is the *programming* issue in this question that makes it suitable for SO? This is strictly about understanding regression, Wald test, F test etc.
Comment: @Glen_b but the question is generally about interpreting R's output and if you can calculate the values by hand on if you need R for it...
Comment: @Tim I can't speak for the other voter, but I at least interpreted the question's focus as reproducing the example output. Though, having now reread the first paragraph, I take your point. I'd second Glen_b's comment on rewording.
Answer: Since this seems to be a self-study question let me give you some hints. First, do you know what the columns in your output mean? Estimate is $\beta$ parameter, Std. Error is standard error and t value is $t$-value (or standardized parameter). Hypothesis tests are conducted using Wald test, i.e. $\beta/\mathrm{SE}(\beta)$. Knowing all this you can easily compute the values (a)-(g). As you can notice from column name Pr(>|t|) it is a probability from $t$-distribution, so knowing the previous values you can read the values from statistical tables for $t$-distribution or compute using appropriate R function. As about (i), you know the adjusted $R^2$, so you have just to revert the adjustment. By the way, it would be probably good idea to check in your handbook information about degrees of freedom in multiple regression and ANOVA (generally for the $F$ test) since this information may be helpful. See also this thread that also describes the lm output.
Comment: @RLearnsMath no need to thank. If you find some answer helpful in here you can upvote it (the upward arrow) or accept it (the "v" button) -- you can upvote multiple answers and accept only a single one. Unfortunately, you can upvote only after gaining some reputation. See https://stats.stackexchange.com/tour and welcome on our site!
Comment: Yes but how will I figure out the amount of observation in the data set? By manually computing each variable?
Comment: @RLearnsMath have a closer look at Tim's last sentence.
Comment: Yes but I can do nothing with ANOVA just because I don't have sample size of the given data.
Comment: Knowing how degrees of freedom are calculated you can easily compute it from DF.
Comment: @RLearnsMath I edited and added two more links, I am sure they will help you to understand how to interpret degrees of freedom and how to use them.


How to create a custom exclude validation rule in Laravel

Question: I would like to create a custom rule that excludes an attribute under some condition, the only ways I could think about are:

manually verify the condition in the FormRequest and add the 'exclude' rule if my condition is ture (which is, imo, not so elegant)
(I'm not sure if this will work/ won't have side effects) create a custom validation rule that will remove the attribute from the request (request->remove($attribute)) if the condition is true.
Is there any better way to do this ?

I couldn't find the implementation of any of the exclude rules either.
Comment: This is a bit vague to to point where i'm thinking it doesn't sound like a job for validation but rather a simple if check.
Comment: yeah but wondering if I can create a custom rule for that... something like new ExcludeWhenMySoComplicatedConditionIstrue
Comment: You can create custom validation rules by following the docs found here [Laravel | Custom Validation Rules](https://laravel.com/docs/8.x/validation#custom-validation-rules). But seeing as how you have not defined any parameters for your question I am not sure how to answer it. I believe you should also look into [Laravel | Available Validation Rules](https://laravel.com/docs/8.x/validation#available-validation-rules) to look for the conditional logic you need.
Answer: This is a vague answer to match your vague question, but it is easily done with conditional complex validation. Use the withValidator() method to access the validator instance before the rules are applied.
// assuming we're inside a FormRequest
public function withValidator($validator)
{
    $validator->sometimes(
        'some_field',
        'required|string|max64',
        fn ($data) => $data->some_other_field !== 1234
    );
}

First argument to sometimes() is the field you want to conditionally validate; the second is the rules you want to apply; and the third is a callback. The callback is passed the request data; if it returns true, the rules will be applied.
Comment: this is exactly what I was looking for, thank you ! I have 2 questions though:
1- do I have to use it inside withValidator instead of just using $this->validator inside rules() method ?
2- how is the 'exclude' rule implemented ? is it something like $this->request->remove('attribute') ?
Comment: I haven't tried accessing a validator instance within the `rules()` method, but there is a protected method `FormRequest::getValidatorInstance()` that's probably safer than just trying to access the property. The `exclude` rule doesn't remove the item from the request, just from the `FormRequest::validated()` return.
Comment: Ah thank you! any idea how to remove an attribute from validated data manually ?
Comment: `FormRequest::validated()` returns a simple array; it's easy enough to remove an element with `unset()`.
Comment: ah ok thank you !
Answer: There are lot of ways to exclude a validation rule based on conditions.
You can use exclude_if, exclude_unless and exclude_without.
Suppose you want to exclude a field validation if its another field's value is null, then you can use
['field1' => 'exclude_if:field2,null|<validation rules for field1>']

Again suppose you want to exclude a field validation unless the other value is not equal to 3, then use,
['field1' => 'exclude_unless:field2,==,3|<validation rules for field1>']

Comment: thank you for your answer, but I was looking for something for more complex conditions and @miken32 answer answers it well.
Answer: I've just found out that since Laravel 8.55 there is the method 'when' in the Rule object that you can use inside your rules() method as follow to exclude an attribute:
Rule::when(MyCallBackThatReturnsABoolean, [/*RulesIfCallBackReturnsTrue*/], [/*RulesIfCallBackReturnsFalse*/])

For some reason, I can't find the method in the documentation.
for example to exclude an attribute if the condition foo==bar is false I could do:
Rule::when(function() use(foo,bar) { return foo===bar }, ['required', 'string'], ['exclude'])

Pull requests here and here
Example of usage here


How can I simulate overriding a parent function (not hiding) in c++?

Question: From reading this answer (Is it possible to override a function in C++ child class without using virtual keyword to the function in parent class which is abstract?) it is apparent that one can not override a parent function from a child class.
Nevertheless, I need something that functions like this.  Here's a non functional setup that describes what I'm trying to do.
class Parent {
public:
  Graph createGraph() {
    return new Graph([this](float x){
        return this->getY(x);
    });
  }

  float getY(float x) {
    return sin(x);
  }
}

.
class Child: public Parent {
public:
  float getY(float x) {
    return x * x;
  }
}

The important bits of my setup are that I have a parent class which has a function that consistently references a function that is often overloaded by child classes.  Coming from Java/Javascript land, my approach would be to do what you see above, but it appears I'm thinking about this incorrectly for c++.
How can I simulate (ie get relatively similar functionality) to this form of overriding?
I know that by not being DRY I could copy/paset createGraph into both, and it would work.  And if that's the way an experienced c++ dev would do it, than it's good enough for me.  But right now, I'm looking for a way to approach this problem that is as DRY as my more java-like way.
EDIT:  it would appear the core issue here is that I misunderstood what virtual does, assuming it meant there could be no definition of the function in the parent class (similar to abstract functions in other languages).  That is not the case, virtual appears to do something else which allows for abstract classes, but does not necessitate them.
Comment: `similar to abstract functions in other languages` >> In c++, true abstract functions are called "pure virtual functions", regular virtual functions can have default implementations.
Comment: Can you explain in what way making `getY` virtual does not accomplish what you need?
Answer: use CRTP pattern. https://gcc.godbolt.org/z/J_N5Y_
void sink(int);
template<class ChildT>
struct Parent {
    void doStuff(){
        sink(
            static_cast<ChildT*>(this)->getY()
            );
    }
    int getY() {
        return 42;
    }
};
struct Child : Parent<Child> {
    int getY() {
        return 43;
    }
};
struct Child2 : Parent<Child2> {
//Does not want to customize, default is fine.
};
void foo() {
    Child c;
    c.doStuff(); # passes 43
    Child2 c2;
    c2.doStuff(); # passes 42
}

Answer: in the parent class you should make the functions you wanna override as virtual eg:
 class Parent{
 virtual float getY(float x) {
    return sin(x);
  }}

Answer: Not sure what you are looking for that has not already been provided in the link you gave, but this is how you would implement overriding in C++.
class Parent
{
public:
    virtual ~Parent() = default;

    Graph createGraph(float x)
    {
        return Graph(getY(x));
    }

    virtual float getY(float x) const
    {
        return sin(x);
    }
};

class Child: public Parent
{
public:
    float getY(float x) const override
    {
        return x * x;
    }
};

int main()
{
    // Play around here with creating a Parent instead of a Child
    //    and/or taking away the virtual keyword to learn how this works
    std::unique_ptr<Parent> thingy = std::make_unique<Child>();
    thingy->createGraph(1.0f);
}

Comment: @SephReed -- since you mentioned Java, the key here is that in Java **all** functions that aren't marked "final" are virtual. In C++ you have to say that you want a function to be virtual.
Answer: How work function call:
struct Parent{
  virtual void foo(){} // Func(1)
  void call(){
    this->foo();         // (A) call final overrider
    this->Parent::foo(); // (B) call Parent::foo
    }
  };

struct Derived:Parent{
  void foo() override {} // Func(2)
  };

void test(){
  Parent parent; //final overrider of foo is Func(1)
  Derived derived1; //final overrider of foo is Func(2)
  Parent& derived2 = derived; //final overrider of foo is Func(2).

  parent.call()//  At (A) call => Func(1)
               //  At (B) call => Func(1)

  derived1.call()  // At (A) call => Func(2)
                   // At (B) call => Func(1)

  derived2.call()  // At (A) call => Func(2)
                   // At (B) call => Func(1)


nginx How to rewrite all urls except few having specified extensions?

Question: i am trying to convert rewrite rules from .htaccess files to nginx config. as a part of moving site to NGINX webserver.
here are rewrite rules from .htaccess file
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !\.php$
RewriteCond %{REQUEST_URI} !\.gif$
RewriteCond %{REQUEST_URI} !\.jp?g$
RewriteCond %{REQUEST_URI} !\.png$
RewriteCond %{REQUEST_URI} !\.css$
RewriteCond %{REQUEST_URI} !\.js$
RewriteCond %{REQUEST_URI} !\.html$
RewriteCond %{REQUEST_URI} !\.xhtml$
RewriteCond %{REQUEST_URI} !\.htm$
RewriteCond %{REQUEST_URI} !\.ico$

RewriteRule (.*) index.php [L]
RewriteRule (.*).html index.php [L]

my current nginx config.
server {
    listen       80;
    server_name  example.com;

    root   /usr/share/nginx/html;

    location / {
        index  index.php index.html index.htm;
    }

    location ~ \.(php)$ {
        try_files $uri =404;
        root           /usr/share/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location !~* .(css|js|html|htm|xhtml|php|png|gif|ico|jpg|jpeg)$ {
      # Matches requests ending in png, gif, ico, jpg or jpeg.
        rewrite ^(.*)$ /index.php break;
        rewrite (.*).html /index.php break;
    }

}

home page is working but internal site links are giving 404.
so far i have tried many rewrite rules like these.
if ( $uri  ~ ^/(?!(\.css|\.js|\.html|\.htm|\.xhtml|\.php|\.png|\.gif|\.ico|\.jpg|\.jpeg))) {
    rewrite ^/(.*)$ /index.php break;
}

but sometimes, internal link works, while redirecting all static files like .css,.js to home page,
and sometime i can't access /administrator/ of my site, it redirects to the home page.
how can i replicate the .htaccess rewrite rules to nginx ?
Answer: To me this looks like a standard front-controller pattern. In nginx, it is implemented like this:
server {
    listen       80;
    server_name  example.com;

    root   /usr/share/nginx/html;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.(php)$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

The logic here is that it first tries to find if the requested resource exists as a file or a directory. If it exists, it is returned to the client. Otherwise the request is passed to the PHP script, which then determines the content to be returned to the client.
Comment: I tried above and it gave me 403 forbidden, in logs it showed *720 directory index of "/usr/share/nginx/html/" is forbidden, so i added         index  index.php; after try_files inside location / and now its working fine., thanks


Cone Theorem Step 3

Question: I'm reading the proof of the cone theorem from Koll'ar-Mori and I find step 3 to be very unclear. In particular below is a simple proof of this step which must be wrong somehow. I am wondering where I went wrong.
The setup for this step is that we have the closed cone of curves $\overline{NE}$ and we define a closed convex(?) subcone $W = \overline{\overline{NE}_{K \geq 0} + \sum_{\dim F_L = 1} F_L}$ where we define $F_L = L^\perp \cap \overline{NE}$ where $L$ is a nef divisor, and $K = K_X + \Delta$ is the log canonical divisor of some log pair $(X, \Delta)$ (ie. $X$ is normal and $K_X + \Delta$ is $\mathbb{Q}$-Cartier). It is claimed in the book that $W = \overline{NE}$.
But isn't $W$ a closed convex subcone? Then, we know that it is equal to the convex hull of its extremal rays, so to show it is all of $\overline{NE}$, it would seem sufficient to show that it contains all of the extremal rays of $\overline{NE}$.
But then an extremal ray of $\overline{NE}$ is nothing but a one-dimensional face of the cone $\overline{NE}$, and faces are all of the form $L^\perp \cap \overline{NE}$ where $L \in \overline{NE}^\vee = \operatorname{Nef}$ is a nef divisor. But then, this means that all the extremal rays of $\overline{NE}$ are all of the form $F_L$, so they are all contained in $\overline{NE}_{K \geq 0} + \sum_{\dim F_L = 1} F_L$ before even passing to the closure, so $\overline{NE} \subset W$ as required.
What is wrong with this argument? Surely there has to be something I am misunderstanding as it avoids a complicated argument in the book. I suspect it's wrong somehow to assume that $W$ is convex but it seems clear that it is.
Thanks!
EDIT: It is also assumed in the book that $(X, \Delta)$ is a klt pair, but I don't think this assumption is relevant in this step. I may be wrong though, so I wanted to mention it here ration than including it in the main body.
Comment: I think the point of this step is that the $L$ over which the sum is taken are *integral* Cartier divisors. (Look at the statement of Theorem 3.15: the $\xi_i$ are supposed to be elements of $N_{\mathbb Z}$.) Your statement that "faces are all of the form.." is true, but it is not obvious a priori why for a face in the $K \geq 0$ halfspace, we can choose the corresponding $L$ to be integral.
Comment: Ah this completely clears it up @LazzaroCampeotti. I think I understand this step now. If you'd like you can copy this comment into an answer and I would accept.
Comment: OK done, glad it helped.
Answer: I think the point of this step is that the $L$ over which the sum is taken are integral Cartier divisors. (Look at the statement of Theorem 3.15: the $\xi_i$ are supposed to be elements of $N_{\mathbb Z}$.) Your statement that "faces are all of the form.." is true, but it is not obvious a priori why for a given face in the $K \geq 0$ halfspace, we can choose the corresponding
$L$ to be integral.

Cone Theorem Step 3


JQuery Multiple selectors, $(this) reference?

Question: given the following
$("#identifier div:first, #idetifier2").fadeOut(300,function() {
  // I need to reference just the '#identifier div:first' element
  // however $(this) will grab both selectors
});

Is there a better way to go about this other than just calling $("#identifier div:first") again?
Comment: **this** referes to the current element. Since your selector ends up finding multiple items, it applies the **fadeOut** function to each one. What are you trying to do exactly?
Comment: fade out two elements, work with them separately then fade them back in. I can achieve this in a different way, that I know. I am however curious as to how I would do it in this manor.
Answer: No, it'll call the function for each handle separately.
The comma in your selector is equivalent to saying:
$("#identifier div:first").fadeOut(300,function() {
  // $(this) -> '#identifier div:first'
  });

$("#idetifier2").fadeOut(300,function() {
   // $(this) -> '#identifier2'
});

You can check by saying (untested):
$("#identifier div:first, #idetifier2").fadeOut(300,function() {
  if($(this).is("#identifier div:first")  {
     // do something
  }
});

However, if you want to do different things (as what seems from your post), its better to attach them separately.
Answer: What many people don't seem to realize in jQuery is that when there are multiple matched selectors, whatever functions are after the selector list will be called separately one at a time on each individual selector.
So $("#identifier div:first, #identifier2") will separately match both:
$("#identifier div:first")
and
$("#identifier2")

And, will call the specified fadeOut function and it's handler separately for each match.  That means each handler will have it's own this value set to the match the matched selector.
Internally inside of jQuery, there's a loop like this pseudo code that iterates through all the returned selector matches and calls the next function in the chain for each one:
for (var i = 0; i < matches.length; i++) {
    jQuery["fadeOut"].call(matches[i], duration, easing, fn);
}

If you want separate code to be used for the two different matches, then it might be better to just use two separate jQuery statements:
$("#identifier div:first").fadeOut(300,function() {
    // do stuff for #identifier div:first
});

$("#identifier2").fadeOut(300,function() {
    // do stuff for #identifier2
});

If you have a lot of code in the block and it's mostly the same, then you can also branch within one block of common code:
$("#identifier div:first, #identifier2").fadeOut(300,function() {
    if (this.id != "identifier2") {
        // execute code that only applies to the #identifier match
    }
    // execute rest of common code
});

Comment: He's not checking for #identifier but the first div inside it.
Comment: @Mrchief - As I said in my answer, if you intend to run completely different code for each match, then use separate jQuery calls for each match and give each of them their own separate custom function block.  It's the programmer's tradeoff when `if` statements in a common block of code is easier or not than just using separate code blocks for each match.  Or factor the common code into a function that you can call from each separate handler.
Comment: I agree. I was hinting at `.is()` where you can easily do one little thing with just one and do common things with rest.
Answer: Just check about which ID you're currently processing in $(this)
if(this.id == "identifier"){ //your code goes here }

Comment: The ID does not include the hash symbol.
Comment: `this.id` is even shorter (and faster).
Comment: This will never pass, since he is fading out the first div in `#identifier`, not the identifier itself.
Comment: How would it check if its `div:first`?


Prove that cardinality of linearly independent set is less than or equal to spanning set

Question: My professor did this proof in class and I was not able to copy down the proof. I managed to get half of it but I don't quite understand how to continue.
He essentially took a basis and kept adding vectors from a linearly independent set and removing one from that set. I don't know what to do next. Thanks in advance.
Comment: Are you talking about finite-dimensional vector spaces? I believe that the proof is very different if you don't require that the vector space be finite-dimensional.
Comment: Can you post the part of the proof that you did manage to copy down, so that we can see where you are stuck?
Answer: I think your professor actually proved Steinitz' exchange lemma, or something very close to this lemma, which I'll quote:

Suppose $v_1,\dots, v_m$ be a set of linearly independent vectors and $S=\{w_1,\dots, w_n\}$ a spanning set of a vector space $V$. Then:

$m\le n$;
There exists a reordering of $S$ such that the set $\{v_1,\dots,v_m,v_{m+1},\dots,v_n\}$  spans $V$.

In other words, up to a reordering of $S$, we can replace the first $m$ vectors in the spanning set with the vectors in the linearly independent set.
The proof consists in proving by induction that for all $k\;(0\le k\le m)$, up to a reordering of $S$, the set
$$\{v_1,\dots,v_k,w_{k+1},\dots,w_m\}$$
is a spanning set for $V$.
A hint for the inductive step: if the assertion is proved for a given $k$, the vector $v_{k+1}$ can be written as
$$v_{k+1}=\sum_{i=1}^k \lambda_iv_i+\sum_{i=k+1}^n\lambda_iw_i.$$
Observe that, since the first set is linearly independent, at least $1$ $\lambda_i,\;i\ge k+1$ is non zero. Up to a reordering of $S$, we may suppose it is $\lambda_{k+1}$,and so you can check that $w_{k+1}$ is in the span of
$\{v_1,\dots, v_{k+1},w_{k+2},\dots,w_n\}$.


Positioning table scrollbar on my body element

Question: I'd like to implement a scrollbar on my table builds with DIVS... I'd like to add a scroll-y bar only for my body element...
It works for the entire table but not for my body element...
JSFiddle : Click here
My code :

.scroll{
    height: 200px;
    overflow-y: scroll;
}

.table{
    display: table;
    table-layout: fixed;
}

.header{
    display: table-header-group;
    background-color: green;
}

.header .row{
    display: table-row;
}

.header .row .cell{
    display: table-cell;
}

.body{
    display: table-row-group;
    background-color: red;
}

.body .row{
    display: table-row;
}

.body .row .cell{
    display: table-cell;
}

some content here

Colonne

Colonne

Colonne

Colonne

Colonne

Colonne

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Answer: Try this:-

.scroll{
    height: 200px;

}

.table{
    display: table;
    table-layout: fixed;
}

.header{
    display: table-row;
    background-color: green;
}

.header .row{
    display: table-row;
}

.header .row .cell{
    display: table-cell;
}

.body{

    background-color: red;
    height:200px;
    overflow-y:auto;

}

.body .row{
    display: table-row;
}

.body .row .cell{
    display: table-cell;
}

some content here

Colonne

Colonne

Colonne

Colonne

Colonne

Colonne

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #1

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #2

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #3

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Ligne #4

Comment: The scroll-y works perfectly but if I modify the text content of a cell in the header, cells don't get the same width...
Comment: You have to set same width:- `.body .row .cell` , `.header .row .cell` try once.
Comment: Yes but I don't want to set the width... Because this is a feature for a table of XXXXXXXXXXX lines generated in Javascript...
Comment: Okay then try it:-.body {
    background-color: red;
    height: 200px;
    overflow: auto;
    width: 550px;
}
Comment: Doesn't work too... If I modify the text content of a column I get the same problem...


What is the most efficient way to update record(s) value when using SummingCombiner?

Question: I have a table with a SummingCombiner on minC and majC.  Every day I need to update the value for a small number of records.  What is the most efficient way to do so?
My current implementation is to create a new record with value set to amount to increase/decrease (new mutation w/Row,CF,CQ equal to existing record(s)).
Answer: Yes, the most efficient way to update the value is to insert a new record and let the SummingCombiner add the new value into the existing value. You probably also want to have the SummingCombiner configured on the scan scope, so that scans will see the updated value right away, before a major compaction has occurred.
Comment: Thanks for the feedback.  I read somewhere online that configuring the SummingCombiner on the scan scope could impact query performance.  You suggest I configure on all three(scan, minC, and maxC)?
Comment: Yes. If you only have a few records for each key, I wouldn't expect there to be a significant impact on query performance. Also, the query results will not be correct unless you configure the combiner on scan.


nginx php files being downloaded by the browser, not processed

Question: I've been hitting my head against the wall trying to figure this out.
I'm trying to add a /knowledge subdirectory which points to a wordpress blog. However nginx isn't processing the files, it's serving them to the browser to download.
Please help!
server {
    listen      80;
    listen   [::]:80;
    server_name domain.com;

    return 301 https://domain.com$request_uri;
 }

server {
    listen 443  ssl;
    server_name domain.com;

    ssl_certificate    /etc/ssl/domain_com-bundle.crt;
    ssl_certificate_key    /etc/ssl/domain_com.key;

    root /opt/domain.com/public/;

     location / {
        try_files $uri @backend;
      }

    location @backend {
      proxy_pass http://127.0.0.1:3030;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }

    #knowledge wordpress config

    location ^~ /knowledge {
        alias /opt/domainWordpress/;
        index index.php index.html index.htm;
        try_files $uri $uri/ knowledge/index.php?q=$uri&$args;
      }

      location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

Comment: Have you installed and configured PHP-FPM or similar to handle the PHP processing? You don't have any section in your Nginx config to catch PHP requests and forward them to a PHP backend.
Comment: hm. Yeah i've installed php-fpm. Do you know of a tutorial to set this up?
Answer: nginx process requests using a single location block. You should read on how nginx processes requests.
Your problem comes from the fact the location handling your URI (/knowledge[...]) differs from the on handling ones targeted at PHP (/[...].php I suppose).
Since you used the special ^~ location operator, regex location blocks are not being checked when selecting the properest one to server your requests, if this block matches. As a consequence of your request being served by this block (longest prefix), it simply serves the files from disk, with the default MIME type having been configured.
You could try nesting location ~ \.php$ block inside location ^~ /knowledge block.


Repeatedly rolling a fair 6 sided die

Question: Suppose you repeatedly roll a fair 6 sided die. What is the probability that you obtain at least one 5 before the first 6?
Will this involve an infinite sum?
Comment: Call the chance you roll a $5$ before a $6$ as $x$.  What is the chance you roll a $6$ before a $5$?  And therefore...
Comment: I somehow got my answer as 1.
Comment: "At least one" $\equiv$ which will you roll first, a or b?
Comment: What are a and b here?
Comment: Well you can either observe the probability tree and sum all cases which will be a infinite geometric sum, or... use the trick @DavidG.Stork gave you to deduce the result right away (Hint: rolling $x$ before $y$ is equivalent as rolling $y$ before $x$ since the dice is fair and symmetric, and both events are opposite, so combining these two facts tells you... what?).
Answer: It is easier to calculate the complementary event, namely $A$, that is: the probability that you don't roll a five before the first six. Then this probability is an infinite sum, that is, the sum over $n$ that the probability that you get the first six in the $n$-th roll and no five in the previous rolls, namely the event $A_n$, i.e.:
$$
\Pr [A]= \sum_{n\geqslant 1}\Pr [A_n]=\sum_{n\geqslant 1}\left(\frac46\right)^{n-1}\frac16=\frac16\cdot \frac1{1-\frac46}=\frac12
$$
Then the probability that you want is $1-\Pr[A]=\frac12$.
Alternatively, following the comment of @David you can notice that the probability to get a five before a six is the same probability to get a six before a five, and each one is the complementary event of each other.
Answer: Rolling a 5 or a 6 are equally likely. In this very simple joint probability space, that makes the events of rolling a 5 or 6 essentially interchangeable. You could put a sticker on the 5 and 6 sides that read "6" and "5" respectively, and nothing at all would change about your experiment. Because of this symmetry, the chance of rolling a 5 before a 6 must be the same as rolling a 6 before a 5, which is therefore 50%.
Answer: If you roll anything other than a $5$ or a $6$ then the process effectively starts over, with no effect whatsoever on the probability of rolling a $5$ before a $6$. On the other hand, if you roll a $5$, you might as well stop rolling since you know that, whenever you do manage to roll a $6$, it will have happened after rolling a $5$. We therefore only really care about a die roll that stops the process, i.e., if we roll either a $5$ or a $6$. These are equiprobable, so...

Repeatedly rolling a fair 6 sided die


Computing anti-derivative of this function

Question: Consider the function on the real numbers $f(x):=\arctan(\frac x{\sqrt{1+x^4}})$. One can easily find that $f'(x)=\frac{1-x^4}{(1+x^2+x^4)\sqrt{1+x^4}}$.
I was wondering how one could compute the anti-derivative of $f'$ without further knowledge about $f$.
That is, how can one compute $$\int \frac{1-x^4}{(1+x^2+x^4)\sqrt{1+x^4}} \, \mathrm dx \text{ ?}$$
A small remark: I chose this function $f'$ as an example of a function that Wolfram Alpha is not able to integrate.
Answer: Hint:
Set $x^2=y,2x\ dx= dy$  for $x\ge0$
$$I=\int\dfrac{1-x^4}{(1+x^2+x^4)\sqrt{1+x^4}}dx=\int\dfrac{\dfrac1{x^4}-1}{\left(\dfrac1{x^2}+1+x^2\right)\sqrt{x^2+\dfrac1{x^2}}}x\ dx$$
$$2I=\int\dfrac{\dfrac1{y^2}-1}{\left(y+1+\dfrac1y\right)\sqrt{y+\dfrac1y}}dy$$
Now $\sqrt{y+\dfrac1y}=u\implies du=?, y+\dfrac1y=u^2$
Can you take it from here?
Comment: I remember a similar question from class 12 RD Sharma :) (+1)
Comment: That works out so nicely; How did you come up with this so fast?
Comment: @MaximilianJanisch, $$\dfrac x{\sqrt{x^4+1}}=\dfrac1{\sqrt{x^2+\dfrac1{x^2}}}$$ for $x>0$


How to have plain docs mixed in with React Styleguidist

Question: I'd like to document other functions and parts of my code base with markdown and have them parsed and displayed in a different section of my documentation. How can I do this?
/**
 * Merge route into the global application state
 */
export const reducer = (state = initialState, action) => {

Importing them directly into styleguide.config.js results in the entire file being parsed as text.
Answer: Generate Markdown documentation using tools like documentation.js, and then include those files as sections into Styleguidist:
module.exports = {
  sections: [
    {
      name: 'Some other API',
      content: 'docs/generated-file.md'
    },
    {
      name: 'Components',
      components: 'lib/components/**/*.js'
    }
  ]
}


Any irreducible representation of a $p$-group over a field of characteristic $p$ is trivial.

Question: In general, we know that if $G$ is a finite group and $K$ is a field, then $K[G]$ (the group algebra) is semisimple whenever $\operatorname{char}(K)$ does not divide the order of $G$.  However, this result does not hold when we have a $p$-group and a finite field of characteristic $p$.

How would I go about showing that an irreducible representation of a $p$-group $G$ over a field $K$ of characteristic $p$ must be the trivial representation?

It seems like this would perhaps entail some sort of application of Maschke's Theorem to get a contradiction.   I know that $|G| = \sum_i \operatorname{dim}(V_i)^2$, where $V_i$ is an irreducible representation. But it seems like that does not help me much here.
Any thoughts as to how to approach this question?
Comment: $|G|=\sum_i \dim(V_i)^2$ does not hold in general. As far as I know, it is true for semisimple algebra over an algebraically closed field.
Comment: Here's another proof: https://math.stackexchange.com/questions/1211369/irreducible-representation-of-a-p-group-over-field-of-characteristic-p-is-tr?rq=1
Answer: Hint. Let $G$ act on the representation (minus $0$) and use an orbit counting argument to find a copy of the trivial representation.

 Let $V$ be a nontrivial irreducible representation.  Note that $V$ must be finite dimensional since $G$ is finite.  Write $V^\circ = V\setminus\{0\}$ and let $G$ act on $V^\circ$.  By orbit stabilizer, $\left| \mathcal{O}_x \right|$ divides $|G|$ for any $x\in V^\circ$, so all $G$-orbits have prime power (more precisely, power of $p$) size.  Since these all need to sum to $\left|V^\circ\right|=p^n-1$, there is at least one orbit of size $1$.  This orbit is a $G$-invariant one-dimensional subspace, and thus is an isomorphic copy of the trivial representation.  But this contradicts that $V$ is irreducible.
Comment: @Alexander Gruber I dont understand one thing. Why do you say that $|V^{\circ}|=p^n-1$?
Comment: @alexander You're assuming $K = \mathbb{F}_p$, but he only said $K$ is of characteristic $p$.
Comment: @Eric, see the [comment](http://math.stackexchange.com/questions/33935/representations-of-a-cyclic-group-of-order-p-over-a-field-of-characteristic-p#comment73248_33942) by Mariano on this. $K$ contains $\mathbb{F}_p$ as the prime subfield, so we can define
$$W=\mathrm{Span}_{\mathbb{F}_p}(\mathcal{O}(v))$$
where $\mathcal{O}(v)$ is the orbit of some non-zero $v\in V$. Such $W$, as a _subset_ of $V$, is $G$-invariant, and so it is a representation of $G$ over $\mathbb{F}_p$, but it is _not_ necessarily a subspace of $V$, and therefore might not be a sub-rep. I'm stuck here. Thoughts?
Comment: A very clean method of thinking of it.
Comment: OK, I think I [figured it out](http://math.stackexchange.com/questions/33935/representations-of-a-cyclic-group-of-order-p-over-a-field-of-characteristic-p#comment3393318_33942)
Comment: By the way, @doodle, you don't need a sub-representation, only a $G$-invariant set. The only arguments being used are the orbit-stabilizer theorem and Burnside's counting Lemma - both are for group actions on sets.
Comment: @doodle May I know how do you see that $W$ is a representation? If the action is $g.(\sum c_i(g_i.v)):=\sum c_i((gg_i).v)$, I could not see its well-defined-ness. Thanks.
Comment: @doodle Got it. Thanks!!!
Comment: How do you conclude that it is an isomorphic copy of the trivial representation from being a $G$-invariant one-dimensional subspace?
Answer: It is surprising to see that nobody mentioned a beautiful proof of a slightly more general statement presented in Serre's "Linear Representations of Finite Groups".
This is Proposition $26$ in $\S8.3$ of Serre's book:
Proposition 26. Let $V$ be a nonzero (not necessarily finite dimensional) vector space over a field $k$ of characteristic $p$ and let $\rho:G\to \mathrm{GL}(V)$ be a representation of a finite $p$-group $G$ on $V$. Then,  $V^G\neq 0$, i.e., there exists a nonzero vector $v\in V$ which is fixed by $\rho(g)$ for all $g\in G$.
Proof. Pick any $v\in V\setminus\{0\}$ and let $X$ denote the subgroup (which is just the $\mathbb{F}_p$-vector space) generated by $\{\rho(g)v\mid g\in G\}$. Then for some $n$, $X$ is an $n$-dimensional $\mathbb{F}_p$-vector space on which the finite $p$-group $G$ acts. Since $X$ is the disjoint union of all of its $G$-orbits (which is either a singleton when a representative is $G$-invariant, or a set whose cardinality is a positive power of $p$ otherwise, by the orbit-stabilizer theorem), we deduce that $|X^G| \equiv |X| = p^n \equiv 0 \pmod{p}$. Since $0\in X^G$, $p \leq |X^G| \leq |V^G|$. $\mbox{ }\blacksquare$