A problem with the expectation of a Pareto

Question: My course notes (3rd-year module in Bayesian Statistics, unpublished) contain the following section.

Assume we have data on the number of people queuing at an ATM at a specific hour for several
randomly chosen days, and that we are interested in the mean time between two consecutive arrivals to the queue at some arbitrary point within this time.
First, let $\textbf{x} = \{x_1,\dots,x_n\}$ represent the observed data and assume these are a random sample from $\text{Po}(x_i\;|\;\lambda)$. We will use the conjugate prior $\text{Ga}(\lambda\;|\;a,b)$ to represent our prior knowledge, thus $$\pi(\lambda\;|\;\textbf{x})\propto\left[\lambda^se^{-n\lambda}\right]\times\left[\lambda^{a-1}e^{-b\lambda}\right]=\text{Ga}(\lambda\;|\;a^\ast,b^\ast),$$ where $a^\ast=a+s$ and $b^\ast=b+n$, with $s=\sum_{i=1}^nx_i$ a sufficient statistic for $x_i$.
Using standard queuing theory, the time within two consecutive arrivals, $y$, is distributed
$\text{Ex}(y\;|\;\lambda)$. Thus, the predictive distribution is $$f(y\;|\;\textbf{x})=\int_0^\infty\lambda e^{-y\lambda}\frac{(b^\ast)^{a^\ast}}{\Gamma(a^\ast)}\lambda^{a^\ast-1}e^{-\lambda b^\ast}\;\text{d}\lambda=\frac{a^\ast}{b^\ast}\left(1+\frac{y}{b^\ast}\right)^{-(a^\ast+1)}.$$ Finally, the expected predictive time between consecutive arrivals is $$\mathbb{E}[y\;|\;\textbf{x}]=\int_0^\infty y\frac{a^\ast}{b^\ast}\left(1+\frac{y}{b^\ast}\right)^{-(a^\ast+1)}\;\text{d}y=\frac{b^\ast}{a^\ast-1}.$$

But, by my reasoning, \begin{align}
& \begin{aligned} f(y\;|\;\textbf{x})
& = \frac{a^\ast}{b^\ast}\left(1+\frac{y}{b^\ast}\right)^{-(a^\ast+1)} \\
& = \frac{a^\ast b^{\ast a^\ast}}{(y+b^\ast)^{a^\ast+1}} \\
& = \text{Pa}(y+b^\ast\;|\;a^\ast,b^\ast) \end{aligned} \\[1em]
\therefore \hspace{1em} & \begin{aligned}[t]
\mathbb{E}[y\;|\;\textbf{x}]
& = \mathbb{E}[y+b^\ast\;|\;y\sim\text{Pa}(a^\ast,b^\ast)] \\
& = \mathbb{E}[y\;|\;y\sim\text{Pa}(a^\ast,b^\ast)] + b^\ast \\
& = \frac{a^\ast b^\ast}{a^\ast-1} + b^\ast \\
& = \frac{(2a^\ast-1)b^\ast}{a^\ast-1} \\
& \neq \frac{b^\ast}{a^\ast-1} \text{ (unless $a^\ast=1$)}.
\end{aligned}
\end{align}
What's gone wrong?
Comment: You haven't integrated correctly.  Use $$\int_0^\infty x(1+x)^{-(1+a)}\,\mathrm dx=\int_0^\infty \frac{1}{(1+x)^a}-\frac{1}{(1+x)^{a+1}}\,\mathrm dx=\frac{1}{a-1}-\frac{1}{a}=\frac{1}{a(a-1)}.$$
Comment: @whuber Thanks, that's useful, but I didn't integrate; I used the linearity of the expectation operator with a formula for the expectation of a Pareto distribution that I got from a formula sheet. Could you point out the problem with that line of reasoning?
Comment: Compare your work with the correct result until you see a discrepancy: that will locate at least one error.
Comment: I'm afraid I can't even make sense of it, because your notation "Pa" is undefined. Although one would guess it is referring to a Pareto distribution, I am unable to see how that is directly related to an integral whose *lower limit is $1.$*  The details matter, *especially* the meanings of your parameters $a^*$ and $b^*.$ I therefore encourage you to write your steps in detail.
Comment: @whuber Yes, I intend Pa to mean a Pareto distribution. I took it from my formula sheet and assumed it was standard notation. From the wikipedia [article](https://tinyurl.com/yk7juhtf) on the Gamma distribution I assume $a$ and $b$ are shape and rate, and the course notes use $^\ast$ for posterior parameters, which here turn out to fit a Pa. My formula sheet gives $b^\ast$ (that is, the parameter in the second position, which it actually calls $\beta$) as the lower limit of the Pareto distribution's support. What integral with a lower limit of 1 do you mean? and are there other details needed?
Comment: It is dangerous to assume everyone uses your convention for parameters of a distribution.  Even the ubiquitous "$\mathscr N(\mu,\sigma)$" notation for Normal distributions has *three* different standard meanings (the second parameter could be the SD, the variance, or the precision).
Answer: Your basic insight of recognising the Pareto distribution is a good way to look at this, but you are just making a small error in your reasoning about the density, which is messing things up.  Since $f(y|\mathbf{x}) = \text{Pa}(y+b^* | a^*,b^*)$ you therefore have:$^\dagger$
$$y|\mathbf{x} \sim \text{Pa}(a^*,b^*) - b^*.$$
(Note that we subtract $b^*$ from the Pareto variable; we don't add it.)  Consequently, you should be using a minus sign for the expectation computation, which gives:
$$\begin{align}
\mathbb{E}[y|\textbf{x}]
&= \mathbb{E}[r - b^* | r \sim \text{Pa}(a^*,b^*)] \\[12pt]
&= \mathbb{E}[r | r \sim \text{Pa}(a^*,b^*)] - b^* \\[6pt]
&= \frac{a^* b^*}{a^*-1} - b^* \\[6pt]
&= \frac{a^* b^*}{a^*-1} - \frac{a^* b^* - b^*}{a^*-1} \\[6pt]
&= \frac{b^*}{a^*-1}. \\[6pt]
\end{align}$$

$^\dagger$ This is a general rule of probability that applies when we shift the location of a random variable by a constant.  In general, if we start with a random varable $A$ with density $f_A$ then the random variable $R \equiv A+k$ has distribution function:
$$F_R(r)
= \mathbb{P}(R \leqslant r)
= \mathbb{P}(A+k \leqslant r)
= \mathbb{P}(A \leqslant r-k)
= F_A(r-k),$$
which then gives it the density function:
$$f_R(r) = \frac{d}{dr} F_R(r) = \frac{d}{dr} F_A(r-k) = f_A(r-k).$$
As you can see, using the location shift $+k$ on the random variable translates to imposing the shift $-k$ inside the density argument.  This is because the point $R=r$ corresponds to $A=r-k$.
Comment: I have added some further detail on the location shift to show you why it works the way I say.
Comment: I think this is the answer I was looking for, but I don't quite follow the subtraction reasoning. I would have thought that $$y|\textbf{x}\sim\text{Pa}(a^\ast,b^\ast)-b^\ast\implies f(y|\textbf{x})=\frac{a^\ast b^{\ast a^\ast}}{y^{a^\ast+1}}-b^\ast\neq\frac{a^\ast b^{\ast a^\ast}}{(y+b^\ast)^{a^\ast+1}}=\text{Pa}(y+b^\ast|a^\ast,b^\ast).$$
Comment: I feel like I'm missing something here. Isn't the $-b^\ast$ in $y|\textbf{x}\sim\text{Pa}(a^\ast,b^\ast)-b^\ast$ a vertical shift, but the $-k$ in $f_R(r)=f_A(r-k)$ a horizontal shift? And a couple of other things I've wondered while I've stared at this, if you have the patience: should $y|\textbf{x}\sim$ be $Y|\textbf{x}\sim$? and does $f(y|\textbf{x})=\text{Pa}(y+b^\ast|a^\ast,b^\ast)$ imply that this $f$ is $f_{Y+b^\ast}$?
Comment: For purposes of this answer, I'm following the notation in your question (taken from your course notes), which does not use the upper-case convention for random variables (so $y$ is either random or fixed depending on context).  But yes, if you were going to use the upper-case notation convention then some of my notation in this answer would change.  I'm also using your own notation in the question where you use $f$ to denote the conditional density for $y$ given $\mathbf{x}$ (so $f$ is $f_Y$, not $f_{Y+b^*}$).
Comment: And how about the vertical/horizontal issue?
Comment: I'm afraid I don't understand what you mean by that directional distinction.  Perhaps you could explain.
Comment: Isn't $\text{Pa}(y|a^\ast,b^\ast)$ a function value, so that a constant (here $b^\ast$) added to it moves the curve plotting the function value up or down?
Comment: I think you may be confusing yourself by equating $\text{Pa}(y|a^*,b^*)$ and $\text{Pa}(a^*,b^*)$.  The first is a density function and it behaves just as you are describing.  In the present context, the second is a reference to a *random variable* that follows the relevant Pareto distribution.  Consequently, the $-b^*$ applied to the latter is moving the *random variable* downward, not moving an argument in the density.
Comment: If you don't feel too barraged by questions, I'm finding this very useful. The distinction you mention is indeed one I haven't properly appreciated. If $\text{Pa}(a^\ast,b^\ast)$ is a random variable, does that mean that (if one had some time one one's hands) one could write $$\text{Pa}(a^\ast,b^\ast)\sim\text{Pa}(\text{Pa}(a^\ast,b^\ast)|a^\ast,b^\ast)$$? More generally I now realise I don't properly understand the relations of $X,y,z$ in $f_X(y)=\text{Some Distribution}(z|\text{some parameters})$. Is any pair of them obliged to be 'match' in some way, e.g. $z$ fixes one of $X$ or $y$?
Comment: That statement wouldn't really make sense --- remember that a random variable with a Pareto distribution has parameter values (attached to the distribution), but it does not have an argument value, since the random variable is not a density function.  Your statement appears to be trying to equate a random variable with a density at a specific point given by that random value, which does not really make sense.  With regard to your broader question, a lot of the meaning of these items depends on context and convention (and sometimes people write them differently).
Comment: Could I read "a random variable [...] does not have an argument value" as "a $Y$ does not come equipped with a $y$"?
Comment: Yes.  That is correct.


Action of a Lie group on a smooth manifold

Question: Suppose a Lie group acts smoothly (but not necessarily properly or freely)
on a smooth manifold $M$. Show that each orbit is an immersed submanifold
of $M$; which is embedded if the action is proper.
This is problem 15 of chapter 21 of Lee's smooth manifolds book I was searching to solve the above problem and I'm now a little confused writing an easy argument for this. I found the following argument but this is not easy enough for me to understand:

For each $p\in M$, the isotropy group $G_p = \{g\in G: g\centerdot p=p\}$ is a closed subgroup of $G$.
The quotient space $G/G_p$ has a unique smooth manifold structure, and $G$ acts transitively on this smooth manifold by left multiplication.
The orbit map $\mathscr O_p\colon G\to M$ given by $\mathscr O_p(g) = g\centerdot p$ descends smoothly to the quotient $G/G_p$ to give a smooth map $F_p\colon G/G_p\to M$ that is a bijection from $G/G_p$ onto the orbit $G\centerdot p$.
The map $F_p$ is equivariant with respect to the left actions of $G$ on $G/G_p$ and $M$, and therefore it has constant rank.
Because it is a constant-rank injection, $F_p$ is a smooth immersion, and therefore its image $G\centerdot p$ is a smoothly immersed submanifold of $M$.

Could anyone help me prove this?
Comment: In the second edition of the book, this is problem 17, chapter 21.
Answer: So I am going to do this step by step. So I belive it's clear that $G_p$ is a closed subgroup of $G$, and we can consider the proper free action $G\times G_p\rightarrow G_p$ by left translation , and since $G_p$ is a closed subgroup it also has a manifold structure and we can consider the space $G/G_p$. Now we get a bijection from $G/G_p$ to the orbit $g.p$ of $p$ since we are doing the quotient by the points that would fix the orbit. Then you have that $F_p$ is an equivariant map because $g.F_p(hG_p)=g(hp)=(gh)p=(gh)G_p p=F_p(ghG_p)$. Using the fact that the action of $G$ in $G_p$ is transitive and the equivariant rank theorem you have that $F_p$ must have constant rank and then using the fact that locally for suitable coordinates $F_p$ looks like $(x_1,...,x_r)\rightarrow (x_1,...,x_k,0,...,0)$ where $k$ is the rank of $F_p$, but since $F_p$ is injective this forces $k=r$ and so you get that it's an immersion,  and so since the image of $F_p$ is the orbit of $p$ and that $F$ is an injective immersion you get the desired result.
I don't know what much could be added , is there anything that needs clarification ?
Comment: If the action is proper will you have that it's an embedded submanifold , since we can consider again the injective immersion from $G/G_p\rightarrow M$, and if we prove that this is a proper map we have that the orbit is actually embedded. But I belive this just comes from using the commutative diagram and the fact that $\phi$ is proper we have that $\hat \phi^{-1}_p(K)=\pi\circ (\phi^{-1}_p)(K)$ @Reza.
Comment: Thank you what about the time the action is proper?
Comment: Also there's another thing one might add, if the action is  not proper you have something stronger than just an immersed submanifold you will have that the orbit at that point will be an initial submanifold , if you don't know the definition of this there's not point in going into too much detail but I just thought I should add this property.


Can you create a Finite State Machine using SOLID principles

Question: I'm currently studying game development and for one of our projects, we had to create a finite state machine that would function as a simple AI. It has always been encouraged to make your code with SOLID principles but for this project I couldn't think of a way to do it. Although it wasn't required for this project I would still like to find a way to do it. It's made in Unity c#.
public interface IState
{
    public IState CheckForState();
}

public class Walk : IState
{
    float speed = 10;

    public IState CheckForState()
    {
        if (speed > 5)
        {
            return Run;
        }
        return this;
    }
}

To make it SOLID you would have to find a way to remove 'Run' from the function cause if the 'Run' script is removed the function wouldn't work anymore, but it should still be able to get it if available.
Comment: maybe you can elaborate on why you think this implmenetation breaks with SOLID? What exactly is `Run` and where is it defined?
Comment: First thought, a higher controller that knows about run state should tell walk state what to change to if speed is slower or higher... Not sure though how you use it.
Comment: @MakePeaceGreatAgain I believe it breaks SOLID cause the `Walk` script would break if the `Run` script were to be removed, the `Walk` script is dependent on its existence and would therefore break the dependency inversion principle, as far as I'm aware. `Run` is a state the AI could be in.
Answer: There's a couple solutions that come to mind that would allow for a fully SOLID solution.
Solution 1
The first and simplest to suffice the dependency inversion principle is to inject the Run class into the Walk class, like so:
public class Walk : IState
{
    float speed = 10;
    private readonly IState _runState;
    public Walk(IState runState)
    {
        _runState = runState;
    }

    public IState CheckForState()
    {
        if (speed > 5)
        {
            return _runState;
        }
        return this;
    }
}

This solution makes it so Walk is no longer dependent on a concrete implementation of Run, but still allows it to transition to a run state. However, this does require that Walk knows which states it can transition to (which I think is a reasonable expectation).
Solution 2
You can further decouple this by representing the state transitions as objects. This would look something like this:
public interface IState
{
    public IState CheckForState();
    public float Value {get;}
}

public interface IStateTransition
{
    public IState CheckTransition(IState source);
}

public class GreaterThanTransition : IStateTransition
{
    private readonly IState _targetState;
    private readonly int _checkValue;

    public GreaterThanTransition(IState targetState, int checkValue)
    {
        _targetState = targetState;
        _checkValue = checkValue;
    }
    public IState CheckTransition(IState sourceState) => sourceState.Value > _checkValue ? _targetState : sourceState;
}

public class Walk : IState
{
    private readonly List<IStateTransition> _transitions;

    public Walk(List<IStateTransition> transitions)
    {
        _transitions = transitions;
    }
    public float Value => 10;

    public IState CheckForState() => _transitions.Select(t => t.CheckTransition(this)).FirstOrDefault(s => s != this) ?? this;
}

Then you can create a Walk instance like this:
new Walk(new List<IStateTransition>
{
    new GreaterThanTransition(new Run(...), 5)
});

This requires that a value from the state object can be used in the IStateTransition to check if a state transition needs to occur. I used an int in my example as the type of the Value property, but you could easily switch it to be a generic type.
This solution completely decouples each state and captures the state transitions as reusable components. It is more complex in some regards since the code is now split across more classes and interfaces, but it also fully incorporates the SOLID principles.


Query e Subquery no codeigniter

Question: Salve Galera , estou quebrando a cuca para montar essa query na model do CI
"SELECT *, geral_cnpj as cnpj, geral_mesref as mesref, (SELECT CEILING(( (SELECT `geral_valor_total` as valormes from tbl_geral where `geral_cnpj`=cnpj and `geral_mesref`=mesref) - (SELECT `geral_valor_total`from tbl_geral as valormesanterior where `geral_cnpj`=cnpj and `geral_mesref`=mesref-1) ) / (SELECT `geral_valor_total`as valormes from tbl_geral where `geral_cnpj`=cnpj and `geral_mesref`=mesref)*100 ) ) as valor_percentual FROM tbl_geral";

A query está correta, pois já rodei no MySQL e traz os resultados. Tentei utilizar dessa forma (que acredito que não esta correto) e me dá o erro
Error Number: HY000/1096
No tables used
SELECT *

segue o method abaixo da model
public function listar_gerais_percentual(){

   $q="SELECT *, geral_cnpj as cnpj, geral_mesref as mesref, (SELECT CEILING(( (SELECT `geral_valor_total` as valormes from tbl_geral where `geral_cnpj`=cnpj and `geral_mesref`=mesref) - (SELECT `geral_valor_total`from tbl_geral as valormesanterior where `geral_cnpj`=cnpj and `geral_mesref`=mesref-1) ) / (SELECT `geral_valor_total`as valormes from tbl_geral where `geral_cnpj`=cnpj and `geral_mesref`=mesref)*100 ) ) as valor_percentual FROM tbl_geral";

  $result = $this->db->query($q);

  return $result;

}

Comment: [ERRO MYSQL 1096 - SEM TABELAS USADAS - CODEIGNITER](https://stackoverflow.com/questions/6927940/mysql-error-1096-no-tables-used-codeigniter)
Answer: Olá! $this->db->query() não é parte do Active Record do CI, mas $this->db->get() sim, e este é um erro que aparece quando uma consulta foi mal montada via query builder. Por exemplo, chamado o método get() sem nome de tabela, ou sem ter especificado via from().
O erro não parece estar nesta função que você mostrou. Verifique se no seu controle não há outras chamadas para outros métodos do modelo. É provável que em alguma outra função do modelo esteja sobrando um get() desnecessário, ou haja uma tal consulta mal configurada.
Answer: Obrigado pela ajuda, porém resolvi dessa forma:
$query = $this->db->query($q);
return $query->result_array();
//// NO CONTROLER ficou
$this->load->model('Dados_model', 'dados');
    $dados['gerais']=$this->dados->listar_gerais_percentual();

OBS: Tentarei utilizar o get() como estudo pra ver se tbem da certo (acredito q ai preciso chamar

Query e Subquery no codeigniter


Como pegar botões em HTML com javascript

Question: Estou fazendo uma calculadora em javascript, porém travei em como posso pegar os botões desta calculadora para usa-los em javascript.
Segue código HTML da calculadora.

    <input type="button" class="num" value="9">
    <input type="button" class="num" value="8">
    <input type="button" class="num" value="7">
    <input type="button" class="oper" value="/">

    <input type="button" class="num" value="6">
    <input type="button" class="num" value="5">
    <input type="button" class="num" value="4">
    <input type="button" class="oper" value="-">

    <input type="button" class="num" value="3">
    <input type="button" class="num" value="2">
    <input type="button" class="num" value="1">
    <input type="button" class="oper" value="+">

    <input type="button" class="num" value="0">
    <input type="button" class="num" value="=">
    <input type="button" class="num" value="C">
    <input type="button"  class="oper" value="*">

Answer: Uma forma de fazer seria capturar todos os botões, em seguida iterar por eles e condicionar as ações de acordo com os valores dos botões.
Por exemplo:

const buttons = document.querySelectorAll('input[type=button]')

buttons.forEach(button => {
  button.addEventListener('click', e => {
    console.log(button.value)
  })
})

    <input type="button" class="num" value="9">
    <input type="button" class="num" value="8">
    <input type="button" class="num" value="7">
    <input type="button" class="oper" value="/">

    <input type="button" class="num" value="6">
    <input type="button" class="num" value="5">
    <input type="button" class="num" value="4">
    <input type="button" class="oper" value="-">

    <input type="button" class="num" value="3">
    <input type="button" class="num" value="2">
    <input type="button" class="num" value="1">
    <input type="button" class="oper" value="+">

    <input type="button" class="num" value="0">
    <input type="button" class="num" value="=">
    <input type="button" class="num" value="C">
    <input type="button"  class="oper" value="*">

Comment: Muito obrigado, me ajudou muito!
Answer: Boa noite, Lucas!
Eu sei que você quer exercitar, portanto vou colocar uma idéia de como você poderia fazer:
Você pode colocar uma função para cada Input e pegar da seguinte forma:
<!DOCTYPE html>

    <input type="button" class="num" value="9" onclick="pegarValor(9)">
    <input type="button" class="num" value="8" onclick="pegarValor(8)">
    <input type="button" class="num" value="7" onclick="pegarValor(7)">
    <input type="button" class="oper" value="/">

    <input type="button" class="num" value="6">
    <input type="button" class="num" value="5">
    <input type="button" class="num" value="4">
    <input type="button" class="oper" value="-">

    <input type="button" class="num" value="3">
    <input type="button" class="num" value="2">
    <input type="button" class="num" value="1">
    <input type="button" class="oper" value="+">

    <input type="button" class="num" value="0">
    <input type="button" class="num" value="=">
    <input type="button" class="num" value="C">
    <input type="button"  class="oper" value="*">

0

Espero ter ajudado!
Abraço
Comment: Muito obrigado, me ajudou muito!


My project folder is no longer a Git repository

Question: I am using Git for a project.
Up to yesterday night, the repository was up and running and I shut my computer down by the end of the day as I always do.
This morning, when trying to run git status from my project folder as I always do, I get this error: fatal: not a git repository (or any of the parent directories): .git
I know that nothing happened between the moment I shut down my computer and boot it again this morning, so I'm confused about why the repository would vanish like that. It's worth nothing that the .git folder and .gitignore file are still present in the project folder.
Now my problem here is that even if I could do a fresh checkout of the repository in a new folder, I still have code that I stashed yesterday (using git stash), including a script of SQL queries that took me several hours to write and other pieces of code I don't even exactly remember what it is because I use stashing a lot to store unfinished work that's not yet ready to be committed.
I searched the Internet and specifically this place and found no one having the same issue, which makes it even more strange.
Comment: You're in the .git dir it seems. Do cd .. Then git status
Comment: I'm already in my repository folder (i.e. `.git/..`)
Comment: If you are willing to share a zip of the whole directory I'd take a look. Based on the information you have provided I am not sure I could be of any more help. The stashed code is stored in your repo, it's just a matter of manually getting to it or fixing the .git dir.
Comment: Thanks for the proposition, but it's job-related and confidential code, so I'll pass. I've resolved to rewriting those lost changes and be less silly about having backups !
Comment: Side question: did you have a remote that you had pushed recent work to that would at least give a partial backup.
Answer: If you still have the \.git sub directory, then you have a chance. There is probably one entry that has been corrupted. I can't remember what specific contents that Git checks for to confirm if the folder is a proper repo, but these things can usually be recovered with a little perseverance.
Take a back up first. Then take another using an alternate method just in case (.git usually being a hidden file)
What is you .git directory structure - does it have all the expected content?
Did you have a remote that you'd push most of your content to to look for comparisons?
Update: see The presence of .git/HEAD is the secondary check for a git repository
Answer: Obligatory question: Do you have a backup?
If not: bad.
If yes: Restore the backup of the repository to a different directory, check out the latest branch / commit you know you were working on, if there's a stash in that backup as well, commit it to a new branch. Then overwrite the source files in that branch with the source files of your damaged repository. This gives you the difference of the last undamaged, backed up state and whatever you did in the meantime. You can stash it as well.
For this very reason I normally commit early, often and push to an external repository as backup.
Comment: Unfortunately, I have no backup. All I have is my project folder in the same state file-wise as when the git repo was working yesterday. But it's just not a repo anymore... So to make it clear, I lost no code, apart from what's in the stashes (unless there's a way to retrieve that).
Comment: @Gaël: A repository doesn't replace a backup. Having your SCM repository lost is almost as bad as loosing working tree code! Take this as a lession and always keep backups. Especially with a tool like Git, where it is so simple to push the whole tree into a remote location.
Comment: @Gaël: I need to reemphase this *in some situations loosing your SCM is even worse than loosing your working tree*. For example when developing medical application software the track of development records is even more important, than the one specfic version your might have lingering around.
Comment: shouldn't git the backup?
Comment: @Ooker: Uhh… no. Why should it? A Git repository is just a whole lot of bunch of files and directories on your filesystem. Of course, certain (commercial) remote repository services (like Github) will run backups on their systems. But Git isn't Github (and vice versa), and many people and orgs run their own repository services. And in that later case it's entirely upon them, to implement proper backup strategies.
Answer: I have the same problem, but what happened is my PC is turned off unexpectedly while doing git merge.
Apparently, the issue is that the HEAD file is corrupted after the shut down. The solution is to check .git/HEAD file and replace the content with

ref: refs/heads/develop

Note that develop is my current branch before my PC shuts down. Also, this might not work on all cases, but worth a try.
Comment: I'm not sure what caused my issue but sure enough, the HEAD file was blank. I added `ref: refs/heads/master` and that fixed it for me. Though, now I'm concerned that some other files are corrupted and I'm just not aware of it. Thanks!!
Answer: To fix this problem just move into your ".git/HEAD file", you will notice it is empty. It is not been referenced to the main/master. So inside of your .git/HEAD just type this "ref: refs/heads/master". Then you can go back to the parent directory.
Comment: This is a duplicate of an of existing answer, by @onyotzki. When answering older questions that already have answers, please make sure you provide either a novel solution or a significantly better explanation than existing answers. Remember to review all existing answers first.


Why Does Blues Have the first 4 Bars on the I chord?

Question: Why is it so common to hold the I Chord for 4 bars?
See other variations:
https://en.wikipedia.org/wiki/Twelve-bar_blues
Comment: Many blues progressions go to the IV chord for bar 2 then back to I for bars 3&4.
Comment: Because if it didn't, it wouldn't be a blues. Having got that out of the way, consider something more interesting. It doesn't sit on I for four bars, but on I7. A dominant 7th shape. Then to IV7, another dominant 7th shape. Then V7, IV7 again and home to I7. Only one of those dom7-type chords does what a dom7 OUGHT to do, resolve down a 5th/up a 4th. And that chord - the first one in the sequence, ought to be establishing the tonic, not immediately pulling away from it!
Comment: There's some blues where the same chord is used for the entire song. E.g., "Who Do You Love" by Bo Diddly.
Comment: There's a lot more detail from cognitive science and music theory, but essentially it's because that's how long it takes for us to get familiar with it and be ready to hear the IV.
Answer: This is a case where the question is probably more interesting than the answer. The answer, loosely speaking, amounts to "because that's just how it is." A similar question that comes to mind is "why is blues so often twelve bars?"
That said, being a folk form, blues, like much folk music, adheres to fairly simple chords and form — so it's playable by "regular folk". As the form developed and musicians began to experiment with it, it developed increasingly sophisticated variations.
Comment: I just like to guess: the origin may be the work song (antiphonal) with soloist (precantor) and choir.
Comment: How does that fit in with a 12-bar blues form?
Comment: @LaurencePayne Please say more about what you're asking.
Comment: There is ab 8 bar blues that is very common.
Answer: It's probably more useful to reverse things, asking why it's got any harmonic variation at all. I mean, many times in modern music, you hold on one or two chords so that whatever is important at that time can do what it wants. You can reference modal jazz like A Love Supreme, but I'm thinking that metal riffage is sitting on one chord, and John Lee Hooker songs like "Boogie Chillun" work like that.
Then, as presented by Bob Brozman, you start getting the V, then the IV, jazz, swing, sevenths everywhere, etc. You do see increasing harmonic complexity, but then, the changes start being an obstacle course and sometimes you just need to do a floor routine.
Comment: I don't know if those filler notes are chord changes. Think of 'Enter Sandman', isn't that whole riff in E the whole time? Same with the 'Master of Puppets' riff.
Comment: Talking about "chord" changes on every note in a guitar riff of solo doesn't make sense. At the very least it seems to miss the concept of passing tones. But more importantly in some styles "chord" and harmonic progression are not useful ideas. Sometimes tonic, mode, and rhythm... not chords in harmonic progression ...are the main elements. Or you can see a combination. Rock often will have riff based sections contrasting with progression based stuff.
Comment: In harder variants of heavy metal (I'd say harder than power metal and neoclassical metal; I recall this tendency in progressive metal and the extreme metal sub-genres), I actually often hear metal riffs as changing chords on *every note*, including at chromatic neighbour tones. Those riffs therefore change chords *several times per measure*.
Comment: @Dekkadeci, I'd have to listen and think about that. I know there _is_ music like that; my extreme jazz example is "Giant Steps" (which Coltrane recorded within a month of the modal _Kind Of Blue_ sessions). Sometimes the challenge is treating the changes like an obstacle course, showing you won't fall off, but sometimes it's a wide and flat and open space, like a gymnastics floor routine, where the challenge is how far you can push yourself.
Comment: @CoolGuy - Those metal riffs I was referring to change power chords *on every note*.
Comment: Isn't that similar to a guitar solo, the solo hits several notes while it is still 1 bar in 1 key?  And also 5ths (power chords) aren't chords since they're only 2 notes.    Also, Master of Puppets changes power cords every note.
Comment: It seems like that might be melody, similar to a classical guitarist finger picking through a scale with double stops while holding on chord.
Comment: Guys? "Other music behaves differently" is fine and true but really has nothing to do with how blues changes evolved.
Answer:
Why is it so common to hold the I Chord for 4 bars?

You give a link to variations on the blue chord progression, so obviously you know that the blues does not necessarily start with four bars on the tonic.
Maybe your question is "why hold the tonic for so long?" Or something like that.
Many blues songs are just riffs that repeat over all three chords I IV V. Sometimes people say you can play the blues scale over any chord in the progression. In a way, you could say there isn't any need to change chords in the blues, not in the traditional sense of matching the tones of chord and melody. In a more "traditional" song the chords change to support/match the melody, but in the blues you don't really need to do that.
Many blues will play the tonic for four bars, because there isn't a reason to do otherwise.
If you want a blues that is direct and unpretentious, dispense with dressing up the progression with fancy changes.
Answer: A lot of music relies on repetition - of notes, and of timings. There's a lot of Blues that uses a two bar phrase that gets repeated. Playing over the same two bars worth of chords, and repeating necessitates four bars of that same chord - generally I. Then continuing the process, the same phrase (two bars again) can be repeated, but a 4th higher over the IV chord. Again, repetition comes to the fore, and the original phrase can be re-played over bars 7 and 8.
Answer: It's really about grounding.  In any pattern, you need to set a base from which to jump.  4 bars is just a really good way to do that musically.  It's like saying "this is where we are starting from.  This is home!"  Then we hit IV and then back to I, reinforcing it.  Once we have adequately established this grounding, then we can play around with more complex progressions and, generally, the listener will know that we will end up back home again.


Views: Using Pager With Single Node, Multiple Fields

Question: I created a node, that has multiple images on it. I want to use this node as the "source" for a views page showing a gallery of images.
I am having a few problems, the first and most major, is that the pager does not work.
I presume that is because all of the images are coming from a single node.
The second problem is more aesthetic; the images are not spaced correctly, and are not distributed across the width. I am not sure how to fix this problem either.
Any help would be greatly appreciated.
Answer: You can use Nivo Formatter to make your image field to a slider. There is no need to build this with views.


how to save the generated xml file using jsp?

Question: i have generated xml file using jsp,but i want the generated xml file should be saved as a file.
my code is
<code>   <?xml version="1.0" encoding="UTF-8"?>
   <%@ page contentType="text/xml;charset=ISO-8859-1" %>
   <playlist version="1" xmlns = "http://xspf.org/ns/0/">
   <title>My Band Rocks Your Socks</title>
   <trackList>
   <%! String[] sports; %>
   <%
    sports = request.getParameterValues("sports");
    if (sports != null)
    {
         for (int i = 0; i < sports.length; i++)
         {
              // out.println (sports[i]);
              String total=sports[i];
              String[] sa=total.split("[,]");
              // String[] sub=new String();
              out.print("<track>");
              for (int j=0;j<sa.length;j++)
              {
                // out.println(sa[j]);
                // out.println("sa["+j+"]="+sa[j]);
                if( j == 0)
                {
                     out.print("<location>" + sa[0] +"</location>");
                }
                else if (j == 1)
                     {
                        out.print("<image>" + sa[1] +"</image>");
                     }
                     else if( j==2)
                          {
                            out.print("<title>" + sa[2] +"</title>");
                          }

               }// end of inner for loop()
               out.print("</track>");
         //out.println();
      }// end of outer for()
    }
    //else out.println ("<b>none<b>");
  %>
  </trackList>
 </playlist>
</code>
Answer: Yes, you can. The way to do it is basically to set an extra header - which you can do on the response object.
The header to set is called Content-Disposition and the value should be something like "attachment; filename=\"foo.xml\"".
Comment: hi Bini,
I added <% response.setHeader("Content-Disposition", "attachment; filename=\"playlist.xml\""); %> worked fine but it is
 prompting to save the file in a particular location..
cant i directly have a code to directly store it in one location and overwrite the same file in the next run.
Comment: @musicking123: You can't force things onto the client machine. You can specify the filename and MIME type but that's it. From there is the browser taking over and user's choice on what to do with it.


How to keep the middle part from a text string using gsub / sub?

Question: This is what i came up with, but it doesn't work perfectly (it's more likely that some of the results are correct by accident):
dd <- c ("2day-2023-1-5--20-0.csv", "1day-2023-2-5--20-0.csv", "3day-2021-1-5--20-0.csv")
sub("day-.(.*)--.*", "\\1", dd)

Expected output would be
"2023-1-5" "2023-2-5" "2021-1-5"

Comment: I am voting to reopen the question because if the dot is seen as a typo, it will still not solve the issue and the problem can be reproduced.
Comment: try `sub(^\\dday-(.*)--.*', '\\1', dd)`
Answer: There is a dot in your pattern here day-.(.*)--.* that matches any character.
In this case it matches the first digit of the year, so that will not be in group 1, and you don't match the leading digit before "day" and that will result in a wrong result like "1023-2-5"
You could match optional digits before day and then match as least as possible characters before matching the  --
\d*day-(.*?)--.*

Regex demo
Or make the pattern more specific and match 1 or more leading digits:
\d+day-(\d{4}-\d{1,2}-\d{1,2})--.*

Regex demo
For example
dd <- c ("2day-2023-1-5--20-0.csv", "1day-2023-2-5--20-0.csv", "3day-2021-1-5--20-0.csv")
sub("\\d+day-(\\d{4}-\\d{1,2}-\\d{1,2})--.*", "\\1", dd)

Result
[1] "2023-1-5" "2023-2-5" "2021-1-5"

Comment: Thank you for solving the problem and even more for the tips you provided
Answer: A complete different, probably helpful, approach:
Here we directly extract the date part from each string in dd and convert it into a Date object.
library(parsedate)
library(lubridate)

as_date(parse_date(dd))

[1] "2023-01-05" "2023-02-05" "2021-01-05"


Sharepoint. Modify dynamic content at runtime

Question: Is there any way to modify dynamic content of SharePoint pages (let's say company news, or some other text info) at runtime before the page shows up to user? I know at least two methods how to do this:

Override some page render method and modify pure HTML before sending it.
Register startup client script and modify content on client side.

But I'm interesting if there is any standard way to do this via some events or content handlers?
Answer: It's done. The trick is to use custom IHttpHandler, then connect dll to sharepoint via web.config - it will be filtering (and changing if needed) all site contents, including dynamic AJAX request contents.


What is the meaning of "SGD scales the gradient uniformly in all directions"?

Question: I'm really newbie about neural network and optimization. When I read the references, I found this journal Wang et al 2018.
The journal stated:

One disadvantage of SGD
is that it scales the gradient uniformly in all directions;
this can be particularly detrimental for ill-scaled
problems. This also makes the process of tuning the
learning rate α circumstantially laborious

What does it mean by "it scales the gradient uniformly in all directions"?
Answer: What it's getting at, is the step size you use should depend on the curvature , ie how the gradient changes in each direction.
Imagine a narrow u-shaped sloping valley.in the direction of the U, you want to take a very small step size or you will shoot up the other side ( the gradient has actually changed direction). Along the valley, in the perpendicular direction - with low curvature - you want a large step size.
the step size you need should be large in directions that curvature is small and gradient stays roughly the same, and small in directions that the gradient is changing rapidly.
with gradient descent, you have a fixed stepsize in all directions. So in the situation of "ill-scaled" problems, where the curvature is not the same in all directions (eg  u-shape valley example). You need to choose a very small step size so you don't constantly overshoot, which means that you will travel very slowly along the valley floor.
Comment: (+1) well explanations
Answer: The gradient vector is multiplied by a scalar constant called learning rate, i.e.
$$\theta_{t+1}=\theta_t-\alpha\nabla_\theta L$$
where $\theta$ is the parameter, $L$ is the loss. This means every dimension of the gradient vector is multiplied by the same constant, i.e. scaled uniformly in all directions.
Comment: Gradient is just a vector. All directions means each element of the vector, like x, y, z directions. It's not about positivity or negativity.
Comment: In the context of the gradient itself, what do all directions mean? is the positive direction negative? or how? sorry I'm not too familiar with gradients
Comment: but isn't gradient the Slope of a Straight Line?
Comment: Slope in *all* directions, which is a vector.


Disable context menu webbrowser control

Question: I am using the WPF WebBrowser control to display a PDF. I want to disable the context menu.
I have already tried the following -

Disable context menu in Internet Explorer control -
In the constructor, added the following -
webBrowser.LoadCompleted +=new LoadCompletedEventHandler(webBrowser_LoadCompleted);

// Event Handler
public void webBrowser_LoadCompleted(object sender, NavigationEventArgs e )
{
    webBrowser.ContextMenu = null;
    var t = webBrowser.Document as System.Windows.Forms.HtmlDocument;
    // t is always coming as null, even though I can clearly see the pdf in the web browser control.
    if(t != null)
    {
        t.ContextMenuShowing += new System.Windows.Forms.HtmlElementEventHandler(t_ContextMenuShowing);
    }
}

Also checked http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7c283faf-16c8-4b4e-a362-f292e3032abb/.
Used the approach to set the registry - HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Restrictions\NoBrowserContextMenu to DWORD 1.
When I set the regisrty, the PDF does not get displayed properly.
Also, since I am using PDF to display, I cannot set - in body -
oncontextmenu="return false;"

Cannot set IsWebBrowserContextMenuEnabled as I am using WPF web browser control.
Comment: I cannot ethically help you disable the context menu in a browser. It causes far too much user pain, and can be easily worked around with a little know-how, so relying on it for security is also ethically wrong.
Answer: It could be because of the PDF visualizer that wants to show it's own context menu.
Which context menu are you seeing? The one of IE or the one of the PDF visualizer?
I would also try to use the System.Windows.Forms.WebBrowser (you can use it in WPF). I used it in a WPF application because it has more functionality than the one of WPF.
Answer: You can wrap the Windows Forms WebBrowser to be bindable and disable the context menu (and access to other properties) in an easy way:
public class WindowsFormsWebBrowser : WindowsFormsHost
{
    public static readonly DependencyProperty HtmlProperty =
        DependencyProperty.Register(
            "Html",
            typeof(string),
            typeof(WindowsFormsWebBrowser),
            new PropertyMetadata(string.Empty, OnHtmlChanged, null));

    public static readonly DependencyProperty IsContentMenuEnabledProperty =
        DependencyProperty.Register(
        "IsContentMenuEnabled",
        typeof(bool),
        typeof(WindowsFormsWebBrowser),
        new PropertyMetadata(true, OnIsContextMenuEnabledChanged));

    private readonly System.Windows.Forms.WebBrowser webBrowser = new System.Windows.Forms.WebBrowser();

    public WindowsFormsWebBrowser()
    {
        Child = webBrowser;
    }

    public string Html
    {
        get { return GetValue(HtmlProperty) as string; }
        set { SetValue(HtmlProperty, value); }
    }

    public bool IsContentMenuEnabled
    {
        get { return (bool)GetValue(IsContentMenuEnabledProperty); }
        set { SetValue(IsContentMenuEnabledProperty, value); }
    }

    private static void OnHtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var browser = d as WindowsFormsWebBrowser;

        if (browser == null)
        {
            return;
        }

        browser.webBrowser.DocumentText = (string)e.NewValue;
    }

    private static void OnIsContextMenuEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var browser = d as WindowsFormsWebBrowser;

        if (browser == null)
        {
            return;
        }

        browser.webBrowser.IsWebBrowserContextMenuEnabled = (bool)e.NewValue;
    }
}

Here the steps to reference Windows Forms controls in a WPF project.
Answer: Here is a solution:
private void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    ((WebBrowser)sender).InvokeScript("eval",
        "$(document).contextmenu(function() { return false; });");
}

Answer: Just use
// Disable the Context menu inside the web browser
webBrowser1.IsWebBrowserContextMenuEnabled = false;

i tried this in Windows Applications
Comment: He's using WPF, not Windows Forms.

Disable context menu webbrowser control


Nice way of thinking about the Laplace operator... but what's the proof?

Question: Here's a nice fact: roughly speaking, the Laplace operator gives you the difference between the value of a function at a point and the average value at "neighboring" points.
More precisely, in $\mathbb{R}^n$ let $S_r(x)$ be the $(n-1)$-dimensional sphere of radius $r$ centered at the point $x$, let $V_r$ be the volume of this sphere, and let $d\sigma$ be the volume element on this sphere.  Then at every point $x \in \mathbb{R}^n$
$$ \lim_{r \rightarrow 0} \frac{\int_{S_r(x)} f d\sigma}{V_r} - f(x) = \frac{r^2}{2n} \Delta f(x) + \bar{o}(r^2) $$
for all $C^2$ functions $f$ on $\mathbb{R}^2$.  So far, however, I've been unable to prove this fact.  In the book I'm following (Grigor'yan, Heat Kernel and Analysis on Manifolds) the only theorem that's really been introduced so far is one of Green's identities:
$$ \langle u, \Delta v \rangle = \langle \nabla u, \nabla v \rangle, $$
where at least one of $u,v$ is compactly supported and $\langle \cdot, \cdot \rangle$ denotes the inner product over $\mathbb{R}^n$.  So, it seemed natural to consider any compactly-supported test function $g \in C^1(\mathbb{R}^n)$, in which case the formula above would look something like
$$ \frac{\int_{S_r(x)}\langle f, g \rangle d\sigma}{V_r} - \langle f, g \rangle = \frac{r^2}{2n} \langle \nabla f, \nabla g \rangle + \langle g + \bar{o}(r^2) \rangle. $$
Not sure where to take it from here, though (or even if this is the right direction!).  Any hints/tricks are much appreciated.  (For the record, I am not solving this problem as a homework exercise.)
Finally, a more minor question: what does the bar signify in $\bar{o}(r^2)$?
Thanks!
Comment: In your first formula, the left-hand side doesn't depend on $r$, but the right-hand side does...
Comment: It seems natural to work in spherical coordinates and Taylor expand $f$ in $r$. But I haven't thought this through.
Comment: I have seen it done via Stokes (i.e., divergence) theorem, maybe in Courant and Hilbert. The integral of $\Delta f = \nabla \cdot \nabla f$ in a small ball is approximated by its volume times the value of the integrand at the centre (i.e., $x$). On the lhs of your equation, recognize $f(y) - f(x)$ as an approximation to the flux of the gradient when y is on a very small sphere centred at $x$.
Comment: Are you sure there isn't a sign error in your second displayed equation?
Answer: Given a point $p$ in the domain of the function $f$, consider the function which is the average value $A(r)$ of $f$ over the sphere $S_r$ of radius $r$ centred at $p$.  If $S^{n-1}$ is the unit sphere in $\mathbb R^n$ then you can write the function as:
$$A(r) = \int_{S^{n-1}} f(p+rx)dx$$
I'm integrating with respect to the standard content on the sphere, but rescaled so that the sphere has unit content.
Differentiating $A(r)$ with respect to $r$ gives
$$\frac{dA}{dr} = \int_{S^{n-1}} x\cdot\nabla f(p+rx)dx$$
in the above equation $x \in S^{n-1}$ is a unit vector, and the $\cdot$ is dot product of vectors.
The above can be interpreted as a flux integral, so Gauss's theorem about flux integrals applies giving
$$\frac{dA}{dr} = r\int_{D^n} \nabla^2 f(p+rx)dx$$
now $x$ is a variable for the unit ball $D^n$.
So this tells you the first few terms of the Taylor expansion for the function $A$, in particular $A(0)=f(p)$, $A'(0)=0$, and so on with the next terms being some multiple of $\nabla^2f(p)$.  A quick calculation says it should be $\frac{\nabla^2(f(p))}{n}$ but perhaps I've been too sketchy.
Comment: Does this proof work also on a Riemannian manifold? (The resulting operator should then be the Laplace-Beltrami operator.

Can anyone suggest a reference for this "derivation" of the Laplace-Beltrami as averaging on small balls?
Comment: It works on Riemann manifolds that have local spherical symmetry.  I doubt it would work on anything else.  My argument above isn't particularly detailed on finding the constants of proportionality.  If you go through the argument and slowly check, you'll see I'm using the local spherical symmetry of Euclidean space in the argument.
Comment: So you say that the classical interpretation of the Laplace-Beltrami operator as the average on small balls is limited to isotropic Riemannian manifolds? This would be quite surprising to me. Or you perhaps mean that this proof, using Stokes theorem, does not generalizes to the general non-isotropic case and one has to go through explicit computations (e.g. in normal coordinates)?
Comment: The theorem is not true in non-isotropic manifolds.  I suppose you could create a variant of the laplacian that depends on the curvature tensor to "correct" the statement of the theorem.  But the classical interpretation of the laplacian depends on spherical symmetry.


tic-toe-program loop not closing

Question: My problem is when ever the winning conditions are met instead of ending the program it goes back to the loop which decides if a position is taken or not. I tried it without the four breaks and it did not work either.
#include <iostream>
using namespace std;

int main()
{
    int a,b,c,d,e,f,g,h,i,x,y,winning,repeat,q,r;
    int array[3][3] = {{a,b,c},{d,e,f},{g,h,i}};

    winning=6;

for(q = 0;q<=2;q++)
{
      for(r = 0;r<=2;r++)
            {
              array[q][r]=0;
              cout << "Row: " << q << "Column: " << r << "Value: " << array[q][r] << endl;
            }
}

while (winning = 6)
{
  cout << "Player 1 Row: ";
  cin >> x;

  cout << "Player 1 Column: ";
  cin >> y;

  cout << " " << endl;

  if (array[x][y] != 0 )
  {
  repeat=1;
           while (repeat=1)
           {
           cout << "That row is taken: ";

           cout << "Player 1 Row: ";
           cin >> x;

           cout << "Player 1 Column: ";
           cin >> y;

           cout << " " << endl;

           if (array[x][y] == 0)
           {
              repeat=0;
           }
           }
  }

  array[x][y] = 1;
  cout << array[x][y];

  cout << "Player 2 Row: ";
  cin >> x;

  cout << "Player 2 Column: ";
  cin >> y;

  cout << " " << endl;

  if (array[x][y] != 0 )
  {
  repeat=1;
           while (repeat=1)
           {
           cout << "That row is taken: " << endl;

           cout << "Player 2 Row: ";
           cin >> x;

           cout << "Player 2 Column: ";
           cin >> y;

           cout << " " << endl;

           if (array[x][y] == 0)
           {
              repeat=0;
           }
           }
  }

  array[x][y] = 2;

  if (array[0][0] != 0)
  {
  if (array[0][1] != 0)
  {
  if (array[0][0] == array[0][1])
  {
     if (array[0][1] == array[0][2])
     {
     winning=array[0][0];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[1][0] == array[1][1])
  {
     if (array[1][1] == array[1][2])
     {
     winning=array[1][0];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[2][0] == array[2][1])
  {
     if (array[2][1] == array[2][2])
     {
     winning=array[2][0];
     break;
     break;
     break;
     break;
     }
  }

  if (array[0][0] == array[1][0])
  {
     if (array[1][0] == array[2][0])
     {
     winning=array[0][0];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[0][1] == array[1][1])
  {
     if (array[1][1] == array[2][1])
     {
     winning=array[0][1];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[0][2] == array[1][2])
  {
     if (array[1][2] == array[2][2])
     {
     winning=array[0][2];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[0][1] == array[1][1])
  {
     if (array[1][1] == array[2][2])
     {
     winning=array[0][1];
     break;
     break;
     break;
     break;
     }
  }
  }
  }

  if (array[1][0] != 0)
  {
  if (array[1][1] != 0)
  {
  if (array[0][2] == array[1][1])
  {
     if (array[1][1] == array[2][2])
     {
     winning=array[0][2];
     break;
     break;
     break;
     break;
     }
  }
  }
  }
}
cin.ignore();
cin.get();
}

Comment: break;break;break;break;? -1
Answer: while(winning = 6) will always return true, what you want is while(winning == 6)
The expression winning = 6 will return 6 which casted to bool will equal true. You do this a lot in your loops, remember = (assignment) and == equality.
Comment: Thank you the program closed when I changed that but only after it went through the loop that decides if a position is taken again a few times.

tic-toe-program loop not closing


Need to know the most essential JS and CSS files for a Drupal 7 page

Question: I am creating a module that has a page that is intended to be a viewer for a certain kind of content. The content itself is a Drupal Book viewer meant to behave like an epub reader. Basically I want this page to be a stand-alone, theme-independent, full-screen "player."
To achieve this effect, I don't want to load the usual long list of CSS and JS files, including those from the current theme as well as any from modules that I am not interested in using. I want the page to load only those JS and CSS files that are required for basic Drupal functionality -- e.g. I want Behaviors to work and a few other things, such as overlays.
My question is, what are considered to be the essential JS and CSS files? I realize I can find a way to just dump a list of all files by module. But I am looking for information on importance. I realize this is a little vague and that there are probably a lot of answers that begin with "It depends ..." However, there must be some items that are more fundamental than others.
I am working in Drupal 7 and using hook_js_alter() and hook_css_alter() to remove (unset) items, and a preprocess function to add items.
Comment: Welcome to Drupal Answers :) It's not really possible to answer this at the moment - specific things you want/don't want will be in specific JS/CSS files, so without knowing everything you consider as "required" (bearing in mind no CSS or JS is actually required to view an HTML page) I don't know how people will be able to respond
Comment: Clive -- yes, I thought this would be the case. I guess the thing to do is to determine the functionality one needs, and then to find the CSS and JS files associated with the modules that provide that functionality.
Comment: Painful work, but yeah, I think that's your best option really
Answer: You can achieve this by making your module load your own html.tpl.php and in that version of the html template, you simply remove references to styles and scripts.
<?php print $styles; ?>
<?php print $scripts; ?>

For a viewer, you can probably do without the reams of CSS cruft that is loaded by default and add your own bare bones css & js either through a hook or by including it in your custom html template.
<?php print $path_to_your_reader_styles; ?>
<?php print $path_to_your_reader_scripts; ?>

Answer: The answer to this question is that there is no answer. As Clive comments, it depends on what you are doing -- or, more specifically, what your base modules are and which theme you are using. At the moment, there is no registry to look at which will tell you all of the JS files and CSS files you are using, but I suppose one can achieve this effect by setting up a pristine site with all of the basic stuff and, before adding anything, inspecting the js and css arrays.


Determine if 2 lines meet 'head-to-head', 'head-to-tail' & etc.

Question: I am programming an application that renders lines in 2d space. Each line has a direction, the direction = the angle between the 1st and last vertex on the line. I am attempting to determine the direction of 2 separate lines(each contain many 2d vertices) and re-orientate(reverse) them if they don't face the direction I require.
Criteria:

If those 2 lines both face towards the intersection point then I need to reverse one of them so they sit 'head-to-tail'.
If neither face the intersection point then I need to reverse one of them so they sit 'head-to-tail'.
If one faces the intersection point and the other does not then I do nothing, they already are 'head-to-tail'.

Do you know of a methodology(mathematical function, algorithm or other) that would allow me to determine whether 2 lines meet 'head-on', 'tail-on' or 'head-to-tail'?
I think it also becomes especially difficult when the 2 lines do not physically intersect. But in this case I still need to determine their directions and ensure that IF they did intersect, that it would be a 'head-to-tail' intersection.
Comment: How is the angle between two points defined? What does it mean for a line (segment?) to 'face' a certain way? What are heads/tails? What does it mean to 'reverse' a line (segment?)?
Comment: If the intersection point is in the interior of a line segment (rather than at an end) then part of the segment "faces the intersection point" and part does not
Answer: I'm just getting started here so I can't comment only answer.  Nevertheless the following pointers are more helpful commentary than answers.
You mean 'line segment' instead of 'line'.  Lines have infinite extent, whereas line segments have finite extent, and rays have infinite extent but only in one direction from their origin.
If you want to think in terms of simplices in accordance with your invocation of vertices, you could call them edges / simplices/simplexes.
It's not clear what you mean by "angle between the first and last vertex on a line".  Vertices are points; between two points there is no angle generated.
Maybe you have a simplex with multiple vertices, and you mean the angle between the first and last edge of the simplex, i.e. the angle between the line segment between 1st, 2nd vertex and the line segment between second-to-last and last vertex.
All of this is just speculation.
You have not formulated you problem well.  Try to elaborate and be more precise.
Comment: I don't think an answer was possible. I don't know how much rep is needed to comment, but the 10 you get from my upvote will help.  Good comments on an ill-posed problem.


analyzing Hisaishi Joe's "Village in may " 3

Question:
( Picture 1 )

( Picture 2 )
I already solved the question mark on Gm in picture 1.
What I want to know is after the last measure on picture 1 (C/E,C7)
How could you go to A7 from C7 ??
I heard it's a deceptive cadence
but how does it work ???
Answer: It works in this case because there are strong melodic lines in both the melody and bass leading to A.
And because the Bb, part of the tritone which gives C7 its tension, still resolves down to A.  Letting ONE element of a tension resolve 'correctly' but doing something surprising with the other notes is a basic method of writing interesting harmony!  This isn't really a cadence point, but yes, there are similarities with a 'deceptive cadence' (or 'interrupted cadence' in Brit-speak).
And, on a broader scale, the piece started in C, made an excursion to F and now looks like it's heading back home to C (though who knows what may be around the next corner which you haven't shown us!)   Are we heading for a ii, V, I in C major?   It's very common to set this sort of thing up with a 'V of ii'.   Even when the music only strays as far as the subdominant, a 'cycle of fifths' sequence is a good way of re-establishing the tonic.
Comment: Thanks for your answer !
So your saying it works because of the Bb to A movement in the bass?
but if thats the key then does it mean it could go to any other chords that includes the A note ?
Comment: To be honest, it could go to all sorts of chords, and we could find a way to justify any of them!   Theory doesn't tell us what we MAY do, it describes what we HAVE done.   The voice-leading, and the fact that A7, Dm, G7, C is a standard route 'home' to C major, are factors that make A7 a colourful but not shocking choice.  We could have gone to Ab major...
Comment: Oh I see ! Thanks for taking your time to answer my question !! It helped me out ! Really appreciated !
Answer: you can't analyze a song by chords,you must use the scales analysis,heearing with ears and use your brain to analyze the chords is the better way than using the theory because you need a strong platform of music understanding.
Comment: Thanks for your answer!!but why can't I analyze songs by chords??what does that mean??and how do you use scales to analyze them??and what do you mean by using my ear and brain??
Comment: i mean the chord name does not make many sense,you need just know about the scale of the chords so you can easily play those chords in at every instrument.about the analyze,no one can teach you,it is about your own ability and tallent as well as the composing job
Comment: You accepted THAT answer?  !!!
Comment: Laurence Payne because I'm more professional than you,i'm learning in a music academy.
Comment: Fair enough.  It's almost 45 years since I graduated from London's Royal Academy of Music.  And I've learnt nothing since  :-)


Formulario não faz o action

Question: Criei um formulário onde quero inserir dados no banco, mas não quero que o utilizador insira os dados, logo coloquei display:block no form. No entanto quando clico no botão não acontece nada.
O código do form é o seguinte:
<form role="form" action="inserir_pedido.php" method="post">
  <input type="text" name="id_servico" id="id_servico" style="display:none;">
  <input type="text" name="nome_servico" id="nome_servico" style="display:none;">
  <input type="text" name="horas" id="horas" style="display:none;">
  <input type="text" name="id_profissional" id="id_profissional" style="display:none;" value="<?php echo $_GET['id'] ?>">
  <input type="text" name="id_utilizador" id="id_utilizador" style="display:none;">
  <button type="button" class="btn btn-info">Enviar email</button>
</form>

Comment: Altere no button: `type="submit"`. Outra dica, campos que você quer atribuir dados mas não quer que sejam visiveis ou editaveis, é interessante você usa-los como `hidden`, como no caso desse input de name id_profissional. Se não quer que seja visivel, mas quer poder capturar seu value, não precisa de css, basta alterar  `type="hidden"`
Answer: Como o @DiegoFelipe falou, quando você deseja pegar o valor de um campo, você não precisa utilizar o Display:none, basta mudar o tipo do campo para hidden que ele não será exibido para o usuário. Ficaria mais ou menos assim um campo:
<input type="hidden" name="id_servico" id="id_servico">

E para que o seu formulário seja submetido, basta mudar o tipo do botão para submit, ficando assim:
<button type="submit" class="btn btn-info">Enviar email</button>

A solução completa ficaria assim:
<form role="form" action="inserir_pedido.php" method="post">
  <input type="hidden" name="id_servico" id="id_servico">
  <input type="hidden" name="nome_servico" id="nome_servico">
  <input type="hidden" name="horas" id="horas">
  <input type="hidden" name="id_profissional" id="id_profissional" value="<?php echo $_GET['id'] ?>">
  <input type="hidden" name="id_utilizador" id="id_utilizador">
  <button type="submit" class="btn btn-info">Enviar email</button>
</form>

Formulario não faz o action


Shards in Kubernetes

Question: We have an application that we are running in kubernetes. However, this application only support a fixed number of people.
It has multiple systems:

DB
Authentication system
Web Application
Media manager

We can scale the Web Application and the Media Manager on demand. However, the Authentication system is not designed as to scale up to higher numbers. This is a problem too because is a close system so is not possible to modify it.
However, the system can scale by itself, behaving like a shard. And we can send different users to each shard without problems.
How can we scale up these shards themselves?
The system now behaves like this:

1 DB/Authentication deployment
1 Web Application deployment

HPA that checks the load of the app and scale it up as needed

Stateful set for Media manager

HPA that scales it up as needed

So what we need is a higher level thing that will do:

Operator? Controller? Analyzing metrics maybe? That will scale up the following things:

1 DB/Authentication deployment
1 Web Application deployment

HPA that checks the load of the app and scale it up as needed

Stateful set for Media manager

HPA that scales it up as needed

So as the load increases we are able to scale up these "shards" on demand.
I think this can be done with a controller or operator. But, is there any operator out there that already works like this?
Thanks for your help!
Answer: lets start with the deployments, since you are using a deployment i assume that these can be scaled easily
you can monitor these deployment by adding a sidecar container to their pods exposing metrics data then collecting the data and storing it in something like prometheus then you can use the prometheus to call a webhook whenever these metrics show latency on your database or high response time of any kind on your applications.
the application receiving the webhook will scale up or down your deployment via the kubernetes api (this application you should develop but it is fairly straight forward)
for the authentication system you can use the same strategy but a bit differently.
lets say you have 4 shards, create a separate deployment for each shard each having one shard and since it is sharded i assume a routing mechanism is in place.
configure the routing mechanism to distribute requests between these 4 deployments via their respective services.
collect metrics from authentication manager like other systems but when your system detects performance degradation reshard the authentication manager which the method for depends it it's behavior.
for example a mongodb sharded cluster will scale when you add more replica sets to a sharded cluster but a redis cluster needs shard rebalancing and hash slot modification when more performance is needed.
either way you need to create more deployments on demand which again is the job of the application receiving the webhook from prometheus.
also reconfigure the routing mechanism to connect to newly created shards as well.
Comment: also i dont know of any operators doing this since it is very specific

Shards in Kubernetes


nginxproxymanager fail2ban for 401

Question: I've setup nginxproxymanager and would like to use fail2ban for security. I'm very new to fail2ban need advise from y'all.
My access log when login failed as below
[12/Sep/2022:09:47:54 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
[12/Sep/2022:11:11:32 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
[12/Sep/2022:11:12:02 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
[12/Sep/2022:11:12:43 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
[12/Sep/2022:11:14:54 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
[12/Sep/2022:11:15:26 +0000] - 401 401 - POST http nginx.example.com "/api/tokens" [Client 192.168.X.XX] [Length 51] [Gzip -] [Sent-to 192.168.X.XX] "Mozilla/5.0...
I really had no idea how to build the failregex, please help
Answer: Here is an example of jail that would find every 401 resulting attempt corresponding your log-format:
[nginxpm]
backend = auto
logpath = /path/to/log
filter =
failregex = ^\s*(?:\[\]\s+)?- 401 \d+ - [A-Z]+ \w+ \S+ "[^"]+" \[Client <ADDR>\]
enabled = true

If you need something more precise, for instance you can use POST instead of [A-Z]+, or "/api/tokens\b[^"]*" instead of "[^"]+" (then it would find only POST requests to /api/tokens?....

My access log when login failed as below

As for access-log, it is not advisable (due to possibly large parasite traffic) - better you'd configure nginx to log unauthorized attempts to another log-file and monitor it in the jail. Or may be monitor error-log instead.
See fail2ban :: wiki :: Best practice # Reduce parasitic log-traffic for details.

nginxproxymanager fail2ban for 401


Sometimes I hear a top note that isn't there. Is this related to Harmonics?

Question: When I try to copy a tune or watch other people play the piano, I sometimes hear a note that isn't there. Especially top note is the case. My teacher said that it is related to harmonics, told me that if you smash down a c note, there are lots of sounds you can hear otherwise of just a c note. Then, my question is,
1) Is this occasional phenomenon normal and do you sometimes have the same problem as I do?
2) If you have absolute pitch, does this bother you?
Comment: Do you always hear notes not notated on the score? I basically only hear such notes if many instruments are playing the same note (probably in different octaves) at the same time, and the additional unnotated note is destroyed if a different notated note is added into the mix.
Comment: No, not always. I usually listens to Jazz music so I assume that there might be some difficulty knowing what voicings and chords were used, hence the magic tricks like I mentioned on my question, perhaps?
Comment: What kind of notes are you hearing? If I played, say, a root position D7 chord, what note would you hear above it? D? F♯? Something else? Is this only on a certain piano? Is this also present in recorded music, or just live? Does it seem to matter how high or low the real notes are? As much info as you can give us would help immensely, if you please. Does loudness matter? Etc.
Comment: I forgot to mention that I hear those notes 'sometimes'. It doesn't bother me much since my ears are not trained to be a musician. But the occasional phenomenon I questioned in this website felt real fun and to be discussed with.
Answer: Its not a problem at all. These are called overtones and are produced with each note without actually being played. You may happen to have a better ear for them than most, but every single note you hear consists of many pitches. (The only exception is a sine wave, which is a pure tone with no harmonics. A tuning fork comes close, but still has them.) The harmonic series tells us, mathematically, what notes will sound good together and what notes will clash. It explains why a major chord sounds different than a minor chord, and many other aspects of music and harmony that we often take for granted. Each instrument, based on size, shape, material, etc emphasizes different harmonics, giving it a distinct sound, even between different models of the same instrument. (There are, of course, many other factors involved in creating a specific sound.)
The note you play is the fundamental. The most prominent harmonic is almost always one octave above the fundamental, vibrating at a ratio of 2:1, and can be quite hard to discern as every other oscillation aligns with the fundamental.
The next harmonic is often the easiest to hear as it is farther away from the fundamental, but still prominent and low enough. It vibrates at a ratio of 3:1 with the fundamental, which puts you an octave plus a fifth above. If C is our fundamental, this would be G.
We continue up the series with the ratios 4:1 (a fourth above the previous harmonic, 2 octaves above the fundamental), 5:1 (up another major third), 6:1 (up another minor third, now 2 octaves above the second harmonic), and so on (7:1, 8:1, 9:1), until they are too high for us to hear.
Notice how the most consonant intervals (octave, fifth, fourth, major third, minor third...) are closest to the fundamental. More dissonant harmonies occur further up, and are mostly imperceptible. (What actually determines how consonant two notes are is the number of pitches that overlap in their respective harmonic series. The less they overlap, the more dissonant the interval.)
Tuning based on the harmonic series is called Just Intonation and is the only way to be perfectly in tune, but the ratios create notes that are unique for each key. To avoid tuning to a new fundamental every time we change keys we created the Equal Temperament tuning system, which closely approximates pitches from the harmonic series, while keeping the distance of each half step constant (but also preventing you from ever truly being in tune!)
The human voice is incredibly good at creating overtones, since we can dynamically change the shape of virtually all parts of the "instrument" on the fly and can produce any microtone, allowing us (with lots and lots of practice) to accurately tune to the harmonic series of whatever the fundamental happens to be at the moment.
Just for fun, try singing the word "we" on a relatively low, but comfortable pitch (doesn't have to be in tune with anything). Now do it again, but REALLY slowly, shifting from the "oo" sound at the beginning to the "ee" sound at the end as gradually as you possibly can (also try to create a lot space in the back of your mouth). If done right, you should hear at least part of the harmonic series in ascending order.
Comment: Also, fun fact, the reason why tighter harmonies sound more muddled the lower they are (and you rarely find anything closer than a fourth below an A2) is because more notes in their harmonic series are within our hearing range meaning there are more audible notes to misalign, creating dissonance.
Comment: 'The harmonic series explains how a maj. chord sounds different from a min. one.' How? And do we/can we 'tune to the harmonic series'? Why would we want to do that? If it works, it'll only be the first couple of harmonics anyway, much the same as in a lot of instruments (the later harmonics go quiet quickly).
Comment: @Tim The identity of any chord is the sum of the wavelengths of each pitch in the harmonic series of each note in the chord. The fundamental pitches in a major chord have a ratio of 4:5:6, with the 3rd 2 octaves below the 5th harmonic of the root and the 5th an octave below the 3rd harmonic of the root. This high level of overlap between the most prominent pitches in the harmonic series creates a relatively simple wavelength with a repeat period of only 4 cycles.
Comment: The minor chord has a more complex ratio of 10:12:15. It, of course, has the same relationship with the 5th, but now the 5th is 2 octaves below the 5th harmonic of the 3rd, which is slightly weaker than the root to 3rd ratio found in the major chord. The minor chord has a repeat period of 10, giving it a similar, but distinct sound from the major chord (compared to the 160 repeat period of a diminished). Indeed, these ratios define the unique sound of each chord structure (regardless of the root), major and minor were just the most obvious examples.
Comment: As for tuning to the harmonic series, it is true that many of the ratios cannot be heard audibly as they are too high or too quiet, but they are still there mathematically. Eventually the ratios become so close together that literally any note will, at some point, fall within the harmonic series. When tuning with Just Intonation we use the lowest partial that meets our needs.
Comment: The leading tone, for example, a major 7th above the root or a semi-tone below the octave, *almost* aligns with the 15th harmonic, but is actually 12 cents flat in Equal Temperment. To be perfectly in tune we need to adjust the leading tone 12 cents sharper to a perfect 15:1 ratio. That is tuning to the harmonic series, or Just Intonation.
Answer: [Partial answer]
Hmmm, harmonics would be my best guess. As you know, harmonics (or overtones, or partials) are present in every note played by a piano; it's possible that you're hearing some of these notes (they're definitely possible to hear and mentally isolate, even under normal circumstances). Not sure why you would be especially sensitive to this, though.
Another possibility: Is this only a problem with only one certain piano? If so, it might be the case that one note is sort of "stuck" in the depressed position, and when some other note is played, the note is sympathetically resonating (I would think that your teacher would be able to hear that, though)...
It is also possible that you have tinnitis, and are hearing a ringing note in your ear, but I think that's highly unlikely unless I'm missing something hear. That would, however, fit the "annoying people with absolute pitch" bill...
I hate to mention this, but I don't really know you, so is it possible you're misidentifying something? Is it possible you're mislabelling a note or somehow hearing notes that aren't there?
Sometimes, when multiple notes are played at once, certain other notes can be perceived. Look up "ghost soprano" here on this site, or try researching barbershop music's resonant chords. It could also be sum-and-difference tones of some sort, so this could be an acoustic phenomenon.

I asked one of my friends who has absolute pitch about whether this would bother them. They said it would bother them if the note were anything but a multiple of an octave above/below the actual notes, since that would mess with pitch recognition, but with so little info, beyond that my friend wasn't really sure. Neither my friend nor I nor anyone I know has had this issue before, so I look forward to seeing other hypotheses, and eventually the correct answer.
Comment: Huh, I generally find it cute instead of annoying whenever I hear a ghost note (and it's inevitably not the same pitch class as the actual notes--e.g. given that all I play are C's, the ghost note is a G), and I have absolute pitch.
Comment: There is a phenomenon about two notes played together makes a third note sound. Can't find it yet...
Comment: @Dekkadeci I think my friend meant more like if they were hearing the higher "ghost note" and were unable to recognise the actual note, but I'm just guessing. I probably should have asked for clarification on that... "Cute", huh? I would have guessed more along the lines of "cool", but I guess that's why I'm asking :P
Comment: @Tim The first thing that comes to mind for me for that is either sum-and-difference tones or Tartini tones (two terms for the same thing, I think...?), on string instruments, erhaps?


Deduce logical statements

Question: I have been tasked with coming up with a statement that is true for the following

P(4) is true
∀n: p(n) ⇒ p(n+5)
Let A={n∈Z|p(n)} be the domain to p(n)

But I am not sure what I can say. For instance, p(n)⇒ p(n+5) only tells me that for each whole number, then I can add 5, and the statement will still be true.
Comment: I am sorry if this might be dumb, but what can I even use ∀n: p(n) ⇒ p(n+5) to do?
Comment: We can't know exactly what your instructor is asking for, but it sounds like they want an *explicit* proposition relating to properties of the integers. Think of some provable properties of sets of numbers eg $\{\ldots,2,7,12,17,\ldots\}$ and try to write these as propositions.
Comment: Trivially: Let p(n) be the statement n > 0
Comment: But what does ∀n: p(n) ⇒ p(n+5) even mean?
Comment: My classmate wrote this, "A = {5k-1 | k∈N}" but I don't understand why it is true
Answer: Like the comments say, you can answer this question inclusive with a trivial answer, the only thing you have to do is to make all the statements above true. Now
$$\forall n: p(n) \rightarrow p(n+5)$$
means that if $p$ is satisfied by a number, let say 1, it has to be satisfied by all numbers $\{1, 6, 11...\}$. Let see a statement that it would makethis statements false: $P =  \{ 5k + 4: k \in N \} \cup \{5\}$. This would make statement (1) true and statement (2) false, for if 5 is in the set, all the numbers {5,10,...} would also have to be.
Now the let see some answers:
(1) Like commented, the statement $P = \{ k>0: k \in Z \}$ would make (1) true, for $4 \in P$, and would make (2) true, for any number $n > 0$ is in $P$, and also the numbers $n$ and $n+5$. (3) also would be satisfied, as we are talking about integers.
(2) The statement $P = Z$ would also turn valid all the statements true.
(3) The statement $P = \{-6, -1, 4, 11, ... \} = \{5k -6: k \in Z \}$.
Comment: It refers to any natural number.

Deduce logical statements


C# Opening a local file

Question: I am trying to make a simple c# program which opens a file in dotnet core 5 using visual studio, however, it transpires that it is looking for the file relative to where the .exe is stored, not my source files. Is there any way I can change this? So that the file can be stored with my source files?
I have tried using Directory.GetCurrentDirectory(), however, this takes me to .exe file, and I need it to open using a relative path rather than the absolute one.
The code is copied and pasted from the Microsoft C# docs here (In the image I have a './' before the filename, I have tried without, it was just something I tried to get it to work.
Code:
using System;
using System.IO;

namespace Test_File_Opening
{
    class Program
    {
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("Sample.txt");
                //Read the first line of text
                line = sr.ReadLine();
                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the lie to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }
                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

Exception: Could not find file 'C:\Users\callu\source\repos\Test_File_Opening\Test_File_Opening\bin\Debug\net5.0\Sample.txt'.
Executing finally block.

Comment: Please provide code as text, not as pictures of text, as mentioned on [ask].
Comment: Use the full path to the desired file, instead of a relative path from the executable?
Comment: Sorry, I didn't mention this, I need it to be a relative path as it needs to be able to run on another machine.
Comment: You can also copy files on build to the output folder automatically. See this somewhat unrelated question but the image applies: https://stackoverflow.com/a/26650101/5948452
Comment: Current Directory always points to the location of exe. You also mentioned that you want to run it on another machine. So, please specify the path of your file relative to the location of your exe. What you are trying to achieve is access the file relative to your source code location without letting your exe know the location of your source code. You can feed the source folder location to your application and then ask your exe to access relative to it.
Comment: Do you have control/knowledge about, where the *Sample.txt* will be located on the other machine(s)? Do you deploy it with your exe? If not, then I'd say, you will need some FileDialog to grab the file... if yes, then you can hardcode the relaltive path from your exe, like System.IO.Path.GetFullPath (@"..\..\Myfolder\Sample.txt") - check System.IO.Path for more options
Answer: The running executable has no knowledge of or connection to the original source code files.  They may be moved or deleted entirely for all it knows.
Use an absolute path for your file:
var sr = new StreamReader(@"C:\Some\Path\To\Your\File.txt");

I need it to open using a relative path rather than the absolute one.

No you don't.  Because there is no universal relative path between a compiled executable and the source code from which it was compiled.
But a comment on the question offers an alternative:

it needs to be able to run on another machine

That's what config files are for... environment-specific settings.  (Alternatively, if your plan all along was to distribute the source code for your users to compile and run themselves then they could simply edit it to their file location anyway.)
If you're using the older App.config style settings, add an App.config to your application and put the file path in the appSettings:
<appSettings>
  <add key="FilePath" value="C:\Some\Path\To\Your\File.txt"/>
</appSettings>

Then use that setting in the code:
var sr = new StreamReader(System.Configuration.ConfigurationManager.AppSettings["FilePath"]);

Or, if you're using something newer like appsettings.json then there is documentation for that as well.  But the principal is still the same.
You could even roll your own way of maintaining application configuration.  Hell, you could even skip a config file entirely and provide the file name as a command line argument when running the application.  The point is that any given environment would need a way to tell the application where the file is.

C# Opening a local file


How do I set cookie to be secure .NET Core?

Question: I've run into problems using Identity Server 4. It's the common problem that requires SameSite=None and secure cookies. While I managed to set SameSite to None, I didn't set cookies to be secure.
I tried searching online but couldn't find any complete solution. I will need information where to use that part of code too, since I'm not experienced.
I am using ASP.NET Core 3.1.
Thanks
Answer: You can set cookie settings like this
<code>services.AddIdentityServer()
.AddInMemoryClients(Clients.Get())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddInMemoryApiResources(Resources.GetApiResources())
.AddDeveloperSigningCredential()
.AddTestUsers(TestUsers.Users);

services.AddAuthentication("MyCookie")
    .AddCookie("MyCookie", options =>
    {
        options.ExpireTimeSpan = ...;
    });
</code>
for more information read Cookie authentication.


Expo splash screen appear, but the app doesn't start

Question: When I open the app using Expo Go or a Development Build, I see the splash screen, but then nothing happens. After waiting for a few minutes, I tried stopping the server by pressing Ctrl + c, and I received an error message as shown below. However, after 1-2 seconds, the following error showed and the app suddenly closed.
I created the development build using the following commands:
$ npx expo prebuild --clean --yarn
$ npx expo run:android --variant debug

It's worth mentioning that everything works perfectly fine in the Android release build and the web build!

I'm using:

Expo SDK 49
expo-router 2.0.0
@react-navigation/drawer 6.6.4
react-native-reanimated 3.3.0
Answer: I ran yarn add @expo/metro-config then change my metro.config.js with:
const { getDefaultConfig } = require("expo/metro-config");

const defaultConfig = getDefaultConfig(__dirname);

defaultConfig.resolver.resolverMainFields.unshift("sbmodern");
defaultConfig.resolver.sourceExts.push("cjs");
defaultConfig.resolver.sourceExts.push("mjs");

module.exports = defaultConfig;

And then rebuild the project with npx expo run:android --variant debug


Uncertainty on independent variable of a non linear model

Question: I have a question about how to estimate the uncertainty of a value calculated from a non linear model. My non-linear model is the following:
$$
y=A+\frac{B}{1+e^{k(x-x_0)}+e^{c(x-x_1)}}
$$
where $ A, B, k, c, x_0, x_1$ are fitting parameters that I find using a Levenberg–Marquardt algorithm (non linear least square fitting). What I do after is to calculate $x$ at a particular $y$, but I don't know how to estimate the uncertainty on the found $x$. What I have done so far is to calculate the standard deviation of the fitting parameters using the covariance matrix and the root mean square error (RMSE) and I tried to propagate the error, but the problem is that I cannot get an analytical solution for $x$.
How can I proceed to estimate the uncertainty on $x$ ? Thanks
Comment: Doesn't your function calculate y as a function of x? Where is the error term in your model?
Comment: Yes my function calculates y. I called them y and x but they are actually viscosity for y and time for x. I have viscosity data changing over time and I fit this data to the above function. Then I use this function to back calculate a particular time. Briefly, I calculate the time when the viscosity has increased of 20%. Now I would like to express this time +- an uncertainty.
Comment: The calculation of x at a particular y is done by a numerical method, because I couldn't get an analytical expression for x.
Answer: Use Monte Carlo uncertainty propagation (GUM-Supplement 1):
1/ evaluate the covariance matrix of your parameters (not only the uncertainties; they are probably strongly correlated and this has a HUGE impact on the final uncertainty)
2/ draw random samples from a normal multivariate distribution using the best value of your parameters and their covariance matrix
3/ calculate x for each point of the sample
4/ estimate the mean and standard deviation of x
Comment: Thank you very much, I will try to understand how to implement Monte Carlo method.
Comment: You just need a random generator for normal multivariate distributions (for instance `mvtnorm::rmvnorm()` in R).
Answer: You can use bootstrap to estimate the distribution of the any x. Below is my effort to point out the things to do:

Make a bootstrap sample. That is, take n samples from the original data with replacement, where n is the size of original data. Estimate all the parameters you want.
Repeat step 1 for a number of times, say b times (The value of b may be 1000, 10000, 100000 etc). That is you make b bootstrap sample and for all the samples you estimate all the parameters. Save values of all the parameters for all b runs.
Now you have b values of x. These values form a distribution of x. You can compute the mean and variance and translate into confidence interval, if you assume certain theoretical distribution for the parameter. The alternate way would be using empirical percentiles to construct the confidence interval. That is use 2.5th and 97.5th percentile of the distribution of x as a confidence interval of x.

If the variance co-variance matrix is necessary, then that also can be constructed from the the data you have.


Splitting field of $f=t^{4}+2\in \mathbb{Z}_{3}[t]$

Question: In order to determine the splitting field of  $t^{4}+2\in \mathbb{Z}_{3}[t]$, I first "guessed" the roots $1$ and $2$ then, by polynomial division, obtained
$t^{4}+2=(t^{2}+1)(t+2)(t+1)$
Since for $t^{2}+1$ to be $0$ I'd need $\sqrt{2}$, I came to the conclusion that $\mathbb{Z}_{3}(\sqrt{2})$ is the spitting field of $f$ over $\mathbb{Z}_{3}$
Is my idea correct ?
Comment: Can you simplify $\mathbb{F}_{3}(\sqrt{2})$? Hint: it is a finite field.
Comment: @ChristianSinger The splitting field of $t^{4} + 2$ over $\mathbb{F}_{3}$ is equivalent to the splitting field $K$ of the irreducible polynomial $t^{2} + 1$ over $\mathbb{F}_{3}$. It is clear that $K$ is a degree two extension of $\mathbb{F}_{3}$. The unique such extension is $\mathbb{F}_{3^{2}} = \mathbb{F}_{9}$.
Comment: I think you can use Hensel lemma
Comment: I just looked up the Hensel lemma and I think it's quite a bit too advanced for my current grasp of algebra
Comment: I know that all splitting fields of $f$ are isomorphic but just for now I don't see a quick way to simplify $\mathbb{F}_{3}(\sqrt{2})$
Answer: Your approach is correct, but I don't think that the expression $\sqrt2$ is used in this context. I would say that the splitting field of $t^4+2$ is $\mathbb{Z}_3[t]/(t^2+1)$ or that it is$$\{a+bs\,|\,a,b\in\mathbb{Z}_3\},$$where $s^2=2.$
Comment: Yeah, I see your point.
Comment: I hope that it is clear that I am *not* criticizing your reasoning, but just the choice of notation.
Comment: Yeah sure! I appreciate your response :-)