Video captions below video field

Question: I'm expanding my language learning site and need a bit of help if it's possible.
I am wanting to link to YouTube videos (that's easy). But I would like to have a captions field. As the video plays the captions would appear in the field. I need to do this so that the user can copy and paste the caption and there will be two lines of captioning "Language 1" and "Language 2." I might in the future add a second field below the captions that would give a grammar explanation to the caption being displayed as well.
The only thing I have found while searching around is: https://www.drupal.org/node/1927080 but it puts the captions into the video.
<code>+---------------------------------+
|                                 |
|              VIDEO              |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|           LANGUAGE 1            |
|                                 | <= Changes based on video time
|           LANGUAGE 2            |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|            GRAMMAR?             | <= Changes based on video time
|                                 |
+---------------------------------+
</code>
Answer: I have been unable to find any existing module to do this and would be quite surprised if one existed. You will very likely have to develop your own module.
Here is a brief rundown of how such a module might work:

Implement a new field type providing either a form for the user to create the subtitles or upload a subtitle file in one of the many subtitle formats. https://support.google.com/youtube/answer/2734698?hl=en
Parse the input from the form and store it. You'd likely want to store it as JSON or something else that will be easy to work with in JavaScript
Write code to pass the data to the browser
Use Javascript to update the Language 1 and Language 2 content to match the data in your stored subtitle file. You can use the YouTube API to get the current time of the video https://developers.google.com/youtube/iframe_api_reference#Playback_status

I think it would be a lot easier to just use YouTube to do this but I'm sure you've already thought of that.

Video captions below video field


How to send an email to the node author when a date is approaching?

Question: The user has created a node and has set a future date to be alerted of the approach of this date.
I want the user receive an email when the set date is approaching.
Making the user able to change the approaching time would be great.
Any sugestions?
Answer: Have you tested Rules, this is the module to do such actions based on events.
Here is a tutorial to help you with this: Publish content based on a CCK date field.
Also don't forget to enable the debugging feature of rules under admin/rules/settings.
Comment: Im trying it right now.

If I understood the way it works, I am going to need to add an action "Send email" and create a trigger that will run the action isnt it?
But I need to send the email with some information that are inside the node, and I'm having trouble creating the action "Send email" with these information.
Comment: This is correct.


Existe alguma diferença relevante entre "Programação orientada a objetos" e "Programação orientada a classes"?

Question: Estava lendo um post que o membro @Maniero indicou, e me deparei com uma resposta de um outro membro que me gerou mais dúvidas e resolvi pesquisar.
Na resposta estava a seguinte frase: "Programação orientada a objetos" e "programação orientada a classes", porém, fiz algumas pesquisas
e não encontrei conteúdo relevante para esclarecer essa dúvida.
Link da resposta acima onde extrai o texto: Qual a diferença entre uma classe e um objeto?
Link de pesquisa: https://pt.wikibooks.org/wiki/Programa%C3%A7%C3%A3o_Orientada_a_Objetos/Classes_e_Objetos
No Wikilivros, não ficou clara a explicação sobre o que é "Programação orientada a objetos" e o que é "Programação orientada a classes" .
Cada vez que procuro mais informação através de pesquisa, não sei definir qual seria mais relevante para o meu caso.
Alguém tem uma explicação melhor para contribuir?
Comment: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: Programação orientada a classes é um subtipo de programação orientada a objetos.
As linguagens que permitem o uso de programação orientada a objetos mais populares, como Java e C#, obrigam o desenvolvedor a definir seu código em classes. Isso estimula a compartimentalização do código e tem diversos benefícios que já foram discutidos exaustivamente em outras perguntas.
No entanto, o uso forçado de classes também traz limitações, que outras linguagens orientadas a objetos não têm. Um exemplo é Javascript. Essa linguagem é orientada a objetos, e orientada a protótipos - que são diferentes de classes. O conceito de classe nem existe em Javascript. Os comportamentos são herdados entre objetos, não entre tipos. Assim como o uso de classes, o uso de protótipos tem lá suas vantagens e limitações. Mas acredito que a análise comparativa é um tema para outra pergunta.
Mais detalhes sobre protótipos em O que é Protótipo Javascript?


Somar valores decimal mysql

Question: Fiz uma query que soma um campo decimal, só que estou tendo problema, pois quando eu coloco a clausula group by t1.id_sell ele me lista as vendas mas já não soma corretamente e sem a clausula soma correto mas só me retorna uma linha.
query:
SELECT Sum(t1.preco_sell) AS result_sum, t1.*, t2.name, t3.name_produto
FROM   tb_sell t1
       INNER JOIN tb_user t2
               ON t1.id_user = t2.id_user
       INNER JOIN tb_produtos t3
               ON t1.id_produto = t3.id_produto
WHERE  t1.status = 2
GROUP  BY t1.id_sell

Comment: Seria legal que você criasse tabelas com estrutura e conteúdo minimos que reproduzisse o problema e postasse junto à questão para facilitar o trabalho de quem se propõe responder.
Answer: O problema está no seu nos campos que você exibe no seu Select, no na sua junção no Group By
Caso você queria exibir a soma de todos os itens vendidos em uma nova coluna, o que você deve fazer é uma SubQuery para isso
SELECT t1.*, t2.name, t3.name_produto,
(SELECT Sum(preco_sell)
    FROM   tb_sell
    WHERE  status = 2
)AS result_sum
FROM   tb_sell t1
       INNER JOIN tb_user t2
               ON t1.id_user = t2.id_user
       INNER JOIN tb_produtos t3
               ON t1.id_produto = t3.id_produto
WHERE  t1.status = 2

Quando você manda exibir todos os itens de t1 a consulta não ira conseguir agrupar, já que todos os campos, provavelmente, tem valores diferentes e com isso não está retornando o que você deseja
Comment: Jeferson essa query tb nao deu certo :/
Comment: vc poderia informar o que vc realmente espera no retorno da query, junto com os campos
Comment: quero que me retorne a soma dos valores das vendas juntamente com todas as vendas apenas separada pela clausura where status = 2 (cod de vendido na aplicaçao)
Comment: esse eh so o principio, pois depois a intençao eh colocar uns filtros
Comment: No caso vc quer q mostre todas as informações da sua tabela de vendas e um campo ao lado com o total gerado de todas as suas vendas, sem ser agrupado por nd?
Comment: na vdd eu sou novo usando o group by jeferson entao pra mim eh tanto quanto novo ainda usar ela..entao to apanhando um pouco rs.. mas a intençao eh essa msm
Comment: No caso, o que vc precisa é de uma subquery que vai te retornar essa soma, qnd vc usa o `group by ` ele vai agrupar pelas seus campos que estão no select, então n tem como exibir essas 2 informações dessa maneira, vou editar a query e vc tenta com ela
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/56316/discussion-between-jeferson-almeida-and-flavio-domingos).

Somar valores decimal mysql


How to count the number of ways?

Question: Mark has $N$ days. Initially he is at position $(h1,0)$ on the X-axis. On each day he can go to the co-ordinates $(x+a,0)$ or $(x+b,0)$ or $(x+c,0) .$  where $(x,0)$ is his current position.
He can select any one of the choice he wants. Each day he can go to (+a , +b or +c) from his current position. At the N-th day, he has to reach the position $(h2,0)$. Count the number of ways in which Mark can reach $(h2,0)$ in N days.
Values of $N,h1,h2,a,b,c$ are large(co-ordinates and values of a,b,c can be negative as well, in some cases a=b or b=c or c=a or a=b=c)
My approach is:- At each day, I store the positions which he can reach on that particular day with the count(number of ways) to reach that position. I am using a map to do this. And this approach is not efficient.
Can somebody share a much more efficient approach ?
Can we derive some formula for this problem or a recurrence relation which can solve it efficiently ?
Example:-
N=3,h1=0,h2=6,a=1,b=2,c=3
Answer : -7(number of ways)
1st way:-(1+2+3)
2nd way:-(1+3+2)
3rd way:-(2+1+3)
4th way:-(2+3+1)
5th way:-(3+1+2)
6th way:-(3+2+1)
7th way:-(3+3+1)
Format:-(Choice on 1st day+Choice on 2nd day+Choice on 3rd day)
Also, $1<=N<=10^5$
Comment: Oh you're right, it is much closer to the coin-exchange problem, my bad. Except, again, the fixed number of days, which causes some cases to have no answers
Comment: Something deep inside me wants to scream "knapsack problem" (https://en.wikipedia.org/wiki/Knapsack_problem) So the only thing I can say is that the number you are looking for is going to be exponential in the number of days.
Also, could you show the 7 possibilities you have found for your example?
Comment: Oh, except that your constraints are much stricter than the knapsack problem (because you have an exact number of days to reach the destination, which the knapsack problem does not have), so sometimes you just won't have any solutions either. This means that there won't be any "simple" recurrence formula.
Comment: @Milloupe To me, it seemed like coin-exchange problem such that you also have to keep checking the number of coins(N). I've showed the 7-ways in my answer now
Comment: Well for starters, every integer $h2-h1$ that is not a multiple of $\gcd({a,b,c})$ cannot be expressed as their linear combination, let alone a combination that equals $h2-h1$ in $N$ days. If $a=b=c$ then it is trivial. The $a=b\lt c$ case could be simpler to look at first, then WLOG $a\lt b \lt c$. But as already discussed in comments, this is the [coin change problem](https://www.algorithmist.com/index.php/Coin_Change) with an additional restriction of using exactly $N$ coins total (Except also that you are allowing negative coins).
Comment: Can you write it as an answer with some code @Vepir
Answer: This is an algebraic approach to count the number of ways. We start with OP's example.

We consider $N=3,h_1=0,h_2=6,a=1,b=2$ and $c=3$.

Each day we can walk either $1,2$ or $3$ steps. We encode this as $x^{\color{blue}{1}}+x^{\color{blue}{2}}+x^{\color{blue}{3}}$
We do these walks in $N=3$ days and encode this as $(x^1+x^2+x^3)^{\color{blue}{3}}$.
Since we are interested in the number of ways to go length $h_2=6$ we are looking for $[x^{\color{blue}{6}}] (x^1+x^2+x^3)^3$ where $[x^k]$ denotes the coefficient of $x^k$.

We obtain
  \begin{align*}
\color{blue}{[x^6]\left(x+x^2+x^3\right)^3}&=[x^6]x^3\left(1+x+x^2\right)^3\\
&=[x^3]\sum_{j=0}^3\binom{3}{j}\left(x+x^2\right)^j\tag{1}\\
&=[x^3]\sum_{j=0}^3\binom{3}{j}x^j\left(1+x\right)^j\\
&=\sum_{j=0}^3\binom{3}{j}[x^{3-j}](1+x)^j\tag{2}\\
&=\sum_{j=0}^3\binom{3}{j}[x^{3-j}]\sum_{k=0}^j\binom{j}{k}x^k\\
&=\sum_{j=0}^3\binom{3}{j}\binom{j}{3-j}\tag{3}\\
&=\binom{3}{2}\binom{2}{1}+\binom{3}{3}\binom{3}{0}\tag{4}\\
&=3\cdot 2+1\cdot 1\\
&\,\,\color{blue}{=7}
\end{align*}
Comment:

In (1) we use the binomial theorem and apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$.
In (2) we again the rule as we did in (1).
In (3) we select the coefficient of $x^{3-j}$.
In (4) we note that only summands with $j\geq 2$ give a contribution since $\binom{p}{q}=0$ if $q>p\geq 0$.

The general case is similarly to the example above. As it is somewhat more technical it might be slightly more cumbersome.

We consider WLOG $h_1=0$, since the number of ways from $h_1$ to $h_2$ is the same as from $0$ to $h_2-h_1$. Here we consider only $0<a<b<c$. Other cases can be derived similarly.
We obtain
  \begin{align*}
\color{blue}{[x^{h_2}]}&\color{blue}{\left(x^a+x^b+x^c\right)^{N}}\\
&=[x^{h_2}]x^{aN}\left(1+x^{b-a}+x^{c-a}\right)^{N}\\
&=[x^{h_2-aN}]\sum_{j=0}^{N}\binom{N}{j}\left(x^{b-a}+x^{c-a}\right)^j[[h_2\geq aN]]\tag{5}\\
&=[x^{h_2-aN}]\sum_{j=0}^{N}\binom{N}{j}x^{(b-a)j}\left(1+x^{c-b}\right)^j[[h_2\geq aN]]\\
&=\sum_{j=0}^{\min\left\{N,\left\lfloor\frac{h_2-aN}{b-a}\right\rfloor\right\}}\binom{h_2}{j}[x^{h_2-aN-(b-a)j}]
\sum_{k=0}^j\binom{j}{k}x^{(c-b)k}[[h_2\geq aN]]\tag{6}\\
&\,\,\color{blue}{=\sum_{{j=0}\atop{h_2-aN-(b-a)j\mid c-b}}^{\min\left\{N,\left\lfloor\frac{h_2-aN}{b-a}\right\rfloor\right\}}\binom{N}{j}
\binom{j}{\frac{h_2-aN-(b-a)j}{c-b}}[[h_2\geq aN]]}\tag{7}\\
\end{align*}
Comment:

In (5) we work analogously to (1) and we use Iverson brackets since for non-zero summands we have to assure that $h_2\geq aN$.
In (6) we work analgously to (2). We also set the upper limit of the sum to a minimum to assure that $h_2-aN-(b-a)j\geq 0$.
In (7) we select the coefficient of $x^{h_2-aN-(b-a)j}$ by respecting that the exponent is a multiple of $c-b$.
Comment: @LutzL: Oh, yes, thanks for pointing at it. Corrected.
Comment: Any idea on a similar problem :- https://mathoverflow.net/questions/335521/how-to-guess-the-correct-prime-number

How to count the number of ways?


Making a Post request to a REST API from a WCF service in a transaction

Question: I am doing a series of work in a wcf service transaction.
1.Making a POST response to a rest api.
2.Processing POST req response and saving it in a db.
Above step 1 and step 2 are happening in a wcf transaction but as a result I have seen an issue where on having an exception step 2 doesn't get committed but step 1 gets completed creating inconsistencies.
I have seen way out to achieve this through saga pattern or 2PC but couldn't find any easy implementation or workaround.
PS : I NEED NOT TO ROLLBACK DATA FOR NOW JUST AVOID COMMITTING POST REQ TO REST API.
Currently I am handling this by making another patch request to rest api to revert the response received in CATCH BLOCK.
Answer: The bad news:
There is no 2PC over rest apis. Rest is by definition stateless, does not include envelopes for metadata to be used in a two phase commit world, so you are out of luck here.
SOAP on the other hand supports the WS-Atomic Transaction protocols, though I would suggest that you use some technology like WCF where all this is implemented already. (net core does not support it, so it .net framework for this).
The somewhat good news:
Eventual consistency to the rescue. The SAGA Pattern is one way to achieve this in the microservices world. In it's simplest form, eventual consistency could be something as trivial as the following:

Application 1 creates a DB row that described the action in Pending state
Application 1 makes the post to a url
The target api, creates an event with the result in a persistent way (on an event bus, a queue or even a database table that the Application 1 can access
Some service or background thread of Application 1 constantly reads or listens to that event bus for the api's results
Once it gets the result, it updates the row made on 1. It retries until possible. You can stop it at some point.

The negative of this approach, is that you need to manually intervene if 5 constantly fails. There are more complicated aspects involved (like compensating actions) but I'll leave this up to you for further study.
The other bad news
There is no out of the box implementation for eventual consistency :(
If you can switch the REST Api to a SOAP with WSAT protocol enabled, then you can have out of box distributed transactions.


Help translating the following PCA results into layman's terms?

Question: As a non-maths doctoral candidate, I would be absolutely thrilled to bits if anyone here might be willing to take a stab at translating the following PCA results into layman's terms.
There are only two sets of raw data: TOEIC test scores and DMIS stages.
Additionally, I also need to be able to state the significance, if any, of this PCA analysis (e.g. I have to answer the perennial dissertation question "so what?")
Lastly, I must assert that it was definitely not me who performed this PCA, but rather a friend who is conversant with SPSS.
Thank you in advance, even if you're not actually in a position to assist me:
<code>Communalities
    Initial Extraction
TOEIC   1.000   .546
DMIS    1.000   .546
Extraction Method: Principal Component Analysis.

Total Variance Explained
Component       Initial Eigenvalues                    Extraction Sums of Squared Loadings
           Total   % of Variance   Cumulative %   Total   % of Variance   Cumulative %
1          1.092      54.579         54.579       1.092      54.579         54.579
2           .908      45.421        100.000
Extraction Method: Principal Component Analysis.
</code>
Comment: If you don't mind, I'll add tag `self-study`, failing to find tag `friend-study` on wiki.
Answer: Initial communality of a variable is its variance, the diagonal element of the analysed matrix. In your case it is 1 for both variables because you analysed a correlation matrix (which is equivalent to saying that you analysed standardized variables).
Extraction communality of the variable, also called "extraction sum of squared loadings", is the portion of its variance that is explained, accounted for, by the extracted principal components.
You extracted one principal component of two possible (you have just two variables). The extracted PC1 has variance ("eigenvalue", in PCA's jargon) 1.092 which is ("explains") 1.092/(1+1) = 54.579% of the total (summative) variance of the two variables. The remaining component PC2 - which you chose to leave out (not to "extract") - has variance .908 which would eat up the remainder of the total variance: so, (1.092+.908) = (1+1) = 100%.
See also this for "explained variance", and this for exhaustive "chew over" of PCA. There isn't anything difficult about PCA, for a layman or a monk to get it equally.
PCA itself does not answer questions about "statistical significance", because it is an exploratory and data transformation technique dealing with the data at hand without reference to some "population".
P.S. As @NickCox truly points out in a comment, there is little practical use for PCA when the variables are almost uncorrelated. PCA is meant to be a dimensional-reduction technique for several (usually >2) correlated variables. In your (your friend's) case the two variables are only weakly correlated - which can be seen from the fact that PC1 and PC2 have almost equal variance. (One can easily compute from your output what was that correlation, and believe me it was not far from 0.) So in your example of very weak-correlated variables extracting only one of the two possible components would be a too gross simplification of real data. However, as an educational or theoretical case your example is all right.
Comment: +1. Your two variables are weakly correlated. It's not clear that PCA is of much use compared with plotting the variables, calculating the correlation and thinking about those.
Comment: @Nick this is why I thought about adding "student" `self-study` tag.
Answer: PCA is a method of data reduction, usually used when you have a great many variables and wish to capture information about them in a relatively small number of variables.
I don't see any reason for doing PCA when you have only 2 variables.
My first question is what sort of data you get from TOEIC scores and DMIS stages. Are these continuous variables? Ordinal ones? Googling, it looks like TOEIC is nearly continuous, but DMIS has only 6 levels. So, correlation is a little problematic (not necessarily completely wrong; it depends on what you are willing to assume about DMIS) and PCA is going to possibly compound those problems.
Given this, my first step would be to create a parallel box plot of the two variables to see how they vary together.


How can i change a function promise to the 'async/await' appraoch

Question: I was having this code in my node app:
function findByCredentials(email, password) {

  let UserModel = this;

  return UserModel.findOne({ email }).then((userDocument) => {
    if(!userDocument) return Promise.reject();

    return new Promise((res, rej) => {
      bcrypt.compare(password, userDocument.password, (err, res) => {
        if(res) return res(userDocument);
        else{ rej() }
      });
    })
  })

}

and i wanted to convert it to the 'async/await' approach, so the result that i could achieve is:
async function findByCredentials(email, password){

    let UserModel = this;
    const userDocument = await UserModel.findOne({ email });

    if(!userDocument) return Promise.reject();

    const compareResult = await bcrypt.compare(password, userDocument.password);

    if (compareResult) return userDocument;
    return Promise.reject();

}

is this correct or not, any links or videos for learning more about this subject? thank you!.
Comment: Instead of `return Promise.reject();` you can just `throw`. And you should throw an error object with a stack trace, not `undefined`.
Answer: It is good that you also improved on the initial code for its promisifying bcrypt.compare, while that method (and the rest of the bcrypt API) returns a promise when you don't provide a callack argument. This improvement has nothing to do with async / await, and should have been done in the original version as well.
One more thing can be improved: you shouldn't call Promise.reject() without argument. Instead throw an Error object.
async function findByCredentials(email, password) {
  const userDocument = this.findOne({ email });
  if (!userDocument) throw new Error("User account not found");
  const compareResult = await bcrypt.compare(password, userDocument.password);
  if (!compareResult) throw new Error("Wrong password");
  return userDocument;
}

NB: the actual error message may need some update, as it might not be a good idea to give away what the actual reason was for the authentication failure (unknown email identifier, or wrong password).


Changing the destination of R CMD build

Question: Is it possible to set a flag in the R CMD build ... command which specifies the destination folder for the tar.gz file?
I have looked pretty closely at the R CMD --help and cannot see it - but i may be missing something.
Comment: This post started life as a series of SO questions to help me build my first R package. I've rolled the lot into a [blog](http://ricardianambivalence.com/2012/07/28/creating-an-r-package-in-10-mins/).
Answer: The normal way to do this would be to cd to the destination folder and run R CMD build foo from there. E.g. sources are in ~/pkgsrcs/foo and you want tar.gz to be in ~/pkgbuild/foo then:
cd ~/pkgbuild/foo
R CMD build ~/pkgsrcs/foo

will result in foo_version.tar.gz in ~/pkgsrcs/foo.

Changing the destination of R CMD build


Kneser-Ney for unigrams?

Question: I was wondering if it is at all possible to use Kneser-Ney to smooth word unigram probabilites?
The basic idea behind back-off is to use (n-1)-gram frequencies when an n-gram has 0 count. This is obviously hard to do with an unigram. Is there something that I am missing that would allow to use Kneser-Ney for unigrams to smooth probabilities of single words? If this is possible how could that be done? If not, why is that impossible?
Comment: "*hard to do*"?  You mean "*impossible*" right? What would be the lower order term of unigram anyway?
Answer: Short answer: although it's possible to use it in this strange way, Kneyser-Ney is not designed for smoothing unigrams, because in this case its nothing but additive smoothing: $p_{abs}\left ( w_{i} \right )=\frac{max\left ( c\left ( w_{i} \right )-\delta ,0 \right )}{\sum_{w'}^{ }c(w')}$. This looks similar to Laplace smoothing and it is very well-known fact, that additive smoothing have poor perfomance and why wouldn't it?
Good and Turing revealed better scheme. The idea is to reallocate the probability mass of n-grams that occur $r + 1$ times in the training data to the n-grams that occur $r$ times. In particular, reallocate the probability mass of n-grams that were seen once to the n-grams that were never seen.
For each count $r$, we compute an adjusted count $r^{*}=(r+1)\frac{n_{r+1}}{n_{r}}$, where $n_{r}$ is the number of n-grams seen exactly r times.
Then we have: $p(x:c(x)=r)=\frac{r^{*}}{N}, N=\sum_{1}^{\infty }r*n_{r}$.
But many more sophisticated models were invented since then, so you have to do your research.
Long answer: First, let's start with the problem ( if your motivation is to gain deeper understanding of what's going on behind statistical model ).
You have some kind of probabilistic model, which is a distribution $p(e)$
over an event space $E$. You want to estimate the parameters of your model distribution $p$ from data. In principle, you might to like to use maximum likelihood (ML) estimates, so that your model is $p_{ML}\left ( x \right )=\frac{c(x)}{\sum_{e}^{ }c(e)}$
But, you have insufficient data: there are many events $x$ such that $c(x)=0$, so that the ML estimate is $p_{ML}(x)=0$.
In case of language models those events are words, which were never seen so far, we don't want to predict their probability to be zero.
Kneser-Ney is very creative method to overcome this bug by smoothing. It's an extension of absolute discounting with a clever way of constructing the lower-order (backoff) model. The idea behind that is simple: the lower-order model is significant only when count is small or zero in the higher-order model, and so should be optimized for that purpose.
Example: suppose "San Francisco" is common, but "Francisco"
occurs only after "San". "Francisco" will get a high unigram probability, and so absolute discounting will give a high probability to "Francisco" appearing after novel bigram histories. Better to give "Francisco" a low unigram probability, because the only time it occurs is after "San", in which case the bigram model fits well.
For bigram case we have: $p_{abs}(w_{i}|w_{i-1})=\frac{max(c(w_{i}w_{i-1})-\delta,0)}{\sum_{w'}^{ } c(w_{i-1}w')}+\alpha*p_{abs}(w_{i})$, from which is easy to conclude what will happen if we have no context ( i.e. only unigrams ).
Also take a look at classic Chen & Goodman paper for thorough and systematic comparison of many traditional language models : http://u.cs.biu.ac.il/~yogo/courses/mt2013/papers/chen-goodman-99.pdf
Answer: Usually the only smoothing in a unigram model would be to do uniform smoothing where every word in the vocabulary that has zero count is given some small probability.
Comment: Thanks for your answer. Is there a way to do that using Kneser-Ney?
Comment: No kneser ney is too sophisticated a tool for this really simple use case.
Comment: What makes you want to use Kneser-Ney in the first place?
Comment: Well, I am just trying to figure out if that would be possible. What would be the state-of-the-art method for smoothing unigrams? Good-Turing?

Kneser-Ney for unigrams?


Exibir postagem com include_once

Question: Eu quero lista todas as minhas postagens de todos os meus custom post type, até então eu consigo lista na index.php
Mas o problema e que só lista um post de cada custom post type.
Meu loop index.php
<?php $args = array('post_type'=>array('filmes', 'series', 'blog'),'paged' => $paged,'orderby'=>'date','posts_per_page' => 8); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php   if (has_post_thumbnail()) {
    $imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'home');
    $imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
    foreach($postimages as $postimage) {
        $imgsrc = wp_get_attachment_image_src($postimage->ID, 'home');
        $imgsrc = $imgsrc[0];
    }
    } elseif (preg_match('/
        ]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
        $imgsrc = $match[1];
    } else {
        $imgsrc = get_template_directory_uri() . '/images/no-imagen.png';
    } ?>
<?php
if ( get_post_type( get_the_ID() ) == 'filmes' ) {
    require_once('post/filmes.php');
} elseif ( get_post_type( get_the_ID() ) == 'series' ) {
    require_once('post/series.php');
} elseif ( get_post_type( get_the_ID() ) == 'blog' ) {
    require_once('post/blog.php');
}
?>
    <?php endwhile; else : ?>
    <?php endif; ?>

alguém saberia qual e o problema ou o que eu estou fazendo de errado?
Answer: Resolvi o problema substituindo o require_once por include
<?php
if ( get_post_type( get_the_ID() ) == 'filmes' ) {
    include('post/filmes.php');
} elseif ( get_post_type( get_the_ID() ) == 'series' ) {
    include('post/series.php');
} elseif ( get_post_type( get_the_ID() ) == 'blog' ) {
    include('post/blog.php');
}
?>

Exibir postagem com include_once


How to get the id of inserted row in android room databse in Kotlin?

Question: I am trying to get the user ID from the newest user. How can I make the insert method spit the ID when the ID is autogenerated?
in Model
@PrimaryKey(autoGenerate = true)
    val userId: Int

in Dao
@Insert(onConflict = OnConflictStrategy.REPLACE)
   fun addUserWithLong(user: User): LiveData<Long>

in Repository
fun addUserWitLong(user: User): LiveData<Long> {
        return userDao.addUserWithLong(user)
    }

in ViewModel
fun addUserWithLong(user: User): LiveData<Long> {
        return repository.addUserWitLong(user)
    }

in Fragment
val id: Long? = userViewModel.addUserWithLong(user).value

I have read in the docs that @Insert returns Long as the row ID but I do not know how to program it. Now the error is "Not sure how handle insert method return type." Is there some way to make with LiveData and not with Rxjava. That is without the need to download more dependecies.
Answer: As per the documentation here

If the @Insert method receives a single parameter, it can return a
long value, which is the new rowId for the inserted item. If the
parameter is an array or a collection, then the method should return
an array or a collection of long values instead, with each value as
the rowId for one of the inserted items. To learn more about returning
rowId values, see the reference documentation for the @Insert
annotation, as well as the SQLite documentation for rowid tables

So you can use it like
   @Insert(onConflict = OnConflictStrategy.REPLACE)
   long addUserWithLong(user: User)

or if you are inserting a list
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    long[] addUserWithLong(user: List<User>)

Edit-1
After checking answers from this post.

No, you can't. I wrote an answer to the issue. The reason is, that
LiveData is used to notify for changes. Insert, Update, Delete won't
trigger a change.

I just created a test project and successfully received Id of last inserted item in activity. Here is my implementation.
Dao
@Insert
suspend fun addUser(user: Users): Long

Repo
suspend fun insertUser(context: Context, users: Users): Long {
        val db = AppDatabase.getInstance(context)
        val dao = db.userDao()
        return dao.addUser(users)
    }

ViewModel
 fun addUser(context: Context, users: Users) = liveData {
//you can also emit your customized object here.
        emit("Inserting...")
        try {
            val userRepo = UsersRepo()
            val response = userRepo.insertUser(context, users)
            emit(response)
        } catch (e: Exception) {
            e.printStackTrace()
            emit(e.message)
        }
    }

Activity
viewModel.addUser(applicationContext, user).observe(this, Observer { userId ->
            Log.d("MainActivity", "Inserted User Id is $userId")
        })

Check test application here.
Comment: I understand that but I am supposed to call the function from not the main thread. And do not know how to achieve that with out LiveData.
Comment: If you want it with livedata than in fragment/activity you should do this. Rest of your code if fine.
viewModel.addUserWitLong(user).observe(viewLifecycleOwner,{id->
            Tiimber.d( "Inserted ID is $id")
        })
Comment: I keep getting this error in Dao. error: Not sure how to handle insert method's return type.
Comment: And I do not want it specifically with LiveData I just need to get it not from main thread. I thought using LiveData or make the function suspend. But I do not know how to make it work either way.
Comment: It works well enough. But it takes a little while to get the ID. And since I am using fragment in observe I replaced this with viewLifeCycleOwner. It worked with requireActivity as well.
The ID should not be used inside the Observer{} because it takes a while to aquire it.


Problem with getResourceAsStream

Question: I am writing an upload and a download function, and I try to have this two methods to write to or read from the same folder, and I ran into some problem with getResourceAsStream. (The software is run on glassfish)
upload: The method upload to this folder: /home/phamtn8/glassfishv3/glassfish/domains/domain1/applications/Documents/Documents-war_war/drawings/Liandro.jpg --> work great
download: stream = the above path
input = this.getClass().getResourceAsStream(stream);  //This return null
The location of the class files that contain these upload and download methods is at:
/home/phamtn8/glassfishv3/glassfish/domains/domain1/applications/Documents/Documents-war_war/WEB-INF/classes/org/xdrawing/web. If I put the jpg file here, the getResourceAsStream work.
NOTE: this.getClass.getName() return org.xdrawing.web.FileName
Please help !!!
Comment: Storing things into your classpath is a really weird and wrong thing to do. What happens if someone uploads a class file? It'll get added to your classpath! Best to store them in an area dedicated to storing files.
Comment: Thank you. Doing it now.
Answer: getResourceAsStream(..) treats paths from the root of the classpath. And yours seems to be the root of the machine. So use new FileInpuStream(fullPath) instead.
In fact, there is another getResourceAsStream method that belongs to the ServletContext. It treats paths from the root of the web application, and is more suitable for web applications. (your web app root is Documents-war_war/)
But the best practice with file uploads and downloads is to store them in a totally different location from your web application - say /home/appname/uploads, so that you can deploy and undeploy the web-app without losing any data. You will just need a configuration option (a <context-param> in web.xml for example) that points to the absolute location of the uploads, and use the FileInputStream approach (or OutputStream respectively)

Problem with getResourceAsStream


Is there an extension of the integers where the "sum of natural numbers" is rigorous?

Question: There's the well-known claim that
$$\sum_{n=1}^{\infty} n = -\frac{1}{12} \tag 1$$
Of course in this form, using the usual interpretation of the infinite sum as limit of finite sums, it's wrong, as the sum on the left hand side diverges. The $-1/12$ is obtained by using the series of the zeta function,
$$\zeta(s) = \sum_{n=1}^{\infty} n^{-s}$$
and then observing that formally evaluating it for $s=-1$ gives eq. (1).
Now let's consider another "sum" of a divergent series:
$$\sum_{n=0}^{\infty} 2^n = -1 \tag 2$$
Again, you can do an argument like the above: If we take the geometric series
$$\frac{1}{1-q} = \sum_{n=0}^{\infty} q^n$$
and insert $q=2$, we get the claimed identity.
However, eq. (2) can also be made rigorous by extending the integers to the $2$-adic numbers, where the left hand side indeed converges to $-1$.
My question therefore is:
Does there exist an extension of the integers that makes eq. (1) rigorous in the sense that in that extension the sum actually converges to the value $-1/12$?
Comment: It's not so much that you're extending the integers to the 2-adics, it's that you are equipping the integers with a metric other than the usual one, so convergence means something other than what it usually does.
Comment: I'm pretty sure you could "cheat" and define a topology on the rational numbers specifically for the purpose of making this (or any other series that has no term appearing infinitely often) infinite sum converge (to anything you want). The challenge would be to do something where the topology has wider interest; e.g. making all suitable Dirichlet series converge.
Comment: @GerryMyerson: Are there examples of divergent series whose regularized value is different from what one gets evaluating some simpler function (assuming it is known) which agrees with the series only for a narrow set of values? In other words, can this "natural" extension be not the "right" one?
Comment: Have a look at [this reference](http://math.stackexchange.com/q/37327).   A good general book on p-adic numbers is that of [N. Koblitz](citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.461.4588&rep=rep1&type=pdf)
Comment: But we can't get the $-1/{12}$ sum with $p$-adics.  The terms of the series do not converge $p$-adically to zero for any $p$.
Comment: @OscarLanzi: The OP is asking if *some* suitable extension exists, not if some $p$-adics are such a suitable extension.
Comment: I know but the comments turned to $p$-adics which is a dead end for the OP's sum.
Comment: Could you give a pointer to what you calle a "well-known claim" ?
Comment: "In this form it's wrong" is incorrect: what you mean is "Interpreted in the usual way, it's wrong". It is true in some other interpretations of what an infinite sum means.
Comment: @JeanMarie: http://math.stackexchange.com/q/633285/34930 and links therein.
Comment: @Hurkyl: I've clarified this point in the question.
Comment: As long as I know instead of extending the integers it's a lot easier to extend the notion of convergence and limits.
Comment: https://mathoverflow.net/questions/115743/an-algebra-of-integrals/342651#342651
Answer: The $2$-adic topology makes $\mathbb{Z}$ into a Hausdorff topological group (and in fact a topological ring). This is important: the fact that the topology is compatible with addition is used to prove several basic facts about convergent series, e.g. that changing a finite number of terms does not affect convergence.
Claim: There is no Hausdorff topological group structure on $\mathbb{Z}$ such that the sequence
$$
\tag{$\star$}
\sum_{n=1}^kn,\;\;\;k=1,2,\ldots
$$
is Cauchy.
Proof: Suppose such a topology exists. Choose an open neighborhood $U$ of $0$ such that $1\not\in U$, and a neighborhood $V$ of $0$ such that $V-V\subset U$. Here, $V-V=\{v_1-v_2:v_1,v_2\in V\}$. We assume $(\star)$ is Cauchy, so there is some $N>0$ such that
$$
\sum_{n=1}^{k_1}n-\sum_{n=1}^{k_2}n\in V
$$
whenever $k_1$, $k_2>N$. Now
$$
1=\left(\sum_{n=1}^{N+3}n-\sum_{n=1}^{N+2}n\right)-\left(\sum_{n=1}^{N+2}n-\sum_{n=1}^{N+1}n\right)\in V-V\subset U,
$$
which contradicts $1\not\in U$.
Comment: So essentially, it doesn't work because the series doesn't diverge *fast* enough. Nice.


301 redirecting broken links after moving Joomla! to subdomain and giving parent domain to Drupal7?

Question: I've recently started doing way more Drupal development than Joomla!, and given I use my personal website as a testing platform that changes about once every few years, am trying to migrate it from Joomla! 1.5 to Drupal 7.
To this end, I've moved the entire Joomla! website to http://v3.aendrew.com and in doing so, broken all incoming links, which are now met with a Drupal install that's never heard about any of my prior content -- http://aendrew.com.
Is there any way I can do the following via Drupal 7?

Detect broken incoming request (Drupal 404s)
Check whether the path exists on the Joomla! subdomain.
Issue a 301 redirect pointing to the Joomla! page if so; issue a 404 if not.

Thank you!
Answer: I would personally follow the steps described below:
1) Use this technique to detect the 404s and issue the redirect
2) Since you don't want to issue the redirect right away, but first check whether the URL exists in the Joomla! subdomain, you can use a function like this to determine whether the URL exists.
3) In order to determine what the URL of the incoming request was (so that you can use it to match it against the Joomla! subdomain), you can use this: $_SERVER['REDIRECT_URL']


Finishing activity without onPause called

Question: I am finishing my current activity using finish(). This is calling onPause automatically. I want to finish activity without onPause being called. My activity is running a song service so i want song to stop when app is in background but dont want it to stop when user goes from one activity into another in my app. I cant do stopService and startService in between activities because then there is a momentary lag in between the sounds.
Comment: Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate().
Answer:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface

google docs
The background Service is agnostic of which Activity is running or any discontinuity between them.
The two types, "bound" and "started" are supposed to have different persistence characteristics but in practice (not stress testing) I find the bound Service does not clobbered for lack of system memory and is much easier to implement (despite tutorials claiming otherwise). It uses some IPC abstraction that appears as though it is being directly invoked from the Activity. The same can't be said of the "started" variety (unless it is also bound) which is IMO a closer approximation to the traditional service I would associate with web-servers (or anything that is already going to be experiencing not insignificant delays- such as due to network transmission).
(Lecture over) I see you are calling finish(). You need some way to shut down the Service from your Activity. Just make sure to branch aways from doing so when not intended. Code would be helpful but I can assure you this is how media players work.
Comment: yeah i am using mediaplayer in my service. Stopping and Starting again causes a delay in background music. It deosnt sound good.
Comment: Can I suggest you use a retained `Fragment` to hold your media player?
Comment: Well i would prefer to use another functioninstead of finish() to close activity as well, without calling onPause
Comment: Also its a game so i dont wanna save instance, i just need some substitute to have onPauses as well as destroying previous activity(level) in it.
Comment: `finish()` is the only way I know to stop an activity. But as I said that per se is not going to cause a break in background music. Do you mean break or delay? For gaming and sound effects there might well be a delay in setting up mediaplayer.
Comment: John please answer my this question as well http://stackoverflow.com/questions/33023062/pause-and-resume-timer-made-using-handlers
Comment: According to me stopService in onPause and start service in onResume causes the break between background music.
Comment: @NimitAggarwal you're the `Handler` expert, I use a `Service` just for my `MediaPlayer`, but it probably would be delayed relative to visual stimulus, as all I do is audio.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92568/discussion-between-nimit-aggarwal-and-john).


The link of "Pdf version" on node page does not appear in chrome

Question: I have installed the the print module on my drupal 7 site. I configured the the print module pdf settings.
Now the link "pdf version" is displaying with each node on the content area at bottom. When I click on the link, it save the node in pdf format.
But this only works in firefox. In chrome the "pdf version" link in not displaying.
What is the problem?
Answer: It was the permission issue. I granted the permission to the authenticated and anonymous users and it works for me.


Solve the equation $2^x+3^x-4^x+6^x-9^x=1$

Question: I found an interesting equation I don't seem to grasp completely.
Solve the equation:
$2^x+3^x-4^x+6^x-9^x=1$
Now. I thought the only relevant solution was the integer solutions, but I was sorely mistaken.
So if the question was: Find all integer solutions to the following equation my attempt is as follows:
$2^x+3^x-4^x+6^x-9^x=1$ (1)
$2^x+3^x+3^x2^x-(2^x)^2-(3^x)^2=1$
Substitution:
$P=2^x\quad$
$Q=3^x$  (2)
$P+Q+PQ-P^2-Q^2=1$
We can see that this equation is symmetric and that $P>0, Q>0$
For $P=1$ we get
$1+Q+Q-1-Q^2=1 \to Q=1$
P & Q are equal, with (2) we get:
$P=Q \to 2^x=3^x \to x=0$
Answer: $x=0$ is the only solution
Now when I wrote down my solution I recognize that several steps are wrong.
 First of all how do i know P and Q are equal? They might not be i suppose
If anyone could give me a hint on how to solve these type of equations or even how to solve this equation I'd be very grateful.
And furthermore is this type of equation called exponential equation?
The type of exponential equation I'm more familiar with is simply solved with log rules, equations were you can simplify both sides and just log and solve.
Comment: Note that, if $x> 0$ then $P$ is even whence $\mod 2$ your expression is $ Q-Q^2\equiv 1 \pmod 2$ which is impossible.  Were you restricting to non-negative $x$?
Comment: @lulu $P$ and $Q$ may not be integers.
Comment: I was, but for the complete solution we must work with all reels i think.
Comment: @Bob1123  They are if $x\in \mathbb N$ that's why I asked if we restricting to non-negative integers $x$.
Comment: @einar  But you still want $x$ to be an integer, no?  I mean, you write "Find all integer solutions to the following..."  If $x=-n$ for $n\in \mathbb N$ then you can multiply both sides by $6^{2n}$ to get $2^n3^{2n}+2^{2n}3^n-3^{2n}+6^n-2^{2n}=6^{2n}$ which again is impossible $\pmod 2$.
Answer: Note that the equation is equivalent to
$$(2^x-1)^2-(2^x-1)(3^x-1)+(3^x-1)^2=0.$$
Moreover, note that the above equation is satisfied iff $x=0$ because if $v\not=0$ then
$$u^2-uv+v^2=v^2((u/v)^2-(u/v)+1)>0.$$
Comment: @SimplyBeautifulArt this is what happens when you write the conic section in $P,Q$ around its geometric center, located where the gradient is zero
Comment: @WillJagy Ah thanks a lot for explaining the motivation for this.
Comment: By subtracting $(2^x-1)(3^x-1)$, we get a perfect square on the LHS, and something that is $\le0$ on the RHS, therefore, $0=(2^x-1)(3^x-1)$, and thus it follows suit.  Beautiful!
Comment: Thanks! That's a beautiful solution indeed! :) Much appreciated!
Comment: @SimplyBeautifulArt Yeah it's very nice! You can also view it as $\dfrac {a^3+b^3}{a+b}=0$ from which you get $2^x + 3^x=2$, which has $x=0$ as the only solution.
Answer: Given conic section
$$  P^2 - PQ + P^2 - P - Q + 1 = 0,  $$
the $P$ partial derivative is
$$ 2P-Q - 1. $$
The $Q$ partial is
$$ -P + 2Q - 1.  $$
Setting both to zero gives $P=Q=1.$
So
$$ P = u + 1, \; \; Q = v + 1. $$
$$  P^2 - PQ + P^2 - P - Q + 1 = u^2 - uv + v^2.  $$
The set $u^2 - uv + v^2 = 0$ is a single point $u=v=0,$ as this is a positive quadratic form: the Hessian matrix is positive.
Oh, if the Hessian has determinant zero, there will not be a "center," the thing is a parabola or degenerate parabola.


Errors on gem version while executing bundler:install task of capistrano when trying to deploy rails app

Question: I am trying to deploy my rails app using Capistrano on Digital Ocean droplet. While deploying using cap production deploy, when it reaches to bundler:install part, it gives me this error.
capistrano log
DEBUG [5a035aa4] Command: cd /home/ideabreed/noc/releases/20200405051118 && ~/.rvm/bin/rvm default do bundle install --path /home/ideabreed/noc/shared/bundle --jobs 4 --without development test --deployment --quiet
 DEBUG [5a035aa4]   Warning, new version of rvm available '1.29.10', you are using older version '1.29.9'.
You can disable this warning with:   echo rvm_autoupdate_flag=0 >> ~/.rvmrc
You can enable auto-update with:     echo rvm_autoupdate_flag=2 >> ~/.rvmrc
You can update manually with:        rvm get VERSION                         (e.g. 'rvm get stable')

 DEBUG [5a035aa4]   [DEPRECATED] The `--deployment` flag is deprecated because it relies on being remembered across bundler invocations, which bundler will no longer do in future versions. Instead please use `bundle config set deployment 'true'`, and stop using this flag
 DEBUG [5a035aa4]   [DEPRECATED] The `--path` flag is deprecated because it relies on being remembered across bundler invocations, which bundler will no longer do in future versions. Instead please use `bundle config set path '/home/ideabreed/noc/shared/bundle'`, and stop using this flag
 DEBUG [5a035aa4]   [DEPRECATED] The `--without` flag is deprecated because it relies on being remembered across bundler invocations, which bundler will no longer do in future versions. Instead please use `bundle config set without 'development test'`, and stop using this flag
 DEBUG [5a035aa4]   Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/home/ideabreed/noc/shared/bundle/ruby/2.6.0/gems/sassc-2.2.1/ext
/home/ideabreed/.rvm/rubies/ruby-2.6.3/bin/ruby -I
/home/ideabreed/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0 -r
./siteconf20200405-18259-1q3n44y.rb extconf.rb
creating Makefile

current directory:
/home/ideabreed/noc/shared/bundle/ruby/2.6.0/gems/sassc-2.2.1/ext
make "DESTDIR=" clean

current directory:
/home/ideabreed/noc/shared/bundle/ruby/2.6.0/gems/sassc-2.2.1/ext
make "DESTDIR="
compiling ./libsass/src/fn_numbers.cpp
compiling ./libsass/src/lexer.cpp
compiling ./libsass/src/memory/SharedPtr.cpp
compiling ./libsass/src/c99func.c
compiling ./libsass/src/plugins.cpp
compiling ./libsass/src/ast_supports.cpp
compiling ./libsass/src/c2ast.cpp
compiling ./libsass/src/emitter.cpp
compiling ./libsass/src/sass_util.cpp
compiling ./libsass/src/ast.cpp
g++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.
Makefile:235: recipe for target 'ast.o' failed
make: *** [ast.o] Error 4

make failed, exit code 2

Gem files will remain installed in
/home/ideabreed/noc/shared/bundle/ruby/2.6.0/gems/sassc-2.2.1 for inspection.
Results logged to
/home/ideabreed/noc/shared/bundle/ruby/2.6.0/extensions/x86_64-linux/2.6.0/sassc-2.2.1/gem_make.out

An error occurred while installing sassc (2.2.1), and Bundler cannot continue.
Make sure that `gem install sassc -v '2.2.1' --source 'https://rubygems.org/'`
succeeds before bundling.

In Gemfile:
  rails_admin was resolved to 2.0.2, which depends on
    sassc-rails was resolved to 2.1.2, which depends on
      sassc

I have done gem install sassc -v '2.2.1' --source 'https://rubygems.org/' as suggested but it has no effect. I don't know what is causing this error as i already have the gem file installed with mentioned version above.
Gemfile
source 'https://rubygems.org'
git_source(:github) {|repo| "https://github.com/#{repo}.git"}

ruby '2.6.3'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 220.127.116.11'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
gem 'slim-rails'
gem 'devise'
gem 'rails_admin', '~> 2.0.2'
gem 'nepali_date_converter'
gem 'ransack'
gem "sassc-rails", "~> 2.1.2"

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry-rails'
  gem 'annotate'
  gem 'any_login'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'rails_db'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'

  gem 'capistrano', require: false
  gem 'capistrano-rvm', require: false
  gem 'capistrano-rails', require: false
  gem 'capistrano-bundler', require: false
  gem 'capistrano3-puma', require: false
  gem 'capistrano-rails-db'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

group :production do
  gem "simple_form"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    actioncable (18.104.22.168)
      actionpack (= 18.104.22.168)
      nio4r (~> 2.0)
      websocket-driver (>= 0.6.1)
    actionmailbox (184.108.40.206)
      actionpack (= 18.104.22.168)
      activejob (= 184.108.40.206)
      activerecord (= 184.108.40.206)
      activestorage (= 188.8.131.52)
      activesupport (= 220.127.116.11)
      mail (>= 2.7.1)
    actionmailer (188.8.131.52)
      actionpack (= 184.108.40.206)
      actionview (= 220.127.116.11)
      activejob (= 188.8.131.52)
      mail (~> 2.5, >= 2.5.4)
      rails-dom-testing (~> 2.0)
    actionpack (188.8.131.52)
      actionview (= 18.104.22.168)
      activesupport (= 126.96.36.199)
      rack (~> 2.0, >= 2.0.8)
      rack-test (>= 0.6.3)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.0, >= 1.2.0)
    actiontext (188.8.131.52)
      actionpack (= 220.127.116.11)
      activerecord (= 126.96.36.199)
      activestorage (= 184.108.40.206)
      activesupport (= 126.96.36.199)
      nokogiri (>= 1.8.5)
    actionview (126.96.36.199)
      activesupport (= 184.108.40.206)
      builder (~> 3.1)
      erubi (~> 1.4)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.1, >= 1.2.0)
    activejob (126.96.36.199)
      activesupport (= 18.104.22.168)
      globalid (>= 0.3.6)
    activemodel (188.8.131.52)
      activesupport (= 126.96.36.199)
    activemodel-serializers-xml (1.0.2)
      activemodel (> 5.x)
      activesupport (> 5.x)
      builder (~> 3.1)
    activerecord (18.104.22.168)
      activemodel (= 18.104.22.168)
      activesupport (= 188.8.131.52)
    activestorage (22.214.171.124)
      actionpack (= 220.127.116.11)
      activejob (= 22.214.171.124)
      activerecord (= 220.127.116.11)
      marcel (~> 0.3.1)
    activesupport (126.96.36.199)
      concurrent-ruby (~> 1.0, >= 1.0.2)
      i18n (>= 0.7, < 2)
      minitest (~> 5.1)
      tzinfo (~> 1.1)
      zeitwerk (~> 2.2)
    addressable (2.7.0)
      public_suffix (>= 2.0.2, < 5.0)
    airbrussh (1.4.0)
      sshkit (>= 1.6.1, != 1.7.0)
    annotate (3.1.1)
      activerecord (>= 3.2, < 7.0)
      rake (>= 10.4, < 14.0)
    any_login (1.4.3)
      rails (>= 4.2.7)
    bcrypt (3.1.13)
    bindex (0.8.1)
    bootsnap (1.4.6)
      msgpack (~> 1.0)
    builder (3.2.4)
    byebug (11.1.1)
    capistrano (3.12.1)
      airbrussh (>= 1.0.0)
      i18n
      rake (>= 10.0.0)
      sshkit (>= 1.9.0)
    capistrano-bundler (1.6.0)
      capistrano (~> 3.1)
    capistrano-rails (1.4.0)
      capistrano (~> 3.1)
      capistrano-bundler (~> 1.1)
    capistrano-rails-db (0.0.2)
      capistrano-rails (~> 1.1)
    capistrano-rvm (0.1.2)
      capistrano (~> 3.0)
      sshkit (~> 1.2)
    capistrano3-puma (4.0.0)
      capistrano (~> 3.7)
      capistrano-bundler
      puma (~> 4.0)
    capybara (3.32.0)
      addressable
      mini_mime (>= 0.1.3)
      nokogiri (~> 1.8)
      rack (>= 1.6.0)
      rack-test (>= 0.6.3)
      regexp_parser (~> 1.5)
      xpath (~> 3.2)
    childprocess (3.0.0)
    coderay (1.1.2)
    concurrent-ruby (1.1.6)
    crass (1.0.6)
    devise (4.7.1)
      bcrypt (~> 3.0)
      orm_adapter (~> 0.1)
      railties (>= 4.1.0)
      responders
      warden (~> 1.2.3)
    erubi (1.9.0)
    ffi (1.12.2)
    globalid (0.4.2)
      activesupport (>= 4.2.0)
    haml (5.1.2)
      temple (>= 0.8.0)
      tilt
    i18n (1.8.2)
      concurrent-ruby (~> 1.0)
    jbuilder (2.10.0)
      activesupport (>= 5.0.0)
    jquery-rails (4.3.5)
      rails-dom-testing (>= 1, < 3)
      railties (>= 4.2.0)
      thor (>= 0.14, < 2.0)
    jquery-ui-rails (6.0.1)
      railties (>= 3.2.16)
    kaminari (1.2.0)
      activesupport (>= 4.1.0)
      kaminari-actionview (= 1.2.0)
      kaminari-activerecord (= 1.2.0)
      kaminari-core (= 1.2.0)
    kaminari-actionview (1.2.0)
      actionview
      kaminari-core (= 1.2.0)
    kaminari-activerecord (1.2.0)
      activerecord
      kaminari-core (= 1.2.0)
    kaminari-core (1.2.0)
    listen (3.1.5)
      rb-fsevent (~> 0.9, >= 0.9.4)
      rb-inotify (~> 0.9, >= 0.9.7)
      ruby_dep (~> 1.2)
    loofah (2.4.0)
      crass (~> 1.0.2)
      nokogiri (>= 1.5.9)
    mail (2.7.1)
      mini_mime (>= 0.1.1)
    marcel (0.3.3)
      mimemagic (~> 0.3.2)
    method_source (1.0.0)
    mimemagic (0.3.4)
    mini_mime (1.0.2)
    mini_portile2 (2.4.0)
    minitest (5.14.0)
    msgpack (1.3.3)
    nepali_date_converter (1.0.0)
    nested_form (0.3.2)
    net-scp (2.0.0)
      net-ssh (>= 2.6.5, < 6.0.0)
    net-ssh (5.2.0)
    nio4r (2.5.2)
    nokogiri (1.10.9)
      mini_portile2 (~> 2.4.0)
    orm_adapter (0.5.0)
    pg (1.2.3)
    polyamorous (2.3.2)
      activerecord (>= 5.2.1)
    pry (0.13.0)
      coderay (~> 1.1)
      method_source (~> 1.0)
    pry-rails (0.3.9)
      pry (>= 0.10.4)
    public_suffix (4.0.3)
    puma (4.3.3)
      nio4r (~> 2.0)
    rack (2.2.2)
    rack-pjax (1.1.0)
      nokogiri (~> 1.5)
      rack (>= 1.1)
    rack-proxy (0.6.5)
      rack
    rack-test (1.1.0)
      rack (>= 1.0, < 3)
    rails (184.108.40.206)
      actioncable (= 22.214.171.124)
      actionmailbox (= 220.127.116.11)
      actionmailer (= 18.104.22.168)
      actionpack (= 126.96.36.199)
      actiontext (= 22.214.171.124)
      actionview (= 126.96.36.199)
      activejob (= 184.108.40.206)
      activemodel (= 126.96.36.199)
      activerecord (= 188.8.131.52)
      activestorage (= 126.96.36.199)
      activesupport (= 18.104.22.168)
      bundler (>= 1.3.0)
      railties (= 184.108.40.206)
      sprockets-rails (>= 2.0.0)
    rails-dom-testing (2.0.3)
      activesupport (>= 4.2.0)
      nokogiri (>= 1.6)
    rails-html-sanitizer (1.3.0)
      loofah (~> 2.3)
    rails_admin (2.0.2)
      activemodel-serializers-xml (>= 1.0)
      builder (~> 3.1)
      haml (>= 4.0, < 6)
      jquery-rails (>= 3.0, < 5)
      jquery-ui-rails (>= 5.0, < 7)
      kaminari (>= 0.14, < 2.0)
      nested_form (~> 0.3)
      rack-pjax (>= 0.7)
      rails (>= 5.0, < 7)
      remotipart (~> 1.3)
      sassc-rails (>= 1.3, < 3)
    rails_db (2.3.1)
      activerecord
      kaminari
      rails (>= 5.0.0)
      ransack (>= 2.3.2)
      simple_form (>= 5.0.1)
      terminal-table
    railties (18.104.22.168)
      actionpack (= 22.214.171.124)
      activesupport (= 22.214.171.124)
      method_source
      rake (>= 0.8.7)
      thor (>= 0.20.3, < 2.0)
    rake (13.0.1)
    ransack (2.3.2)
      activerecord (>= 5.2.1)
      activesupport (>= 5.2.1)
      i18n
      polyamorous (= 2.3.2)
    rb-fsevent (0.10.3)
    rb-inotify (0.10.1)
      ffi (~> 1.0)
    regexp_parser (1.7.0)
    remotipart (1.4.4)
    responders (3.0.0)
      actionpack (>= 5.0)
      railties (>= 5.0)
    ruby_dep (1.5.0)
    rubyzip (2.3.0)
    sass-rails (6.0.0)
      sassc-rails (~> 2.1, >= 2.1.1)
    sassc (2.2.1)
      ffi (~> 1.9)
    sassc-rails (2.1.2)
      railties (>= 4.0.0)
      sassc (>= 2.0)
      sprockets (> 3.0)
      sprockets-rails
      tilt
    selenium-webdriver (3.142.7)
      childprocess (>= 0.5, < 4.0)
      rubyzip (>= 1.2.2)
    simple_form (5.0.2)
      actionpack (>= 5.0)
      activemodel (>= 5.0)
    slim (4.0.1)
      temple (>= 0.7.6, < 0.9)
      tilt (>= 2.0.6, < 2.1)
    slim-rails (3.2.0)
      actionpack (>= 3.1)
      railties (>= 3.1)
      slim (>= 3.0, < 5.0)
    spring (2.1.0)
    spring-watcher-listen (2.0.1)
      listen (>= 2.7, < 4.0)
      spring (>= 1.2, < 3.0)
    sprockets (4.0.0)
      concurrent-ruby (~> 1.0)
      rack (> 1, < 3)
    sprockets-rails (3.2.1)
      actionpack (>= 4.0)
      activesupport (>= 4.0)
      sprockets (>= 3.0.0)
    sshkit (1.21.0)
      net-scp (>= 1.1.2)
      net-ssh (>= 2.8.0)
    temple (0.8.2)
    terminal-table (1.8.0)
      unicode-display_width (~> 1.1, >= 1.1.1)
    thor (1.0.1)
    thread_safe (0.3.6)
    tilt (2.0.10)
    turbolinks (5.2.1)
      turbolinks-source (~> 5.2)
    turbolinks-source (5.2.0)
    tzinfo (1.2.6)
      thread_safe (~> 0.1)
    unicode-display_width (1.7.0)
    warden (1.2.8)
      rack (>= 2.0.6)
    web-console (4.0.1)
      actionview (>= 6.0.0)
      activemodel (>= 6.0.0)
      bindex (>= 0.4.0)
      railties (>= 6.0.0)
    webdrivers (4.2.0)
      nokogiri (~> 1.6)
      rubyzip (>= 1.3.0)
      selenium-webdriver (>= 3.0, < 4.0)
    webpacker (4.2.2)
      activesupport (>= 4.2)
      rack-proxy (>= 0.6.1)
      railties (>= 4.2)
    websocket-driver (0.7.1)
      websocket-extensions (>= 0.1.0)
    websocket-extensions (0.1.4)
    xpath (3.2.0)
      nokogiri (~> 1.8)
    zeitwerk (2.3.0)

PLATFORMS
  ruby

DEPENDENCIES
  annotate
  any_login
  bootsnap (>= 1.4.2)
  byebug
  capistrano
  capistrano-bundler
  capistrano-rails
  capistrano-rails-db
  capistrano-rvm
  capistrano3-puma
  capybara (>= 2.15)
  devise
  jbuilder (~> 2.7)
  listen (>= 3.0.5, < 3.2)
  nepali_date_converter
  pg (>= 0.18, < 2.0)
  pry-rails
  puma (~> 4.1)
  rails (~> 6.0.2, >= 18.104.22.168)
  rails_admin (~> 2.0.2)
  rails_db
  ransack
  sass-rails (>= 6)
  sassc-rails (~> 2.1.2)
  selenium-webdriver
  simple_form
  slim-rails
  spring
  spring-watcher-listen (~> 2.0.0)
  turbolinks (~> 5)
  tzinfo-data
  web-console (>= 3.3.0)
  webdrivers
  webpacker (~> 4.0)

RUBY VERSION
   ruby 2.6.3p62

BUNDLED WITH
   2.1.1

Need a help to fix this.
Answer: I got the same error today.
My server did not have enough RAM to compile the sassc gem. I raised the RAM from 256 to 512 MB and it worked.


Consequence of Doob-Meyer decomposition

Question: Let $\mathcal{H}^2_0$ be the space of all $L^2$ bounded RCLL martingales null at zero. As a consequence of Doob-Meyer we know:

For every $M\in \mathcal{H}^2_0$ there exist a unique adapted, increasing RCLL process $[M]$ null at zero with $\Delta [M]=(\Delta M)^2$ such that $M^2-[M]$ is a uniformly integrable martingale null at zero.

Suppose $L\in \mathcal{H}^{2,c}_0$ (the $c$ indicates that the martingale is continuous) and $M\in \mathcal{H}^{2,d}_0$, where $\mathcal{H}^{2,d}_0$ is the orthogonal complement in the Hilbert space $\mathcal{H}^2$ with the inner product $(L,M):=E[M_\infty L_\infty]$
I should show that $[L,M]=0$. The hint was to prove two things:

$LM$ is a uniformly integrable martingale
$[L,M]$ is continuous.

I was able to prove $1$. However why do I have to prove 2? By the theorem above we know there is an unique adapted RCLL process $[L,M]$ null at zero, of finite variation such that $\Delta [M,L]=\Delta L \Delta M$ and $LM-[L,M]$ is a uniformly integrable martingale. The process identically to zero is RCLL, adapted and of finite variation. Moreover by 1, we know $LM-0$ is auniformly integrable martingale. By uniqueness this would imply $[L,M]=0$. Am I wrong? I do not see why I have to show that $[L,M]$ is continuous. Even more, why should it be? Of course it is RCLL (due to polarization), but in general not continuous.
Thanks in advance!
Answer: You are right that the process $0$ is an adapted, RCLL and increasing process. You have shown that $LM$ is a uniformly integrable martingale, so in order to conclude that $[L,M]=0$, you just have to show that $\Delta [L,M]=\Delta L\Delta M$. I believe this is why they want you to show that this particular quadratic variation process, $[L,M]=0$, is continuous (they are not asking you to show that every quadratic variation process is continuous because, as you said yourself, this is not the case). Now that $[L,M]=0$ is continuous then $\Delta [L,M]=\Delta L\cdot \Delta M$ is obvious.

Consequence of Doob-Meyer decomposition


What is an edge router and how does it work?

Question:
Possible Duplicate:
What is an edge server / router / device?

Can someone tell me what an Edge Router is and how it works?  Examples and analogies are always welcome.
Comment: I think this is close enough to be a duplicate.  http://serverfault.com/questions/67484/what-is-an-edge-server
Comment: I don't really see enough information on that question regarding edge routers, specifically.
Answer: An edge router is simply a router that connects the network you control to a network that you don't.  In most cases, it is the router that's connected directly to your internet connection.
This is in opposition to a core router, which is a router that routes between multiple networks that are all under your control.
An edge router is generally a lower-end router, as it tends not to do much beyond pass traffic, and generally to a circuit that has a relatively low bandwidth.  Edge routers are sometimes combined with firewalls, NATs, and VPN endpoints, but I'm not really sure you'd still call it an edge router at that point.
Comment: nice summary. +1.


Forecasting the past?

Question: More of a literacy question that stats, but I'm looking for correct terminology and the Google machine hasn't thrown anything up.
You have explanatory data and observed data for 2000-2010. You have only explanatory variables for 1990-2000. You want to estimate the X for the years 1990-2000, are you forecasting? Estimating? Back predicting? What is the correct terminology?
Comment: I'd call it *backcasting* - which means I agree with @AndyW 's answer
Answer: I've seen it referred to as backcasting (which is the obverse of forecasting). For an example see:

McShane, Blakely B. & Abraham J. Wyner. 2011. A statistical analysis
  of multiple temperature proxies: Are reconstructions of surface
  temperatures over the last 1000 years reliable? Annals of Applied
  Statistics
  5(1):5-44. PDF Here.
Answer: I would call it estimating or perhaps even missing data imputation. It all depends on context.
Is X really causally predicted by your explainatory variables? Or is X only a part of the set that's missing.  I find it hard to think of a real situation. Might help if you provided some more context.
Comment: A company that has only started recording weather dependent data since 2000. But Obviously I have weather records going further back.
Comment: @Will: I see. So what'd be the objective in predicting the unrecorded data for the pre 2000 era?

Forecasting the past?


How to debug linux networking: Address already in use

Question: I have a Slackware linux box where I cannot start any service that listens on one particular port on localhost. By using strace I found out that the error happens on the bind() call, and the error is EADDRINUSE (Address already in use):
bind(3, {sa_family=AF_INET, sin_port=htons(874), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EADDRINUSE (Address already in use)

This happens with any process I try to start listening on that port, so it is not related to the process itself. The above strace output comes from the command strace -ff nc -l -p 874 -s 127.0.0.1.
So, this suggests there is a process already listening on localhost port 874. However, I can't seem to find it. The following commands all return nothing:
netstat -aplunt | grep :874
netstat -na | grep :874
lsof -i :874
lsof -i tcp | grep 874
fuser 874/tcp
socklist | grep 874
iptables -t filter -S | grep 874
iptables -t nat -S | grep 874
iptables -t mangle -S | grep 874
conntrack -L | grep 874

If I try to listen on 0.0.0.0:874 it fails with the same error. Listening on one of the IP addresses configured on a nic works OK, and listening to 127.0.0.2:874 also works OK. Listening on a different port works fine, also on 127.0.0.1 or 0.0.0.0.
So, now I am curious. How can I find out why the network stack returns EADDRINUSE here? What other things could I look at, or what other commands can I run to get more information?
Additional info:

Kernel 4.1.31.
Selinux is not used here.
Trying to connect to 127.0.0.1 with telnet returns "Connection refused"
I'm running the commands as root
Comment: AFAIK Linux requires root privileges when listening to a port < 1000. Maybe that's the problem here.
Comment: Is this host an NFS client? It may be using source port 874 for an NFS mount. Anyway I would try `netstat -na | grep 874` in case your current `netstat` flags are too restrictive.
Comment: Is the port mentioned anywhere in `iptables -S` output?
Comment: Can you please also print output of **strace -ff nc -l  874** also, The one you used is trying to make connections with 874 as source port. Thanks!
Comment: @TomShaw You just made my day! It was **NFS** all right. I'm not sure how this exactly came about, but after unmounting all NFS mounts and restarting the RPC and NFS services the problem is gone. With tcpdump I also saw some traffic from port 874 to port 111 (why didn't I think of that before) which confirms it. Can you post this as an answer please?
Comment: Can you check if there is no established sessions on that port? Run **netstat -aplunt | grep 874**, just add 'a' flag. Or maybe some session using this port as the source port?(Although highly unlikely). But worth giving a shot.
Comment: No output. I've updated the netstat command in the question.
Comment: I think @hertitu is right, it may be port forwarding in iptables. Also use `nmap` to check 874 tcp and udp port. What ip has localhost in /etc/hosts file? Check all configs in /etc and /usr/local/etc folders that they have 874 substring.
Comment: @hertitu how would portforwarding affect listening on a port? Anyway, I checked, and there are no iptables rules for that port. To be extra sure I flushed the firewall: no change.
Comment: @AnirudhMalhotra I'm not making a connection, I'm **listening** on port 874, which is where the problem is. The command you showed listens on a random high port. There is no problem doing that.
Comment: Well here is what the man page of nc states:
**-p source_port
             Specifies the source port nc should use, subject to privilege restrictions and availability.

-l      Used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host.  It is an
             error to use this option in conjunction with the -p, -s, or -z options.  Additionally, any timeouts specified with the -w
             option are ignored.**

you cannot these flags in conjunction. So I will correct myself the command you used is rather contradictory. Thanks!
Comment: Perhaps we have a different version of nc? Mine says: **-l**: listen mode, for inbound connects, **-p port**: local port number.
Comment: Anyway, I have the same problem if I use a different process to listen: **rsync --daemon --address=127.0.01 --port=874**
Comment: I'm running all commands as root. Question updated.
Comment: finally pheww... TCPdump(ughh, should have thought about earlier). Glad it worked though.
Comment: Glad I could help, posted as an answer with some ways of mitigating the issue. P.S. On my machine the NFS connections are visible in the `netstat -na` output, albeit without associated processes (because they come from the kernel). They can't be seen with commands like `lsof` or `fuser`.
Answer: If your host is an NFS client, it may be using source port 874 for an NFS mount. I suspect that because the connection does not originate from userspace it may not be visible to the tools you've used so far.
Consider one of the following:

Adjust the sysctls sunrpc.min_resvport and sunrpc.max_resvport (default 665 and 1023) to change the range of source ports that the NFS client uses
Use a listening port outside of this range
Use the noresvport option on the NFS mount to use the non-privileged range (may have security implications)


For D major, if I use the F# note on the low "E" string, does that count as a D major?

Question: For D major, if I use the F# note on the low "E" string, does that count as a D major? If yes, what would I call this chord?
Answer: It certainly is another D major chord. Playing an F# at the bottom of the chord makes it a 1st inversion, commonly written as D/F#. Most people who play this chord would tend to put the thumb over onto bottom string, 2nd fret. You could also play the open chord from the 5th string open (A), which would then be a 2nd inversion, or D/A.
As long as you have all three notes from a simple triad chord, it will be called according to its root note. The order of the notes (especially on guitar!) will only alter the voicing.
Answer: I presume you are talking about on a guitar?  If your bottom note is F# and you include As and Ds above it, then it is called D major, 1st inversion.
Comment: There is a 'guitar' tag under the question!
Answer: The chord you refer to is most commonly denoted as a D/F# for which the simplest explanation is a D Major Chord with F# as the lowest (bass) note ("D with F# Bass"). You will often see this type chord notation for guitar referred to as a "slash chord".  In a slash chord the first letter is the chord name (root) and the letter after the slash denotes the bass note (usually the first note strummed) to be played.
Technically a D/F# slash chord is still a D major, but as others have said, it is a first inversion of the D Major Triad.  We also call it a "different voicing" of the D Major chord. All inversions of a D Major Chord on guitar contain the same three notes in the D Maj Triad - except the order that you play them is altered (also the number of times and octaves the note appears/repeats).
The D/F# chord is very useful on guitar when playing a G, D, Em progression as it allows for a nice descending bass line to be incorporated into your progression.  And in some songs, the D/F# voicing just seems to sound better than the basic D major chord played only on the top four strings.
Many folks play the D/F# by using their thumb over the top of the neck to fret the F# on the low E string.  However my hands are too small to reach over with my thumb so I use my index finger on the low E string.  Usually I leave out the pinky and don't play the high e.
The D/F# is one of my favorite alternate voicings of a chord for guitar.  I use it often.


How to install Eclipse Luna IDE

Question: I'm trying to install eclipse Luna on my pc, but it show error all the time. I've searched on many websites and found that there's something to do with configuration settings. Please help me by providing  step by step instructions.!
Screenshots below shows the error.
Comment: Please describe the error, or provide some screenshots.
Comment: I'll help you if you can help me with my car. It's broken.
Comment: That is a very unclear and overly-broad questions. Please see [How to Ask](http://stackoverflow.com/review)
Comment: I've uploaded the screenshot.
Comment: Plz check the above screenshot.
Comment: Do you have the right java version? This error can happen when you try to start a 32 bit java on a 64 bit os.
Answer: Please check the version of JDK and Eclipse, the both need match that if you installed 64bit Eclipse then you need 64bit JDK.

How to install Eclipse Luna IDE


Java: Time based thread locking

Question: I am looking out for a way in java, by which we can achieve time based locking for java threads OR may be time based interruption.
consider this.
A java thread calls following function,
private DATA getData() {
   DATA data;
   synchronized(dataLock) {
       data = fetchData()
   }
   return data
}

Now assume call to fetchData() is hung, doesn't return.
is there a way to timeout on this lock(dataLock) here, or interrupt this thread ?
Comment: Ditto what Persixty said:  The real problem is how to "unstick" a `fetchData()` call.  That question has nothing to do with threads or locks, and you can only answer it by looking at the `fetchData()` implementation.  If there's no way to "unstick" it, then maybe you can change your architecture so that `fetchData()` is called in a subordinate process that you can kill and re-start if needed.  (Been there! Done that!)
Comment: I don't see why the lock is relevant. If the method `fetchData()` doesn't (somehow) time-out a 1 threaded application will hang. If it does time-out then a multi-threaded application will on return from `fetchData()` (or when it throws a time-out exception) release the `dataLock`. The question here is really "is there a time-out constrained way of calling `fetchData()`) to which the answer is 'no idea'. What does `fetchData()` do. Must libraries offer some time-out capability or even an asynchronous 'cancel' method or (in Java) if 'fetchData()` is using an interruptible channel (or similar).
Comment: @jameslarge Exactly. Work out a way to 'unstick' `fetchData()` and the lock isn't a problem. Fail to find a way to 'unstick' `fectData()` and the lock is irrelevant. What library or source is `fetchData()` using? Can you post the methods code?
Comment: Possible duplicate of [Using Timeout to avoid deadlock in Java multithreading](https://stackoverflow.com/questions/13741479/using-timeout-to-avoid-deadlock-in-java-multithreading)
Comment: @Persixty, method 'getData()' shall be called by multiple threads, assume 'fetchData()' once stuck, would never return/timeout. Here I was trying to find a "time based locking" alternative of 'synchronized(dataLock)' call.
Comment: @jameslarge : Thanks for suggestion, this sounds good to use a subordinate process to call `fetchData()`. Considering you have no control on `fetchData()`, it a third-party library method.
Comment: @Persixty: Its a generic problem I stumbled upon, was trying to figure out a solution for it.
Comment: @CuriousGeorge It is and the answer is in making `fetchData()` time-out or be interruptible (say if it normally blocks until input arrives). No manipulation of the lock will get you anywhere without that facility on `fetchData()`.
Answer: Use the more flexible Lock interface (i.e. for example ReentrantLock), which allows you to call tryLock(long time, TimeUnit unit) to prevent waiting forever.
Comment: That depends on the `fetchData()` method itself. You can of course interrupt the thread and hope that's enough to stop it doing whatever it's doing. You could subclass a lock implementation to provide access to the `Thread` that's currently holding the lock (it's a protected method in `ReentrantLock`).
Comment: Thanks for comment @Kayaman, but the requirement is different. Its not about timing other threads, rather timing out this thread.
Comment: No, there's no such built-in transaction functionality in any programming language that I know of. If a thread gets stuck, another thread is needed to try to interrupt it. Emphasis on *try*. There's no guarantee that you can timeout a runaway thread.
Comment: @CuriousGeorge I think the above answer suffices of timing out current thread. Please be clear on "Its not about timing other threads, rather timing out this thread"
Comment: @Kayaman, thanks for the idea, I can have some work around this.
Comment: @Aarish, What I meant was, instead of other threads calling `tryLock(timeout, unit)`, and timing out on this lock. Was looking for something such that while acquiring a lock, if we could specify a timeout, so that after acquiring lock, if current thread is stuck forever for some reason, it would be interrupted.
Comment: @Kayaman I also have similar question related to locking [here](https://stackoverflow.com/questions/47107331/how-to-make-sure-that-i-am-not-sharing-same-socket-between-two-threads-at-a-same). Wanted to see if you can help me out.

Java: Time based thread locking


Textarea maximalsize in Borderlayout

Question: I have a simple problem but I found no good solution for it. I have a JFrame with components at SOUTH, NORTH, EAST, and CENTER. On CENTER is my problem. On center I have a JPanel with a Borderlayout and 2 JTextAreas (one on NORTH, one int the CENTER).
I want that the first panel begins always on top of the panel and stretch maximum (if needed) to the middle of the panel, not more. The second area should begin at the end of the first area. If one of both text areas is to big, there should appear a JScrollPane.
What is the best Way to realize that? Should I use a other layout for the panel?
Here is my little execute example for it:
public class myGUI {

    public static void main(String[] args) {
        new myGUI();
    }

    public myGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

    //Add Content at South, West and North....
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());
        centerPanel.add(new JScrollPane(new JTextArea("AREA")), BorderLayout.NORTH);
        centerPanel.add(new JScrollPane(new JTextArea("AREA2")), BorderLayout.CENTER);
        frame.add(centerPanel);
        frame.setVisible(true);
    }
}

Possible scenarios of the center panel:

SOLUTION with help from @Hovercraft Full Of Eels
public class MyGUI {
public static void main(String[] args) {
    new MyGUI();
}

private static GridBagConstraints constraint = new GridBagConstraints();

public MyGUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);

    frame.add(new JLabel("NORTH!"), BorderLayout.NORTH);
    frame.add(new JLabel("EAST!"), BorderLayout.EAST);
    frame.add(new JLabel("SOUTH!"), BorderLayout.SOUTH);

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new GridBagLayout());
    changeConstraint(0,0);

    JTextArea text1 = createTextArea("11111111111111");
    centerPanel.add(text1, constraint);
    changeConstraint(0,1);

    JTextArea text2 = createTextArea("2222222222222");
    centerPanel.add(text2, constraint);
    JScrollPane scroll = new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    frame.add(scroll, BorderLayout.CENTER);
    frame.setVisible(true);
}

/**
 * Create a Gridbag Constraint
 * @param text
 * @return
 */
private void changeConstraint(int gridx, int gridy){
    constraint.anchor = GridBagConstraints.FIRST_LINE_START;
    constraint.fill = GridBagConstraints.HORIZONTAL;
    constraint.weighty = 0;
    constraint.weightx = 1.0;
    constraint.gridx = gridx;
    constraint.gridy = gridy;
}

/**
 * Create a Textarea
 * @param text
 * @return
 */
private JTextArea createTextArea(String text){
    JTextArea textarea = new JTextArea(text);
    textarea.setWrapStyleWord(true);
    textarea.setLineWrap(true);
    return textarea;

}

}
Comment: Pictures/images of what you desire, please.
Comment: "I want that the first panel begins always on top of the panel and stretch maximum (if needed) to the middle of the panel" - Well if it stretches TO the middle, where does it start? Do you mean streched down/upwards or to the sides? Be waaaay more specifc
Comment: i add a picture of the different szenarios, i hope it helps to understand my problem. The double border should be a scrollpane ^^
Answer: One possibility: Consider creating a JPanel that uses GridBagLayout, and adding both JTextAreas to this JPanel, making sure to set their weightx to 0 and weighty to a non-zero value, say 1.0. Then place that JPanel into a JScrollPane and the JScrollPane into your GUI.
Comment: Thank you. I add my solution on my first post. I have only one Problem: The panel / textboxes doesnt begin on the top of the "CENTER" position, but i cant change it with the anchor of gridbag.

Textarea maximalsize in Borderlayout


What does closed form solution usually mean?

Question: This is motivated by this question and the fact that I have no access to Timothy Chow's paper What Is a Closed-Form Number? indicated there by
Qiaochu Yuan.
If an equation $f(x)=0$ has no closed form solution, what does it normally
mean? Added: $f$ may depend (and normally does) on parameters.
To me this is equivalent to say that one cannot solve it for $x$ in
the sense that there is no elementary expression $g(c_{1},c_{2},\ldots
,c_{p})$ consisting only of a finite number of polynomials, rational
functions, roots, exponentials, logarithmic and trigonometric functions,
absolute values, integer and fractional parts, such that
$f(g(c_{1},c_{2},\ldots ,c_{p}))=0$.
Comment: "Closed form" is more of a general idea than a precise one. You fix some objects that you consider "elementary".  Then you fix some operations that take as input collections of things, where "things" includes your elementary objects.  And you ask what can you generate from that.  The things you can generate are called closed-form.  Usually people stick to finitary constructions even if they allow fairly complicated "elementary" functions.
Comment: Can you access it from his webpage?  http://math.mit.edu/~tchow/cv.html
Comment: @Ryan Budney: your comment seems to be a good answer that you  might transform in a formal one.
Comment: @Américo Tavares: to prevent triviality you should probably require that the c_i are rational, which I think is what you meant but did not say.
Comment: @DouglasS.Stones I don't have permission to access the link. Don't know if it's the same for everyone.
Answer: I would say it very much depends on the context, and what tools are at your disposal. For instance, telling a student who's just mastered the usual tricks of integrating elementary functions that
$$\int\frac{\exp{u}-1}{u}\mathrm{d}u$$
and
$$\int\sqrt{(u+1)(u^2+1)}\mathrm{d}u$$
have no closed form solutions is just the fancy way of saying "no, you can't do these integrals yet; you don't have the tools". To a working scientist who uses exponential and elliptic integrals, however, they do have closed forms.
In a similar vein, when we say that nonlinear equations, whether algebraic ones like $x^5-x+1=0$ or transcendental ones like $\frac{\pi}{4}=v-\frac{\sin\;v}{2}$ have no closed form solutions, what we're really saying is that we can't represent solutions to these in terms of functions that we know (and love?). (For the first one, though, if you know hypergeometric or theta functions, then yes, it has a closed form.)
I believe it is fair to say that for as long as we haven't seen the solution to an integral, sum, product, continued fraction, differential equation, or nonlinear equation frequently enough in applications to give it a standard name and notation, we just cop out and say "nope, it doesn't have a closed form".
Comment: (cont'd) Much later, when I encountered an elliptic integral for the first time, I was all "eh, just like the logarithm..." and I was never afraid/surprised of encountering new functions.
Comment: Though anecdotes are not admissible as data, I have to say that for me personally, the reason for my being rather comfortable around these integrals is that I have had the pleasure(?) to be taught the natural logarithm as the integral of the reciprocal function. I had never encountered the natural previously at the time. I knew base-10 logarithms, and was familiar with the change-of-base formula, so finding out that this integral had the properties of a logarithm was quite the eye-opener. (cont'd)
Comment: So... in other words, it is mathematician's fancy way of saying "I don't know"?
Comment: I agree that "closed form" depends on context.  However, I also think the default context for most people is the one defined in the question.
Comment: My copy of Abramowitz and Stegun is rather worn out from much use, which is why when explaining this stuff to other people, I always have to ask "what do you already know?" or something to that effect. I do know I may well have to say different things to a physicist and to a freshman calculus student who encounter the same integral!
Comment: @ John D. Cook I disagree. Fractional and integer parts are not default closed forms for me. On the other hand, factorial and Gamma function are included
Answer: To better understand closed forms, you may want to familiarize yourself with what's called Differential Algebra.  Just as number theory relies on abstract structures such as rings, fields, ideals, etc. to express roots of algebraic equations using elementary numbers, similarly there is a parallel apparatus for expressing functions (i.e. solutions of differential equations) using differential rings, fields, ideals  called Differential Algebra.  It is this underlying mechanism that defines which functions can be expressed as "closed forms".
Parallels:

Similar to splitting fields for algebraic equations, there is a parallel Galois theory with Picard-Vessiot extensions and what not.
Similar to correspondence between subfields of number fields and Galois subgroups, on the differential side, there is a correspondence between differential subfields and subgroups of algebraic groups.
Just as algebraic equations can be determined to be solvable by radicals, similarly linear differential equations can be determined to be solvable by exponentials, Liouvillian functions, etc.  There is an ascending tower of differential fields which can be built.

There is more... I am no expert in this differential algebra field but if you want some freely available references, see

Seiler Computer Algebra and differential equations
Van der Put Galois theory of differential equations, algebraic groups and Lie algebras
Papers by Michael F. Singer are good. See for example "Galois theory of linear differential equations".
Check the Kolchin seminar in Differential Algebra
Answer: See the links below for Timothy Chow's article.
a)
[Borwein/Crandall 2013] tries to give an answer.
$\ $
b)
Let us assume, $f(x)=0$ is to be solved for $x$.
If the equation $f(x)=0$ has no closed-form solution, the equation has no solution which can be expressed as a closed-form expression.
A mathematical expression is a closed-form expression iff it contains only finite numbers of only constants, explicit functions, operations and/or variables.
Sensefully, all the constants, functions and operations in a given closed-form expression should be from given sets.
c)
Let us say, a (partial) closed-form inverse ($f^{-1}$) is a (partial) inverse (= inverse function) whose function term can be expressed as closed-form expression.
Because of $f(x)=0$ and the definition of a (partial) inverse $f^{-1}(f(x))=x$, the following holds: $f^{-1}(f(x))=f^{-1}(0)$, $x=f^{-1}(0)$. And therefore:
If an equation $f(x)=0$ has no closed-form solution, the function $f$ has no partial closed-form inverse, or a partial closed-form inverse exists but is not defined for the argument $0$ of the right side of the equation. This means, $x$ cannot be isolated on only one side of the equation
- by applying a partial closed-form inverse of $f$,
- by only applying the partial closed-form inverses and inverse operations of the closed-form functions respective operations which are contained in the expression $f(x)$.
The existence of a partial closed-form inverse is a sufficient but not a necessary criterion for the existence of a closed-form solution.
d)
Lin and Chow ask for closed-form numbers. A closed-form number is a number that can be generated from a rational number by only closed-form functions.
e)
The elementary functions are a special kind of closed-form functions. The elementary numbers of Lin and the exponential-logarithmic numbers of Chow are special kinds of closed-form numbers.
If $f$ is an elementary function, the following statements are equivalent:
- $f$ is generated from its only argument variable in a finite number of steps by performing only arithmetic operations, power functions with integer exponents, root functions, exponential functions, logarithm functions, trigonometric functions, inverse trigonometric functions, hyperbolic functions and/or inverse hyperbolic functions.
- $f$ is generated from its only argument variable in a finite number of steps by performing only arithmetic operations, exponentials and/or logarithms.
- $f$ is generated from its only argument variable in a finite number of steps by performing only explicit algebraic functions, exponentials and/or logarithms.
Whereas Ritt and Lin allow explicit and implicit algebraic functions, Chow restricts the approved algebraic operations to the explicit algebraic functions, that are the arithmetic operations.
$\ $
[Borwein/Crandall 2013] Borwein, J. M.; Crandall, R. E.: Closed Forms: What They Are And Why We Care. Notices AMS 60 (2013) (1) 50-65
[Chow 1999] Chow, T. Y.: What is a Closed-Form Number? Amer. Math. Monthly 106 (1999) (5) 440-448 or https://arxiv.org/abs/math/9805045
[Lin 1983] Ferng-Ching Lin: Schanuel's Conjecture Implies Ritt's Conjectures. Chin. J. Math. 11 (1983) (1) 41-50
[Risch 1979] Risch, R. H.: Algebraic Properties of the Elementary Functions of Analysis. Amer. J. Math 101 (1979) (4) 743-759
[Ritt 1925] Ritt, J. F.: Elementary functions and their inverses. Trans. Amer. Math. Soc. 27 (1925) (1) 68-90
Answer: One usually refers to "closed form" as a solution involving functions we commonly know of.  This class of functions varies from problem to problem, field to field.  For example, one might say $x^5-x+1=0$ has no closed form solution because $x$ can't be solved for in terms of radicals.  However, it can be solved in terms of Bring radicals.  Here, closed form might mean "a combination of rational numbers, addition, multiplication, and radicals".
One could extend "closed form" to mean a solutions involving elementary functions, which are functions made of a finite composition of arithmetic operations, exponentials, logarithms, constants, and solutions to algebraic equations.  Under this definition of closed form, $x^5-x+1=a$ has a closed form solution since it is an algebraic equation.
However, upon entering calculus, you will find there are many integrals you cannot solve.  For example,
$$\int\sqrt{1+x^3}~\mathrm dx,~\int e^{-x^2}~\mathrm dx$$
These are antiderivatives of elementary functions, though they themselves are not elementary.  One can make these integrals as "closed form" by having it be the class of Liouvillian functions, which are elementary functions and their antiderivatives.

So as your problems get harder and your field changes, closed form will have a different meaning to you (and not limited to the above).
For most purposes, I think closed form is implied to mean elementary function though.
Answer: My take on this question, from a practical standpoint:
In the world of computers, there are no "closed forms."
"Closed form" is a mathematician's label for certain mathematical expressions which he deems "elementary."  More specifically, it's a way of saying, "We don't care about the algorithms for evaluating this expression."
What makes a "closed form" is that the algorithmic steps involved in computing it are regarded in algebraic manipulation as one atomic step.

A classic example of this is the factorial, $n!$.  Strictly speaking, the definition involves a recurrence.  However, it comes up in practice so often, mathematicians label it a "closed form" itself.
Now, perhaps some clever mathematical algorithms expert might come up with a more efficient way to compute the factorial of arbitrary values of $n$, which does not involve actually performing $n-1$ multiplication steps.  The point I'm making is that the label "closed form" doesn't depend on that better algorithm being known, or even being possible.  It just means, "We are regarding the algorithm for computing this as not a crucial question (for the current text)."

In fact, if you get right down to it, $f(x)=x+1$ is the ultimate closed form.  The unary "increment" operator.
Adding bigger numbers (the binary "sum" operator) can be seen as a "recurrence" or repeated application of the "increment" operator.
Multiplication itself is repeated application of the "sum" operator, and likewise exponentiation is a repeated application of multiplication.
But all of these are considered as "closed forms."  The concept is not a fixed one.

To quote Concrete Mathematics:

We could give a rough definition like this: An expression for a quantity f(n) is in closed form if we can compute it using at most a fixed number of "well known" standard operations, independent of n. For example, 2n – 1 and n(n + 1)/2 are closed forms because they involve only addition, subtraction, multiplication, division, and exponentiation, in explicit ways.
The total number of simple closed forms is limited, and there are recurrences that don't have simple closed forms. When such recurrences turn out to be important, because they arise repeatedly, we add new operations to our repertoire; this can greatly extend the range of problems solvable in "simple" closed form. For example, the product of the first n integers, n!, has proved to be so important that we now consider it a basic operation. The formula 'n!' is therefore in closed form, although its equivalent '1·2·. . .·n' is not.
Answer: Closed form solution is a solution that can be represented without using limits, and as such, integrals, infinite sums, derivatives. Only using functions, their compositions and arithmetic operations on them. The class of functions allowed may vary. By default it usually allows elementary functions plus Gamma function, plus Polygamma function, plus Hurwitz zeta function. Sometimes, service function like "integer part", "absolute value", "argument", "real part", "imaginary part" may be allowed.


Significado de (void *)

Question: Qual o significado de chamar uma função com uma que era int e é passada como (void *)?
Se a variável foi declarada como int porque se passa ela como parâmetro para uma função
*(void *)variavel* ?
Exemplo
int var = 10;

teste((void *)var);

Answer: O (void *) quer dizer que é um ponteiro para uma variável não especificando o tipo da variável.
Por exemplo, pode-se ter o mesmo conceito com (int *) onde é um ponteiro para uma variável do tipo int, especificando o tipo.
A Microsoft tem um documento explicando um pouco isso em http://msdn.microsoft.com/en-us/library/y31yhkeb(v=vs.120).aspx

Significado de (void *)