order of kernel of surjection between curves is equal to separate degree

Question: Let $Φ:C→D$ be a non constant map of smooth curves.
Silverman says in AEC

for all but finitely many $y∈D$,
$$\#\phi^{-1}(y) = \deg_s(\phi)$$

How can I prove this? Silverman also say to prove this, see Hartshorne Ⅱ6.8. But I can find no connection between them.
Some remarks in mathstacks I see use the ideal correspondence and Hilbert's Nullstellensatz, but curves $C$ and $D$ in AEC might not be defined over algebraically closed field, so I need to show the proposition over arbitrary fields.
Comment: The proposition in Hartshorne tells you that $\Phi$ is a finite morphism and that $K(C)/K(D)$ is a finite algebraic field extension. Do you know anything about either of these notions that could help you?
Answer: I assume you mean Proposition II.2.6(b) in AEC. The curves must be defined over an algebraically closed field, or else the statement is not true. An easy counterexample in the non-algebraically closed case is $K = \mathbb{R}$, with curves $C = D = \mathbb{A}^1(\mathbb{R})$, and $f(x) = x^2$. Then $\# \phi^{-1}(y) = 0$ for infinitely many $y$ (namely, all $y < 0$), but $0 \neq \deg_s\phi = 2$.
In order to understand how II.2.6(b) incorporates a hypothesis of an algebraically closed field, it is necessary to refer to the Definition of smooth curve (on page 17), which refers to the Definition of projective variety (on page 9), which refers to the Definition of projective algebraic set (on page 7), which refers to the definition of $V_I$ (on page 7), which refers to the Definition of $\mathbb{P}^n$ (on page 6), which refers to the Definition of $\mathbb{A}^n$ (on page 1). We finally see that $\mathbb{A}^n$ by definition means $\mathbb{A}^n(\bar{K})$, so we are indeed working over an algebraic closure.
In order to avoid a notation conflict with $L$ and $K$ below, I will use $F$ to denote the (algebraically closed) scalar field over which $C$ and $D$ and $\phi$ are defined.
To prove the result, use the fact that over an algebraic closure, points on curves are in 1-1 correspondence with nonzero prime ideals in the coordinate ring. The splitting of prime ideals in finite extensions of global fields then proves the desired result. Specifically, take $K = \phi^* F(D)$ to be the function field of $D$, and $L = F(C)$ to be the function field of $C$, and consider the formula
$$
[L:K] = \sum_{j=1}^g e_i f_i
$$
from the aforementioned page, where $e_i$ and $f_i$ denote ramification index and inertial degree. The residue fields at every point must all be equal to $F$, since $F$ is algebraically closed, meaning that no further nontrivial finite extensions of this residue field are possible. Hence $f_i = 1$ for all $i$, and the formula then reduces to the simpler expression
$$
[L:K] = \sum_{j=1}^g e_i.
$$
(Note that this expression is identical to the statement of AEC II.2.6(a).) Since $[L:K] = \deg \phi$ by definition of $\deg \phi$, this equation is exactly the statement that $\deg \phi = \# \phi^{-1}(y)$ for all $y \in D$, where the points in $\phi^{-1}(y)$ are counted with multiplicity (the respective values of $e_i$ denoting the multiplicity of each element of $\phi^{-1}(y)$). In order to obtain II.2.6(b) in the separable case, simply observe that $\deg_s\phi = \deg \phi$, and that there are only finitely many points in $C$ where $e_i \neq 1$.
In the inseparable case, you will have $e_i = d$ where $d$ denotes the inseparable degree of $[L:K]$. Dividing both sides of the equation by $d$ then yields the result.
I also highly recommend that you read Remark II.2.8 in AEC since this remark adds some further information to this discussion.
Comment: Your remark about things needing to be defined over an algebraically closed field is not needed if you upgrade to schemes, where this proposition is true with no conditions on the base field. It's not clear to me what context the OP is working in (classical varieties or schemes?) but I think it's good to note that the proposition is true in the right context without extra assumptions.
Comment: You are correct, but Silverman AEC does not work with schemes, although for a few of the proofs of the theorems in AEC he does reference external sources where the proofs from those sources use schemes. OP states clearly that they are working out of Silverman AEC.


Triangular notehead at the end of a glissando/portamento

Question: I was studying a score that had this strange symbol in the violin part.  It's a triangular notehead at the end of a glissando/portamento.  The note seems to be suspended, not connect to the staff with any ledger lines:

Does anyone know what this notation means? How should I interpret it?
I tried looking it up, but no luck. Notation music software such as MuseScore doesn't seem to have this as a feature.
Answer: The symbol indicates the highest pitch possible on the instrument (in this particular case: a glissando to the highest possible pitch). It only makes sense for an instrument with an undefined highest pitch (otherwise the actual highest pitch should be explicitly written).
The same symbol flipped below the stave and pointing downwards indicates the lowest possible note.
This symbol can be found in Elaine Gould's Behind Bars, pages 12,13,143.
Comment: So should the notehead be read as an arrowhead, rather than a triangle as such?
Comment: @gidds It doesn't matter whether you call it an arrowhead or a triangle. I would call it an arrowhead.


Subtração em jquery

Question: Eu tenho essa função em javascript, e queria passar ela para jquery. O usuário clica em um botão em html e chama a função para um desconto.`
`

Comment: Bem-vindo, não esqueça de ler esse post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: Com jquery pode ser feito da seguinte forma:

$(document).ready(function () {
   var preco = 100;
   var desconto = 0.30;
   var total;

    $("#calculo").on("click", function(){
        if(ssbc.checked) {
            total = preco -(preco*desconto);
        } else {
            total = preco;
        }
        //alert("O valor de sua inscrição é: R$ "+total+",00");
        console.log("O valor de sua inscrição é: R$ "+total+",00");
    });
});

<input type="checkbox" name="ssbc" id="ssbc" />
<input type="button" id="calculo" value="Calcular" />

$(document).ready significa que vamos executar a função assim que os elementos html estiverem postos na página.
A linha $("#calculo").on("click", function(){ pode ser substituída por $('#calculo').click(function (){ que também, nesse caso, vai funcionar a contento.

Para saber a diferença entre .on("click", function()) e o .click(function()) acesse  esse post
Comment: A resposta do @LeoCaracciolo está corretíssima.
Answer: Este exemplo é só uma alternativa onde os valores podem ser inseridos pelo usuário.

$('#aplicar').click(function(){
    $('#desconto').slideToggle();
  });

$('#calcular').click(function(){
    if ($("#aplicar:checked").length) {
      $('#total').text("O valor de sua inscrição é: R$ " + parseFloat($('#preco').val() - $('#valDesconto').val()).toFixed(2));
    } else {
      $('#total').text("O valor de sua inscrição é: R$ " + parseFloat($('#preco').val()).toFixed(2));
    }
})
#desconto { display: none; }

<form>
  Preço: <input id="preco" type="number" step="0.01">

  Aplicar desconto
  <input type="checkbox" id="aplicar">

    Desconto: <input id="valDesconto" type="number" step="0.01" placeholder="Desconto">

  <input type="button" id="calcular" value="Calcular">

</form>

Subtração em jquery


DevTools window for Chrome extension background script closes while debugging it

Question: I'm debugging a Chrome extension that uses Event Pages to set up some periodic notifications.
The problem is that why debugging the background page, Chrome closes its DevTools window out of the blue. at chrome://extensions, I have have to click Inspect views: background page (inactive) again.
Answer: From the Event pages docs:

Event Pages are loaded only when they are needed. When the event page is not actively doing something, it is unloaded, freeing memory and other system resources.

To temporarily disable that behavior for debugging purposes, set persistent: true in manifest.json and reload the extension.


Proof of the Uniqueness Part of Hensel's Lemma

Question:
Hensel's Lemma: Let $f(x) \in \mathbb{Z}[x], a \in \mathbb{Z}, k \geq 1.$ If $f(a) \equiv 0$ (mod $p$) and $f'(a) \not \equiv 0$ (mod $p$), then there exists a unique $b$ (mod $p^k$) such that $f(b) = 0$ (mod $p^k$) and $b \equiv a$ (mod $p$).

Much of the proof as to existence can be found here (pp.2-3). One proceeds by induction on $k \geq 1.$ One assumes the inductive hypothesis, that there is a unique root $b_k$ (mod $p^k$) satisfying $f(b_k) = 0 \bmod p^k$ and $b_k \equiv a \bmod p$. To show the $k+1$th case holds, one defines \begin{align} b_{k+1} = b_k + p^kt_k \tag{1} \end{align}, where $t_k$ is the unique solution (mod $p$) to
\begin{align}
f'(b_k)t_k \equiv -f(b_k)/p^k \bmod p. \tag{2}
\end{align}
Using assumptions and the identity that $f(a + p^kt) = f(a) + f'(a)p^kt \bmod p^{k+1}$, for any $t \in \mathbb{Z}$, one can argue that a unique solution mod $p$ to (2) indeed exists and that $b_{k+1} \bmod p^{k+1}$ indeed satisfies $f(b_{k+1}) = 0 \bmod p^{k+1}$ and $b_{k+1} \equiv a \bmod p$.
I am having trouble, however, constructing the proof as to uniqueness of the Hensel's Lemma, as it is given above. The link given before gives a proof of uniqueness to a slightly more difficult version of Hensel's Lemma, which does not apply to the statement above. How might I prove uniqueness for this version of Hensel's Lemma?
Edit: In following their reasoning for the uniqueness part on p.3, I write
\begin{align}
b_{k+1}' = b_{k+1} + p^{k}\gamma_k, \gamma_k \in \mathbb{Z}_{p}.
\end{align}
Then, I use
\begin{align}
f(b_{k+1}') = f(b_{k+1} + p^{k+1} \gamma_{k}) = f(b_{k+1}) + f'(b_{k+1})p^{k}\gamma_{k} \bmod p^{k+1}.
\end{align}
By assumption, $f(b_{k+1}') = f(b_{k+1}) \equiv 0 \bmod p^{k+1}$. Thus, $f'(b_{k+1})\gamma_k \equiv 0 \bmod p$. Since $f'(b_{k+1}) \equiv f'(a) \neq 0 \bmod p$, I have $\gamma_k \equiv 0 \bmod p$... and this implies $b_{k+1}' \equiv b_{k+1} \bmod p^{k+1}$?
Comment: The details in the edit you added at the end provide exactly the argument that was intended. Also there is another, arguably more elementary, way to approach the uniqueness mod $p^n$ of the root: during the induction argument in the proof,  prove along the way that for each $n \geq 1$, $f(x)$ has a unique root $a_n \bmod p^n$ such that $a_n \equiv a \bmod p$. I have expanded the remark right after the proof to point this out.
Comment: How is the uniqueness statement you cited more difficult than the uniqueness statement that you want?  Your version uses only integral coefficients rather than $p$-adic integer coefficients, but the math in both cases seems to be nearly the same since integers mod $p^k$ and $p$-adic integers mod $p^k$ are naturally isomorphic rings. In other words, if you just run through the argument at the link with integers in place of $p$-adic integers, where do you find yourself running into trouble?
Comment: @KCd Thank you for this. Just one point of clarification: Does the relation $b_{k+1}' = b_{k+1} + p^k\gamma_{k}$ hold because both $b_{k+1}', b_{k+1}$ are of the form (1)?
Comment: That's just an inductive assumption.  When $k \geq 1$ we assume there is a unique root mod $p^k$ that reduces to $a \bmod p$, so this holds automatically at $k = 1$, and then show when there is a unique root mod $p^k$ that there is a unique root mod $p^{k+1}$.  Thus the relation you ask about is simply a consequence of  (i) there being a unique root mod $p^k$ that's $a \bmod p$ and (ii) any root mod $p^{k+1}$ that is $a \bmod p$ reduces to a root mod $p^k$ that is $a \bmod p$.
Answer: Hints:

Take two solutions $b$ and $c$.
It is clear that $b \equiv c \bmod p$.
Prove by induction that $b \equiv c \bmod p^j$ for $j\le k$.


Programa com expressões de booleana entra no bloco do if todas as vezes

Question:     prefixes = "JKLMNOPQ"
    suffix = "ack"
    for letter in prefixes:
        if letter[0] == "Q"or"O":
            print(letter+"uack")
            continue
        print(letter+suffix)

Resposta esperada:
Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack

Resposta adquirida:
Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack

Não entendi o porque de or quando usado retorna tudo como True ao em vez de selecionar as variáveis que eu digitei no código.
Answer: O or não funciona como imagina, o correto seria:
prefixes = "JKLMNOPQ"
for letter in prefixes:
    if letter[0] == "Q" or letter[0] == "O":
        print(letter + "uack")
    else:
        print(letter + "ack")

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Você estava comparando a expressão letter[0] == "Q" que pode ser verdadeiro ou falso de acordo com o valor de letter[0]. Como tem um or a única forma da decisão ser tomada sem avaliar mais nada é quando esta expressão seja verdadeira, porque é certo que o bloco deve ser executado. E até aí está certo. O or também é o adequado aí. O problema está na segundo expressão do or que não retorna o que você espera.
Qual o resultado booleano de "O"? Por definição, todos os valores que não sejam considerados zerados ou vazios são falsos, todos os outros valores são verdadeiros, então "O" é verdadeiro. Então toda vez que a primeira expressão der falsa e ele vai tentar a segunda esta é sempre verdadeira, e portanto faz tudo ser verdadeiro.
O que de fato você queria fazer é letter[0] == "O" porque aí a expressão pode dar verdadeira no momento certo, mas dará falsa em grande parte dos casos.
As outras mudanças eu fiz porque é mais legível e óbvio
Comment: Obrigado por esclarecer minha dúvida.
Answer: Outra forma de fazer seria:
prefixes = 'JKLMNOPQ'
for prefix in prefixes:
    suffix = 'uack' if prefix in {'Q', 'O'} else 'ack'
    print(prefix + suffix)

Veja funcionando no Repl.it | Ideone | GitHub GIST
Basicamente substituindo as duas comparações com == pelo operador in e a verificação por uma condição inline, ou ternário, se preferir. Eu particularmente acho esta forma mais legível para humanos.
Comment: @Miguel sim, a busca em um set é O(1), enquanto nos outros é O(n), mas não necessariamente isso se reflete na execução, dado o tamanho do conjunto.
Comment: Nunca tinha visto antes o uso de operadores dentro de uma linha, valeu pela dica vou dar uma pesquisada nisso também.
Comment: Existe algum motivo especial (talvez performance) para usar `set` em vez de `lista`/`tuple` neste caso?
Comment: Obrigado Anderson , sim, é motivo suficiente.


SELECT dentro do INSERT PHP Mysql

Question: Tenho o seguinte código:
<code>$sql = mysql_query("INSERT INTO TB004_PRODUTO_FORNECEDOR ( TB002_CODIGO, TB003_CODIGO )
                  SELECT TB003_CODIGO, 1 AS Codigo FROM TB003_PRODUTO WHERE TB003_DESCRICAO = '$name_02'
                  VALUES ( '$name_01', Codigo )");
</code>
Como eu posso selecionar o código do produto dentro insert para ele apenas inserir o código?
Comment: Se isso for possivel, vou gostar de saber.. rsrs. Só não use mais o `mysql_*`, pois está defasado. Utilize o `mysqli_*` ou `PDO`
Comment: @AndreiCoelho eu já fiz no `PDO`, mas neste caso não posso, por mais que eu queria, vou ter que fazer `msql` mesmo.
Comment: Entendi =)... a resposta abaixo parece valida
Answer: Olá, não sei se entendi bem, mas pelo que eu entendi você quer inserir o resultado de um select. Se for isso basta fazer +- assim:
<code>INSERT INTO TB004_PRODUTO_FORNECEDOR ( TB002_CODIGO, TB003_CODIGO )
VALUES ('$name_01',(SELECT TB003_CODIGO FROM TB003_PRODUTO WHERE TB003_DESCRICAO = '$name_02'))
</code>
Comment: Colocar o segundo valor em um select é isso? Legal.. vivendo e aprendendo
Comment: Olá se você quer inserir o segundo valor (TB003_CODIGO), mas só tem o nome para pesquisar então seria assim mesmo.
Comment: Entendi. Interessante...
Comment: Pior que tinha feito isso, mas outra coisa estava errada e não deu certo, eu segui o jeito que tinha feito no PDO `$stmt = $this->conn->prepare("INSERT INTO tasks (Project, CompanyFantasy, Priorities, Delivery, Attachment, ByUser, Systems, OrderTask, Subject) VALUES
                                    (:project, :companyfantasy, :priorities, :delivery, :attachment, :byuser, :systems, (select OrderTask from (SELECT MAX(OrderTask)+1 as OrderTask FROM tasks) X), :subject)");`, um pouco diferente a lógica porque estou usando MAX()+1.

SELECT dentro do INSERT PHP Mysql


Reading tsv files with byte strings with pandas

Question: I have a tsv file with a column containing utf-8 encoded byte strings (e.g., b'La croisi\xc3\xa8re'). I am trying to read this file with the pandas method read_csv, but what I get is a column of strings, not byte strings (e.g., "b'La croisi\xc3\xa8re'").
How can I read that column as byte strings instead of regular strings in Python 3? I tried to use dtype={'my_bytestr_col': bytes} in read_csv with no luck.
Another way to put it: How can I go from something like "b'La croisi\xc3\xa8re'" to b'La croisi\xc3\xa8re'?
Comment: to go from something like `"b'La croisi\xc3\xa8re'"` to `b'La croisi\xc3\xa8re'` you can do `data[2:-1].encode()`
Comment: Not really, this returns the following wrongly encoded byte string: `b'La croisi\xc3\x83\xc2\xa8re'`
Answer: sample file:
    First Name  Last Name   bytes
0   foo          bar        b'La croisi\xc3\xa8re'

then try this:
import pandas as pd
import ast
df = pd.read_csv('file.tsv', sep='\t')
df['bytes'].apply(ast.literal_eval)

Out:
0    b'La croisi\xc3\xa8re'
Name: bytes, dtype: object

Comment: This doesn't work because it opens the utf-8 encoded byte string column from my `tsv` file into a simple string. Maybe there's a set of arguments I could pass to this function that would fix it?
Comment: OK, this should work for you: df['bytes'].apply(ast.literal_eval)
Comment: bytes(str(df['my_bytestr_col']),'utf-8')
Comment: This returns `b"b'La croisi\\xc3\\xa8re'"` in Python 3


On the space of continuous functions of a second-countable space

Question: Let $X$ be a locally compact, Hausdorff, second-countable space, and let $C(X,\mathbb{C})$ the space of continuous, complex-valued functions over X endowed with the uniform norm.
Is $C(X,\mathbb{C})$ separable?
Comment: Since continuous functions on $X$ can be unbounded, the uniform "norm" isn't even a norm.  Perhaps you wanted the space of bounded continuous functions?
Answer: Not in general. Consider $X = \mathbb{R}$, for each subset $A$ of the integers let $f_A : \mathbb{R} \to \mathbb{C}$ be the function which has a narrow triangular spike (say of width 1/2) of height 1 centered at each integer in $A$, and is zero otherwise. The distance between any two such functions in the sup norm is one, and there are uncountably many of them, so the space cannot be separable.
Comment: More generally, instead of the integers you can use any infinite set without limit points (taking a little more care in the construction). This shows that the space of bounded continuous functions is separable if and only if $X$ is compact.


Removing # from url in Angularjs while having .run in routes

Question: Here is my app.js  route file in AngularJS
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider.
                when('/login', {
                    title: 'Login',
                    templateUrl: 'resources/views/layouts/loginUser.php',
                    controller: 'authCtrl'
                })
                .when('/', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/login.php',
                    controller: 'logoutCtrl'
                })
                .when('/reset', {
                    title: 'Reset Password',
                    templateUrl: 'resources/views/layouts/forgetPassword.php',
                    controller: 'authCtrl'
                })
                .when('/invalidtoken', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/invalidtoken.php',
                    controller: 'authCtrl',
                    role: '0'
                })

                //$locationProvider.html5Mode(true);
    }])

        .run(function ($rootScope, $location, Data, $http) {
            $rootScope.$on("$routeChangeStart", function (event, next, current) {
                     var nextUrl = next.$$route.originalPath;

                    if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/register' || nextUrl == '/registered' || nextUrl == '/reset' || nextUrl == '/resetdone' || nextUrl == '/registersuccess')
                    {
                        $location.path(nextUrl);
                    }
                     else
                    {

                        $location.path('/');
                    }
            });
        });

Here i use .run to handle few requests.
I want to remove the # from the url to make the url pretty,
So i did like this to remove the # as suggested here
app.config(['$routeProvider', '$locationProvider'
    function ($routeProvider, $locationProvider) {

and in the last line
$locationProvider.html5Mode(true);

But nothing is happening to the application, it stills haves # in the url.
Even i tried this way
How can i achieve this ?
Update :
If i do
.run(function ($rootScope, $location, Data, $http, $locationProvider) {

and in the last line
$locationProvider.html5Mode(true);

I am getting this error
Error: $injector:unpr
Unknown Provider

I have tried in many ways, but none of them working.
Update 2 :
Or can anyone suggest a link of angularjs example which provides example without # in url ?
Comment: Have You put   in  page head?
Comment: @Vivek yes, i tried that , but it didn't helped me
Comment: What browser you use?
Comment: @PetrAveryanov Google Chrome latest is the one i use
Comment: @PetrAveryanov Is there any other possiblity to have like this ?
Comment: @SagarNaliyapara I referred that site only initially :)
Answer: Why do you want to use the .run() ? Add  <base href="/" /> to you  or start of your body (first line) and then to match the logic of your .run() try this ( .otherwise("/path") to your $routeProvider):
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider', '$locationProvider',
    function ($routeProvider, $locationProvider) {
        $routeProvider.
                when('/login', {
                    title: 'Login',
                    templateUrl: 'resources/views/layouts/loginUser.php',
                    controller: 'authCtrl'
                })
                .when('/', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/login.php',
                    controller: 'logoutCtrl'
                })
                .when('/reset', {
                    title: 'Reset Password',
                    templateUrl: 'resources/views/layouts/forgetPassword.php',
                    controller: 'authCtrl'
                })
                .when('/invalidtoken', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/invalidtoken.php',
                    controller: 'authCtrl',
                    role: '0'
                })
. otherwise("/");
           $locationProvider.html5Mode(true);
    }]);

If you still face issues, I recommend https://github.com/angular-ui/ui-router
Update:
your index.html
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Green Hopping</title>
        <link rel="shotcut icon" type="favicon.ico" href="public/images/favicon.ico" />
        <link rel="icon" type="favicon.ico" href="public/images/favicon.ico" />

      <base href="/">

All other templates are same like this. Copy paste the following for home.html , login.html , dashboard.html , logout.html . Plunker will not be able to show issues with routes for client side. Try this. This is completely functional code.

Home |
    Login |
    Dashboard |
    Logout

 This is from the home/login/dashboard/logout Controller. Loggedin: {{loggedin}}

Comment: There are methods in UI Router like `.onEnter`,`resolve`, `.onExit` that you can use for your benefit to do actions on entering or after exiting the url. It makes life easier.
Comment: But i wanted to use .run in the same time for some conditions, Is that not possible ?
Comment: Your were unable to remove `#` from your url and as per your `.run()` logic, if `"/wrongurl"` it goes to `"/"`. This can be done by `.otherwise("/")` directly and my provided code will do all that your given code does. This wont clash with `.html5Mode(true)` & ``. Why use `.run()` for that logic. If you want to do some other logic when entering a url, then why not use `$locationChangeStart` event & `path([path])` method(in `$location`) in `.run()`. `https://docs.angularjs.org/api/ng/service/$location`. These have been made way easy in `ui.router` I mentioned. Check it out.
Comment: Do also let me know if my code helped for the same logic of run you are using.
Comment: Hey, if i do so , i am getting the blank page, and nothing is displaying :( Could you help me pls
Comment: That is a working code so should not faulter. It will faulted if you send wrong parameters or get query params. The URL and parameter has to match. What is you code now and what are you passing? Some syntactical or method usage issue probably
Comment: Updated the code above. Plunker does not allow checking issues with client side routes. There was no $locationProvider injection.
Comment: Made a minor code edit to suit your isLoggedin Variable. at `.run()` `if (authenticated)` function.
Comment: `` should be inside the body ?
Comment: I am getting this error.. :( TypeError: Cannot read property 'originalPath' of undefined
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97504/discussion-between-sa-and-gary).
Answer: try changing:
$locationProvider.html5Mode(true);

To:
$locationProvider.html5Mode({
   enabled: true,
   requireBase: false
});

Answer: Are you by chance receiving a 404 error ? Whenever you change the mode to html5history you have to tell the web server to always return the index page no matter what URL is requested. As the angular docs says here:
https://docs.angularjs.org/guide/$location

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows Angular to differentiate between the part of the url that is the application base and the path that should be handled by the application.

Have you tried doing that and configured it properly ?
Also remember that you have to specify the base entry href of your application for it to work like
  <base href="/" />

Comment: You mean to deal with .htaccess ?
Comment: Yeah i guess so - haven't work on the Apache server so you will have to check how to do it yourself.
Answer: You can't inject $locationProvider in .run because providers are only available for .config
This answer should help but you will have 2 issues:

You will need a check before $locationProvider.html5Mode(true)  as it will not work on IE 10 or older.
if(window.history && window.history.pushState){
    $locationProvider.html5Mode(true);
}

This will work only by removing the # when the user enters it in the url, i.e. if the users types app/#/login it will change to app/login. However, if the user bookmarks or copies the changed url app/login and enters that in the browser he will get an error as the server does not know about angular routing since it is client side only. In the thread I linked above you may find some comments on how to fix this.
Comment: I am not trying it in internet explorer, i am trying in chrome but this conditions is not working, i tried putting this inside and outside of the .run :(
Comment: Did you add     as in this answer http://stackoverflow.com/a/32620370/3716153 ?
Comment: Yeah, i added the same in the index.html file
Comment: If you have teamviewer, can you pls have a look on my code ?
Comment: It will be very hard to figure out the problem without seeing the code. Are you putting the above lines inside the .config ? Are you getting any console errors?
Comment: No, i wanted you to see my code via teamviewer... and i don't have any errors in console..
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97473/discussion-between-gaafar-and-sa).
Comment: Team viewer is blocked on my network. Try adding $locationProvider.html5Mode(true); without the condition inside the .config function
Comment: Hey, are you there ?, could you pls come in chat/discussion
Comment: I guess you can find the hind if you see my code directly.. Any possiblity of it... Like ammyy or any other client to see my screen pls
Comment: I'm afraid I can't help without seeing the actual code.
Comment: Try to share a fiddle or plunkr as I can't access team viewer. Or update the question with full code (js & html)
Comment: ok, i will try to add, you can't even able to see the code, if you reach home ? because my project is laravel based and it would take lot of time to construct the plunkr. but i will try to do
Comment: Here is the plunker ..http://plnkr.co/edit/X6xDNpMOXsssN3InkiCX?p=preview it contains only the app.js and the index.html file
Comment: Hi, you saw the plunkr ?
Comment: You are not injecting the '$locationProvider' in the config function like this:  app.config(['$routeProvider','$locationProvider',
    function ($routeProvider, $locationProvider) {
Comment: here http://plnkr.co/edit/EP3V8TfS24sZrtogcwaJ?p=preview use the app.js from this one
Comment: hey, i have changed accordingly.. but it was same.. It just 'Navigated to http://localhost/projects/myproject/' in console.. still blank page :(
Answer: The problem is it is missing the service injection.
So in config section try injecting $locationProvider like below.
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
    $routeProvider.
            when('/login', {
                title: 'Login',
                templateUrl: 'resources/views/layouts/loginUser.php',
                controller: 'authCtrl'
            })
            .when('/', {
                title: 'Login',
                templateUrl: 'resources/views/layout/login.php',
                controller: 'logoutCtrl'
            })
            .when('/reset', {
                title: 'Reset Password',
                templateUrl: 'resources/views/layouts/forgetPassword.php',
                controller: 'authCtrl'
            })
            .when('/invalidtoken', {
                title: 'Login',
                templateUrl: 'resources/views/layout/invalidtoken.php',
                controller: 'authCtrl',
                role: '0'
            })

            $locationProvider.html5Mode(true);
}])

Comment: No, # is not removing while i try this :(
Answer: With html5mode you have to specify the base url in your html file for eg,
<base href="/">

Some links you can go through for your reference,
https://docs.angularjs.org/error/$location/nobase
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag
Comment: $locationProvider is missing in you config function and one more thing you need to have server side routing as well, to get what you want. reason behind is when locaitionchagnestart it will look for the url and will through you a new error so to avoid that error you need to implement server side routing.
Comment: even i tried by adding locationProvider.. It didn't worked me. Can you help me out pls
Answer: it does not look possible you to remove hash-bang (#) from href manually, and it causes malfunction your router because hashbangs are enables browser not treat your state in order to send get request to an end point. browser does not fire a get request over #/route while it does over /route, unless you use your url provider in html5 mode. For html5 mode, add the line below into your app.config function:
$locationProvider.html5Mode(true).hashPrefix('!')


Is it significantly better to use ISO-8859-1 rather than UTF-8 wherever possible?

Question: For globalization of scripts, it is very common to use UTF-8 as the default charset; for example in HTML or default charset of mysql. This is also the case for latin website in which characters are in the class of ISO-8859-1. Isn't it advantageous to use ISO-8859-1 when UTF-8 characters are not needed. From advantageous, I mean critically beneficial.
My point is that only 0 - 127 characters of UTF-8 are 1 byte, and from 128 - 255 are 2-byte; where ISO-8859-1 is 1 byte system. Doesn't it play a critical role in database storage?
Comment: "Better" is so unspecific as to mean very little. What, exactly, are the qualities you're comparing? What are you trying to improve?
Answer: If everything you need now and forever is ISO-8859-1, you'll save space by using it, though likely not much if most of the characters used are < 128. If you ever need to use anything outside of ISO-8859-1, you'll be in a world of hurt. From an overall perspective, the cost in storage for UTF-8 is way lower than the cost of implementing multiple encodings.
Answer: Most of these 127 UTF-8 1-byte characters are the most used when you work with ISO-8859-1. Let's have a look here. If you use UTF-8 you will need 1 extra byte only when you use one of the 127-255 characters (not so commons I bet).
My opinion? Use UTF-8 if you can and if you haven't problem handling it. The time you save the day you will need some extra characters (or the day you have to translate your content) really worth a few extra bytes here and there in the DB...
Answer: Short answer: It doesn't matter.
Long(er) answer: Think of it that way. You have a message table that contains the messages of a forum. You have a lot of messages (let's say, 1 million). Assume every message takes 10 extra bytes due to UTF-8. That's 10 millions extra character, which is not even 10MB (not counting index).
For such a "popular" forum, you will not use more than 15MB of storage at most. That's nothing. You should definitely not worry about the extra bytes lost, and UTF-8 will provide benefits that are much more important than 10 MB.
Answer: Does size matter?
As you know, the characters in the range U+0080 to U+009F take up twice as much space in UTF-8 as they do in ISO-8859-1.  But, how often do these characters get used?
In a typical Spanish text I got from the front page of Wikipedia:

Artículo bueno
La séptima temporada de la serie de televisión de dibujos animados Los
  Simpson fue emitida originalmente por la cadena Fox entre el 17 de
  septiembre de 1995 y el 19 de mayo de 1996. Los productores ejecutivos
  de la séptima temporada fueron Bill Oakley y Josh Weinstein, quienes
  producirían 21 episodios de la temporada. David Mirkin fue el show
  runner de los cuatro restantes, incluyendo dos vestigios que habían
  sido producidos para la temporada anterior. La séptima temporada
  estuvo nominada para dos Premios Primetime Emmy, incluyendo la
  categoría "Mejor programa animado (de duración menor a una hora)" y
  obtuvo un Premio Annie por "Mejor programa animado de televisión". La
  versión en DVD fue lanzada a la venta en la Región 1 el 13 de
  diciembre de 2005, en la Región 2 el 30 de enero de 2006 y en la
  Región 4 el 29 de marzo del mismo año. La caja recopilatoria fue
  puesta a la venta en dos formatos diferentes: una caja con la forma de
  la cabeza de Marge y otra rectangular clásica, en la cual el dibujo
  muestra el estreno de una película.

There are 17 non-ASCII characters in a sea of 1044 ASCII characters.  That means an expansion of only 1.6% expansion when encoding in UTF-8.  Hardly worth worrying about, especially when the all-ASCII HTML markup is taken into account.
(However, the difference may be significant for a more heavily-accented language like Sango.)
How would your idea work, anyway?
Are you going to encode all your data in windows-1252?  That doesn't give you globalization; the globe does not stop at the Oder River.  True ISO-8859-1 (lacking €) is even worse; the globe does not stop at the English Channel.
Tag text with its encoding?  That works for XML, HTML, and SMTP.  But you asked:

Doesn't it play a critical role in database storage?

How do you intend to store mixed Latin-1 and UTF-8 strings in a database?
Have two columns EncodedText BLOB, IsUtf8 BOOLEAN?  How are you gonna query that?  Surely you won't just look at EncodedText and ignore IsUtf8; that approach leads to mojibake.
You could write a view with a column CASE WHEN IsUtf8 THEN EncodedText ELSE Latin1ToUtf8(EncodedText) END, and a proper INSTEAD OF INSERT trigger, but that's likely to cost you more bytes than it saves.


Extend spree to have functionalities as Shopify?

Question: I'm new to spree. I'm not sure whether is that possible to extend spree to have a functionality like Shopify. The user signups to create a store. He owns everything to that store. Each owner is not able to edit other stores.
How can I extend it? Which is the best strategy?

through database sharding, each store has it own database, connect to different based on domain name?
add store_id to every table, that would need to change a lot of code, right?

Any ideas?
Answer: You can have a look at this official extension:
https://github.com/spree/spree-multi-domain
This extension allows you to have multiple stores on multiple domains using the same backend.


R: Remove a row from all data.frames in global environment

Question: I have over 200 data.frames in my global environment. I would like to remove the first row from each data.frame, but I am not sure how.
Any help will be appreciated please let me know if further information is needed.
Comment: How did you wind up with such a mess? It would probably be better to keep those data.frames in a list rather than polluting your global environment like that. They would be much easier to work with that way.
Comment: See [How to make a list of data frames](http://stackoverflow.com/a/24376207/903061) to follow-up on MrFlick's advice.
Answer: This will list all the data frames in your environment, remove the first row from each, and organize them into a list of data frames. Generally, better practice to have them in a list so you can more easily apply functions across them and access them.
df <- lapply(ls(), function(x) get(x)[-1,])
Update: good idea to check if objects are in fact data frames and only work with those. First we create a logical vector listing dataframes, then combine them into a list and remove the first row of each.
dfs = sapply(ls(), is.data.frame)
lapply(mget(names(dfs)[dfs]), "[", -1, , drop = FALSE)

thanks to comments for finding my error and providing more efficient solutions
Comment: you should probably add a check that the object is a dataframe http://stackoverflow.com/questions/35387419/how-to-rbind-all-the-data-frames-in-your-working-environment-in-r/35387595#35387595


operator overloading "+" & "++" in C#

Question: public class EncryptVal
{
    private EncryptVal(T value)
        {
        Set( value );
    }
    // Encrypt
public bool Set(T value)
{}

// Decrypt & return (T)value;
public T Get()
    {}

public static implicit operator EncryptVal<T>(T value) {
    //shuffle bits
    return new EncryptVal<T>(value);
}

public static implicit operator T(EncryptVal<T> value) {
    //unshuffle bits
    return value.Get(); ///// error ...
}
}

i couldnt overload the + operator & ++ operator. How can i do this?
usage:
EncryptVal<int> e = 42;
EncryptVal<int> f = 1;
Console.WriteLine("decrypt int count \t= {0:d}", f.Get()); // ok
Console.WriteLine("decrypt int count \t= {0:d}", f); // error
Console.WriteLine("decrypt int count \t= {0:d}", e); //how?

Comment: The code you show doesn't have much to do with the question. I neither see an overloading of the + operator nor a usage of it.
Comment: how cna i do this + operator & ++ operator. and T is int, float, double. and Do you'll get value only variable without using the () get?
Answer: To overload + or ++ you simply add the + / ++ operators you want...
public static EncryptVal<T> operator ++(EncryptVal<T> value)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, string rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, EncryptVal<T> rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, int rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(bool lhs, EncryptVal<T> rhs)
{
    throw new NotImplementedException(); // your implementation here
}

It is unclear how this relates to the rest of the question, though.
In particular, the Console.WriteLine is probably going to want public override ToString() more than anything else.

operator overloading "+" & "++" in C#


How to send coupon code in new user registration email template?

Question: I have a requirement when ever anew user register to my site.I want to send the coupon code to the customer with registration email?
I followed following tutorial for the same. Tutorial
But I am getting a blank email containing nothing.
I used following in my config.xml
<frontend>
    <events>
        <customer_register_success>
            <coupon_observers>
                <coupon>
                    <type>model</type>
                    <class>Mynamespace_Coupon_Model_Observer</class>
                    <method>sendCoupon</method>
                </coupon>
            </coupon_observers>
        </customer_register_success>
    </events>
</frontend>

Comment: Is it a unique coupon code? If it's a general code, you can add it to your registration confirmation mail.
Comment: It should Take from Magento admin shopping cart price rule.
Comment: Is it the one and the same price rule for all customers?
Comment: Yes same coupon code will go to every customer for on time use only
Comment: Check my answer below. That's the most simple way.
Answer: Create the coupon code and set setting 'Uses per Customer' to 1.
Go to system -> transactional emails and change / add mailtemplate 'new account' and add your created coupon code to this mail.


How to rebuild my google cloud Compute Engine VM instance like Linode VPS?

Question: I am going to migrate my server from Linode to Google Cloud recently. When I am testing the google cloud Compute Engine VM instance, I can not find out the rebuild button like Linode.
Now I did some wrong operation on my VM instance, so I need to rebuild it. I don't want to delete it because I don't want to change the IP address.
I have tried the "reset" operation, but it is useless. I
Answer: Unfortunately Google Cloud Platform does not have the rebuild button. As I understand you don't want to loose your external IP address. I recommend you to reserve the ephemeral IP address of your actual instance, create a new one with a screenshot and then assign the reserved IP address.
Here are the steps:

Go to the External IP addresses page in the GCP Console. In the Type column, change the address type to Static for the IP address you want to promote. Provide a name for the new static IP address and click Reserve.
Stop the old instance.
Create a new instance with the snapshot and select the reserved IP address.


Find a basis for $V^m$

Question:
Given a vector space $V$ with a basis $\{e_1,e_2,e_3....,.....,e_n\}$. Construct a basis for $V^m=\{v_1,v_2,\ldots,v_m| v_i \in V\}$.

I was thinking of something like $(0,0,\ldots,e_i,0,\ldots)$ where $1 \le i \le m$.
Answer: If you define basis to be a spanning set, your $E = \{e_1, \ldots, e_n\}$ will do. If your basis also needs to be linearly independent, apply Gaussian Elimination to solve $E X = V^m$ and pick all the $e_i$ which have at least one non-zero coefficient anywhere in the resulting $X$ matrix.

Find a basis for $V^m$


If $\tau = (1,2)(3,4,5)$ determine whether there is a $n$-cycle $\sigma$ ($n\geq 5$) with $\tau = \sigma^k$ for some $k\in\mathbb N$.

Question: I would like to know if my proof below is correct.

Problem If $\tau = (1,2)(3,4,5)$ determine whether there is a $n$-cycle $\sigma$ ($n\geq 5$) with $\tau = \sigma^k$ for some integer $k$.

Solution: Let $\sigma = (a_1, a_2,\ldots,a_n)$. We actually prove a more general result here, i.e., $\sigma^k$ has a cycle decomposition with $d=\gcd(k,n)$ cycles, each having the same length $l=\dfrac{n}{d}$.
Pick any element, say $a_1$. Consider $\sigma^k$ acting on $a_1$. We then have $\sigma^k(a_1) = a_{1+k \pmod n}$. Let us look at the elements obtained by repeated action of $\sigma^k$ on $a_1$. In general, we have $\sigma^{kz}(a_1) = a_{1+kz \pmod n}$. For this to be equal to $a_1$, we need $kz\pmod{n} = 0$. The smallest positive $z$ gives the length of cycle containing $a_1$. The smallest value of $z$ is then $l=\dfrac{n}d$.
Now consider the smallest $a_i$ not generated by $a_1$ under $\sigma^k$ and repeat the process. This process has to terminate since $n$ is finite. Hence, $\sigma^k$ has a cycle decomposition with $d=\gcd(k,n)$ cycles, each having the same length $l=\dfrac{n}{d}$.
In our case, $\tau$ has a cycle decomposition where one cycle has a cycle length $2$ and another cycle has cycle length $3$. Hence, there is no $n$-cycle $\sigma$ ($n\geq 5$) with $\tau = \sigma^k$ for some integer $k$.

Thanks
Answer: Your more general result is correct, but they is some more work to be done in order to prove it. You need to show the following:

If $\gcd(n,k)=1$, then $\sigma^k$ is also an $n-$cycle.
If $\gcd(n,k)=d$, then $\sigma^k$ is a product of $d$ $\frac{n}{d}-$cycles.

You have done most of it. Does organise better your proof.
Comment: I do not see how if I add what you have written will improve my proof. Also, your second statement is wrong. It should be $\dfrac{n}d$ cycles and not $k$ cycles.
Comment: I made the correction.
Comment: It is again incorrect. It should read a "product of $d$ $\dfrac{n}d$-cycles".


upgrade nodejs centos 6.9

Question: I am received this error when try use module nodemailer in nodejs 0.12 distro centos 6.9
/root/node-v0.10.30/node_modules/live_webcam/node_modules/nodemailer/lib/nodemailer.js:3
const Mailer = require('./mailer');
^^^^^
SyntaxError: Use of const in strict mode.
I try update in nodejs but yum report 404 package
yum
How to fixed this?
Thank's any Advanced!
Answer: The current status of Node 0.12 is End-of-Life which means that you shouldn't expect it to work at all.
See the Node LTS schedule:

Few years ago (ages in terms of Node's history) io.js was forked from Node 0.12 because it was so outdated.
If you don't know how to install a newer version of Node then see my tutorial or Node website.
Comment: Hi thank you so much! After instaling nodejs :

root@sdv7 [/opt/node-6.7.0/node_modules/live_webcam]# node -v
v6.7.0

I copyed my aplication to /opt/node-6.7.0/node_modules/, but when run node server.js, receive this error :

root@sdv7 [/opt/node-6.7.0/node_modules/live_webcam]# node server.js
module.js:583
  return process.dlopen(module, path._makeLong(filename));
                 ^
Error: Module version mismatch. Expected 48, got 14.

Sorry my knowledge is not advanced in nodejs, I need to make some change in the code?

Thank you again!
Comment: Ok, I fixed this change module bcrypt by bryptjs. NodeJs now work for me!

Thank you !

upgrade nodejs centos 6.9


A simulation risk formulation where Bayesianism and frequentism is combined

Question: For my mathematics bachelor-thesis at the Statistics Netherlands, i became acquainted with frequentist and Bayesian statistics. I had set up a simulation-study, and I am not sure if the risk I conceived is faulty somewhow.
You see, I do not like that others in their simulation-studies only chose one parameter, since the behaviour of the estimators (in our context) is surely to change depending on the true parameter. However, I still like the idea of a true parameter and being able to sample data using the parameter. So here is an overview of different risk formulations i came up with:
1. Frequentist risk with chosen parameter: $R(L,\delta,\theta) = \int_X L(\theta,\delta(x))f(x|\theta)dx$
2. Bayesian posterior risk: $R(L,\delta,x) = \int_\Theta L(\theta,\delta(x))p(\theta|x)d\theta$
Notice that (1) is perfectly fine for the sample mean, i.e. The MSE for $\bar{X}$ is the same for any $\theta$ if the underlying distribution is normal. However, not every distribution gives rise to this invariance property.
Bayesian risk has the 'problem' that it does not consider data from the long run, but that is something I am not sure about*.
So hereby, I present you, pragmatic risk:
$R(L,\delta,p)=\int_\Theta L(\Theta,\delta(x))f(x|\theta)p(\theta)d\theta$
If my supervisor and I were to choose an objective flat-prior, then we can choose to approximate a 'Grand mean squared error' in the simulation-study for multiple estimators. And my interpretation of such a risk is that if the risk of two estimators differ, one of the estimators is safer in the long run, regardless of the true parameter.
Questions
*Does the Bayesian framework disregard 'the long run', or does it implicitly consider it in its computations, because the data-distribution-generating $\theta$'s are considered/weighted?
Is my interpretation correct?
Answer: This question is related to (if not a duplicate of) one XV question I answered a few days ago on the various definitions of Bayes risk. It is correct to note that the frequentist risk $\mathrm{R}(\theta,\delta)$ is dependent on the value of the parameter $\theta$ for most models and most estimators $\delta(\cdot)$. While the integrated Bayes risk
$$\mathrm{R}(p,\delta)=\int_{\cal{X}}\int_\Theta \mathrm{L}(\Theta,\delta(x))f(x|\theta)p(\theta)\,\text{d}\theta\,\text{d} x$$
is a constant real number for a given prior $p(\cdot)$ and a given estimator $\delta(\cdot)$. However it does depend on the choice of the prior $p(\cdot)$, which is unacceptable for non-Bayesians. For instance, F. Samaniego examines the frequentist properties of Bayesian estimators in his 2010 book,  A comparison of the Bayesian and frequentist approaches to estimation, by using several priors. Which is not an approach I particularly recommend. The "objective" Bayes solution of relying on a flat prior is similarly rejected by non-Bayesians (and some Bayesians), for reasons ranging from the issue of the choice of the dominating measure (lack of invariance by change of parameterisation), to the flat prior being outside probability distributions, to the possibility of an infinite Bayes risk.
However, the Bayesian framework does account for the frequentist distribution of the data, through the posterior, which means that most Bayes estimators are (a) admissible and (b) consistent ("in the long run"). See for instance complete class theorems (mentioned on XV here and here and there).


Putting a prior distribution on average GPA

Question: I am trying to see what would be an appropriate prior distribution for $\theta$, the average GPA of all college students who graduate in a particular year Y from university U. Assume also that from past data we know that usually about $50\%$ of graduating college students from U obtain a grade of $3.0/4.0$ or higher.
What would be a meaningful prior distribution for $\theta$? Given that we are not completely clueless about the past distribution of $\theta$, it would be better not to put a uniform prior on $\theta$. I was thinking of putting a normal prior distribution on $\theta$ but this seems problematic too, since the support of a normal distribution is $\Bbb R$ while the support of the prior for  $\theta$ is $[0,4]$. IS there some natural choice for the prior distribution given the above?
Comment: if you really want to use the normal you can put a normal prior on a transformed version of GPA (so that its on $\mathbb{R}$) e.g. $\text{GPA_transform} = logit(GPA/4)$
Comment: Do you have the actual data or do you want a conservative choice in the general case where you don't know the data? In the former case you could post a histogram.
Comment: @user7019377 I don't have any data (except for the information I am already providing). I am just trying to figure out a reasonable prior for this kind of a parameter in a general scenario, nothing specific given.
Answer: I would say that a natural choice of a distribution for a bounded real-valued variable is beta distribution. Standard beta distribution is bounded in $[0,1]$, but you can introduce additional parameters for lower and upper bound. Moreover, you can re-parametrize beta in terms of mean ($\mu = \tfrac{\alpha}{\alpha+\beta}$) and precision ($\phi = \alpha+\beta$),
$$ f(x) = \frac{1}{\mathrm{B}(\mu\phi, \,(1-\mu)\phi)} x^{\mu\phi-1} (1-x)^{(1-\mu)\phi-1} $$
what makes choosing the appropriate parameters easier.


Series expansion of Elliptic integral $F(\sin^{-1}(1-x)|-1)$ where $0<x\ll1$

Question: I understand the leading term $F(\pi/2\mid-1)$ would be $K(-1)$. I also want the next term contributing from $x$. Actually I could not expand $\sin^{-1}(1-x)$ (when $0<x\ll1$) around 1. Any help would be highly appreciated.
Thanks a lot.
Comment: Just to get the notation straight, $$ F(\varphi \mid m) = \int_0^{\varphi} \frac{d\theta}{\sqrt{1-m\sin^2{\theta}}} ? $$
Comment: yes. So $m=-1$ means $F(\phi|-1)=\int \frac{d\phi}{\sqrt{1+msin^2 \phi}} $, in the indefinite form.
Answer: We may put $1-y=\sin{\theta}$ in the integral, so $dy = -\cos{\theta} d\theta $, $\cos{\theta}=\sqrt{y(2-y)}$ on the interval in question, to find
$$ F(\arcsin{(1-x)}\mid -1) = \int_x^1 \frac{dy}{\sqrt{y(2-y)(1+(1-y)^2)}} = \int_x^1 \frac{dy}{\sqrt{y(2-y)(2-2y+y^2)}}. $$
Of course,
$$F(\arcsin(1) \mid -1) = F(\pi/2 \mid -1) = \int_0^{\pi/2} \frac{d\theta}{\sqrt{1+\sin^2{\theta}}} = K(-1) = \frac{\Gamma(1/4)^2}{4\sqrt{2\pi}}, $$
so this is the constant term (this particular value is found using the Beta-function integral). The rest comes from
$$ F(\arcsin{(1-x)}\mid -1)-F(\arcsin{(1)}\mid -1) = -\int_0^x \frac{dy}{\sqrt{y(2-y)(2-2y+y^2)}}, $$
and since $x$ is small, we can do by expanding the integrand:
$$ \frac{1}{\sqrt{y(2-y)(2-2y+y^2)}} = \frac{1}{2} y^{-1/2} \left(1 - y \left(\frac{3}{2} +  y - \frac{1}{4} y^2 \right) \right)^{-1/2} = \frac{1}{2} y^{-1/2} + O(y^{1/2}) $$
by using the binomial expansion on the bracket. Integrating term-by-term gives
$$ F(\arcsin{(1-x)}\mid -1) = K( -1) - x^{1/2} + O(x^{3/2}) = \frac{\Gamma(1/4)^2}{4\sqrt{2\pi}} - x^{1/2} + O(x^{3/2}), $$
and you can find more of the terms by a taking more terms of the expansion of $\left(1 - y \left(\frac{3}{2} +  y - \frac{1}{4} y^2 \right) \right)^{-1/2}$.

As for $\arcsin{(1-x)}$, we can use the same trick on its integral: putting $y=1-u$, $1-u^2 = 1-(1-y)^2 = y(2-y)$
$$ \arcsin{(1-x)} = \int_0^{1-x} \frac{du}{\sqrt{1-u^2}} = \int_x^1 \frac{du}{\sqrt{y(2-y)}}, $$
and then you can expand the square root binomially and get an expansion in odd powers of $x^{1/2}$ in the same way.
Comment: Excellent. But I think:
$F(\arcsin{(1-x)}\mid -1)-F(\arcsin{(1)}\mid -1) = -\int_0^x \frac{dy}{\sqrt{y(2-y)(2-2y+y^2)}}$
which leads to
$F(\arcsin{(1-x)}\mid -1) = K( -1) -\sqrt{ x} + O(x^{3/2}) = \frac{\Gamma(1/4)^2}{4\sqrt{2\pi}} - \sqrt{x} + O(x^{3/2})$

Kindly confirm.
Comment: Quite right. I think I've got it straight now; you're welcome to edit it yourself if I've missed something.
Answer: For more than the first term.
We can start using $$\frac d {dx}F\left(\left.\sin ^{-1}(1-x)\right|-1\right)=-\frac{1}{\sqrt{1-(1-x)^2} \sqrt{1+(1-x)^2}}\tag 1$$ and use Taylor expansions around $x=0$ $$\sqrt{1-(1-x)^2}=\sqrt{2} \sqrt{x}-\frac{x^{3/2}}{2 \sqrt{2}}-\frac{x^{5/2}}{16
   \sqrt{2}}-\frac{x^{7/2}}{64 \sqrt{2}}-\frac{5 x^{9/2}}{1024
   \sqrt{2}}+O\left(x^{11/2}\right)$$ $$\sqrt{1+(1-x)^2}=\sqrt{2}-\frac{x}{\sqrt{2}}+\frac{x^2}{4 \sqrt{2}}+\frac{x^3}{8 \sqrt{2}}+\frac{3
   x^4}{64 \sqrt{2}}+\frac{x^5}{128 \sqrt{2}}+O\left(x^6\right)$$ which makes the denominator of $(1)$ to be $$2 \sqrt{x}-\frac{3 x^{3/2}}{2}+\frac{7 x^{5/2}}{16}+\frac{5 x^{7/2}}{64}+\frac{11
   x^{9/2}}{1024}+O\left(x^{11/2}\right)$$ So
$$\frac d {dx}F\left(\left.\sin ^{-1}(1-x)\right|-1\right)=-\frac{1}{2 \sqrt{x}}-\frac{3 \sqrt{x}}{8}-\frac{11 x^{3/2}}{64}-\frac{7
   x^{5/2}}{256}+\frac{141 x^{7/2}}{4096}+O\left(x^{9/2}\right)$$ Integrating
$$F\left(\left.\sin ^{-1}(1-x)\right|-1\right)=-\sqrt{x}-\frac{x^{3/2}}{4}-\frac{11 x^{5/2}}{160}-\frac{x^{7/2}}{128}+\frac{47
   x^{9/2}}{6144}+O\left(x^{11/2}\right)+C$$ and $$C=F\left(\left.\sin ^{-1}(1)\right|-1\right)=F(\frac\pi 2|-1)=K(-1)=\frac{\Gamma \left(\frac{1}{4}\right)^2}{4 \sqrt{2 \pi }}$$.


Estimate of the variance

Question: If we have a set of samples $x_1 ,\dots, x_N$ and we denote with $\bar x = \frac{1}{N} \sum_i x_i$ their average, then the sample variance is defined as
$s^2=\frac{1}{N-1} \sum(x_i - \bar x)^2$
(see [1], for example).
I have found that someone says that the sample estimate of the variance is $s^2=\frac{1}{N^2}\sum_i \sum_{i'} (x_i - x_{i'})^2 $
(see formula (14.27) of [2])
"Sample variance" and "sample estimate of the variance" should be the same thing, right? However, I don't find how the 1st formula equates the 2nd.
Has anyone any idea? Thanks!
[1] https://onlinecourses.science.psu.edu/stat414/node/66
[2] Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.). http://statweb.stanford.edu/~tibs/ElemStatLearn/
Comment: The second equation appears to be variance across stratas
Comment: The second estimate involves a double summation and it is not clear exactly how $x_i$ differs from $x_i$,. What ranges are the summations taken over?  Finally the choice of N versus N-1 in the denominator in the case of equation (1) just depends on whether or not you want to use the unbiased estimator.
Comment: @MichaelChernick the double summation is over the same vector twice.
Comment: Maybe you missed "2" when you copied formula (14.27) of [2].  (2*var_j)
Comment: See https://stats.stackexchange.com/questions/225734/why-isnt-variance-defined-as-the-difference-between-every-value-following-each/225758#225758
Answer: The expression is missing a factor of 2.
Using the ol' add and subtract method to incorporate the term that you want:
\begin{eqnarray}
\sum_{i=1}^n \sum_{i^\prime}^n \left( x_i - x_{i^\prime} \right)^2 &=& \sum_{i=1}^n \sum_{i^\prime}^n \left( x_i - \bar{x} + \bar{x} - x_{i^\prime} \right)^2
\end{eqnarray}
Then we know we can factor the quadratic term because we like it that way.
\begin{eqnarray}
\sum_{i=1}^n \sum_{i^\prime}^n \left( x_i - \bar{x} + \bar{x} - x_{i^\prime} \right)^2 &=& \sum_{i=1}^n \sum_{i^\prime}^n \left( \left( x_i - \bar{x} \right)^2 + \left(x_{i^\prime} - \bar{x} \right)^2  + 2 \left(x_{i^\prime} - \bar{x} \right)\left(x_{i} - \bar{x} \right) \right)
\end{eqnarray}
The cross-product goes to 0.
\begin{equation}
\sum_{i=1}^n \sum_{i^\prime}^n \left( \left( x_i - \bar{x} \right)^2 + \left(x_{i^\prime} - \bar{x} \right)^2  \right) = \sum_{i=1}^n \left( x_i - \bar{x} \right)^2 + \sum_{i^\prime}^n \left(x_{i^\prime} - \bar{x} \right)^2  = 2 \sum_{i}^n \left( x_i - \bar{x} \right)^2
\end{equation}

Estimate of the variance


Alternatives to the classical pendulum ODE

Question: The classical (undamped) pendulum ODE is
$$\ddot \theta = -\frac{g}{\ell} \sin(\theta)$$
Defining state ${\bf x} := (\theta, \dot \theta)$, we have a system of $2$ ODEs, $\dot {\bf x} = {\bf f} ({\bf x})$, where ${\bf f} : \Bbb R^2 \to \Bbb R^2$.
Consider the change of coordinates ${\bf y} = {\bf \Phi} ({\bf x})$, where vector field ${\bf \Phi} : \Bbb R^2 \to \Bbb R^2$ is a diffeomorphism. Differentiating with respect to time,
$$\dot {\bf y} = \left(\left({\bf D \, \Phi} \cdot {\bf f} \right) \circ {\bf \Phi}^{-1} \right) ({\bf y})$$
where ${\bf D \, \Phi}$ denotes the Jacobian of vector field ${\bf \Phi}$, $\cdot$ denotes multiplication, $\circ$ denotes composition and ${\bf \Phi}^{-1}$ denotes the inverse of ${\bf \Phi}$. Are there "nice" choices of vector field ${\bf \Phi}$ that make vector field $$\color{blue}{\left( {\bf D \, \Phi} \cdot {\bf f} \right) \circ {\bf \Phi}^{-1}}$$ "nice" in some sense?
What is "nice"? For example, polynomial and rational functions are nice. All elementary functions are nice. Anything of relatively "low" descriptive complexity would be nice. In fact, any alternative to the classical pendulum ODE would be nice, even if highly contrived.

My work
The only idea I had was to rewrite the pendulum ODE in Cartesian coordinates, which led to
$$\begin{aligned} (\ddot x - g) y  - x \ddot y &= 0\\ x^2 + y^2 &= \ell^2 \end{aligned}$$
which isn't really a system of ODEs. Rather, it is a system of differential-algebraic equations (DAEs). Nothing else occurred to me. I am not familiarized with diffeomorphisms. Ideas are most welcome.
Comment: While it may not be the type of "nice" you are looking for, the [action-angle coordinates](https://en.wikipedia.org/wiki/Action-angle_coordinates) are often considered the "nicest" coordinates for this type of dynamical system.
Comment: Write the energy as $\dot θ^2+4\omega^2\sin^2(θ/2)=R^2$, so that one could use polar coordinates $\dotθ=R\cos\phi$, $2\omega\sin(θ/2)=R\sin\phi$, with $\dot R=0$, $\dot\phi=\omega\cos(θ/2)$.
Comment: But if even trigonometric functions are not okay and you insist on the word "diffeomorphism" (defined globally), the problem has no solution. One way to see it is this: the initial system has an infinite number of fixed points in $\mathbb R^2$, and the system you want (where trigonometry is forbidden) would only have finitely many.
Comment: Still, why $\Phi=\mathrm{id}$ is not okay for you? if sine function is not sufficiently elementary, then what do you mean by elementary?
Comment: @Startwearingpurple Because of [this](https://chemistry.stackexchange.com/a/84096/30836).
Comment: @Startwearingpurple I have nothing against "local" diffeomorphisms. This question was inspired by chemistry — can one "simulate" a pendulum using a chemical computer, even if only on a "small" region of the non-negative quadrant? — but is now a separate matter. At first, I was curious if my claim on Chemistry SE was correct. Now, I am curious about other things, too. If you believe the question should be refined, suggestions on how to refine it are most welcome.
Comment: If you just want to map the initial system  to a polynomial/rational one, one way is to rewrite the equation for $\theta$ as an equation for $u=\tan \frac{\theta}{2}$. Obviously, $\dot \theta=\frac{2\dot u}{1+u^2}$, $\ddot \theta=\frac{2\ddot u}{1+u^2}-\frac{4u{\dot u}^2}{(1+u^2)^2}$, $\sin\theta=\frac{2 u}{1+u^2}$, so that the differential equation $\ddot \theta+\sin\theta=0$ becomes $\ddot u-\frac{2u{\dot u}^2}{1+u^2}+u=0$ (which of course can be written as a 1st order system). But it might be that I misunderstand completely your aim.
Comment: @Startwearingpurple Thank you for the input. Very roughly speaking, in state space, a pendulum's trajectory is a curve, though not an ellipse. Is there a "coordinate system" in which the trajectory is indeed an ellipse? This "deformation" of the state space could be local rather than global. I am interested in behavior close to the origin, not in all the other equilibria.
Answer: It is possible to find another way for the solution of
$$y''+k\sin(y)=0 \qquad \text{with} \qquad y=y(x)\qquad \text{and} \qquad k>0$$
Switch variables and then write
$$\frac {x''}{[x']^3}=k\sin(y)$$ The usual reduction of order gives
$$x'=\pm\frac{1}{\sqrt{2 k \cos (y)+c_1}}$$ So
$$x+c_2=\pm\frac{2}{\sqrt{c_1+2 k}}F\left(\frac{y}{2}|\frac{4 k}{c_1+2 k}\right)$$ where appears the elliptic integral of the first kind.
This can be inversed easily leading to the amplitude for the Jacobi elliptic functions.
Answer: To solve the ODE in the form of
$$2y''+ p^2\sin y = 0,\quad p=\sqrt{\dfrac l{2g}},$$
can be used the integrating factor $\;y'\not=0,\;$ and that leads to the equation
$$y'^2 - p^2\cos y = y'^2\big|_{y=0} -p^2 = (k^2-1)p^2,$$
$$\dfrac{\text dy}{\text dx} = \pm p\sqrt{k^2 - 1-\cos y}\,,$$
with the solution
$$\pm p(x\bigg|_{y=0}+x) = \dfrac2{\sqrt{k^2-2}}\operatorname{F}\left(\dfrac y2\,\bigg|-\dfrac2{k^2-2}\right),$$
where $\;F\;$is the elliptic integral of the first kind.


rails generate active_admin:install error

Question: I run rails g active-admin:install
with Gemfile:
source 'https://rubygems.org'
gem 'rails', '~> 5.0.0'
gem 'pg'
gem 'activeadmin', github: 'activeadmin/activeadmin'
gem 'inherited_resources', github: 'activeadmin/inherited_resources'
gem 'devise',      '> 4.x'
gem 'rspec-rails', '>= 3.5.0.beta1'
gem 'ransack',    github: 'activerecord-hackery/ransack'
gem 'kaminari',   github: 'amatsuda/kaminari', branch: '0-17-stable'
gem 'formtastic', github: 'justinfrench/formtastic'
gem 'draper',     github: 'audionerd/draper', branch: 'rails5', ref: 'e816e0e587'
gem 'activemodel-serializers-xml', github: 'rails/activemodel-serializers-xml'
gem 'rack-mini-profiler',          github: 'MiniProfiler/rack-mini-profiler'
gem 'database_cleaner',            github: 'pschambacher/database_cleaner', branch: 'rails5.0', ref: '430a957'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'

But get error:
/home/user/.rvm/gems/ruby-2.2.3/gems/actionpack-5.0.0/lib/action_dispatch/middleware/stack.rb:74:in `insert': can't modify frozen Array (RuntimeError)
from /home/user/.rvm/gems/ruby-2.2.3/gems/actionpack-5.0.0/lib/action_dispatch/middleware/stack.rb:74:in `insert'

When I run:
bundle install

It works perfectly.
Can anyone help me?
UPDATE
Solved by install or update ruby version.
Comment: Same issue occured, I do the changes and rub as answer below
Answer: Please do update the Gemfile as:
gem 'devise'
gem 'activeadmin', github: 'activeadmin'
gem 'inherited_resources', github: 'activeadmin/inherited_resources'

and run
rails g active_admin:install
Comment: Still I have error

`/home/user.rvm/gems/ruby-2.2.3/gems/actionpack-5.0.0/lib/action_dispatch/middleware/stack.rb:74:in insert': can't modify frozen Array (RuntimeError)`

Do you know why?
Comment: It is bug in the previous version due to compatibility issue. Could you please update rails to latest code as on GitHub.
Comment: so, I change gem `'rails', '~> 5.0.0'`?


Segmentation fault on returning from main (very short and simple code, no arrays or pointers)

Question: I've been wondering why the following trivial code produces a segmentation fault when returning from main():
<code>//Produces "Error while dumping state (probably corrupted stack); Segmentation fault"

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

class Test
{
    vector<int> numbers;
};

int main()
{
    Test a;
    ifstream infile;

    cout << "Last statement..." << endl; // this gets executed
    return 0;
}
</code>
Interestingly,
1) if only one of the two variables is declared, I don't get the error,
2) if I declare a vector variable instead of an object with a vector member, everything's fine,
3) if I declare an ofstream instead of an ifstream, again, everything works fine.
Something appears to be wrong with this specific combination...
Could this be a compiler bug? I use gcc version 3.4.4 with cygwin.
Thanks for the tips in advance.
Gábor
Comment: gcc 3.4.4 is ancient. Can you try with the 4 series?
Comment: I recall seeing a bug report with something similar, I can't remember exactly though so I can't find it. But I'm pretty confident this is an obscure bug that has since been fixed.
Comment: Come come. I remember when 3.0 was state of the art. Now gcc 2.95/2.96 now there was an old and wacky compiler.
Comment: I just tried to compile your program in g++ version

    g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)

and it works fine
Comment: Funny it should work for you, Thanh, with the same version of gcc. (Although I don't really see why the gdc and dmd version is relevant here; aren't these related to the D programming language?)
Answer: This is a bug.  If this is your entire program, there is absolutely nothing wrong with it.  You have discovered a bug in the compiler or standard library.  As was recommended to you in the comment, try a 4.x series gcc compiler.  The 3.x series is old as the hills.
Comment: Thanks a lot for the prompt answers/comments. Unfortunately, upgrading the compiler is no simple matter in this case. I'm developing a psychology experiment with a C library called Tscope, which is dependent on the Allegro game library. Tscope comes prepackaged with a cygwin environment, gcc compiler, basic IDE, etc. The problem is: Allegro does not compile on the more recent cygwin anymore. And I don't believe just replacing gcc.exe would work, would it?
Comment: @Gábor Kovács - No, that wouldn't be enough.  But I believe cygwin has a packaging system that allows you to selectively upgrade.  So you could try that.


Atualizar e Inserir dados numa tabela com informações de outra em outro banco

Question: Tenho a seguinte situação:
Banco A e o banco B ambos com a tabela clientes com o os seguintes dados:
A.clientes                    B.clientes

id    | nome                  id    | nome
-------------------           -------------------
1     | Lucas                 1     | Mauro
5     | Marcos                3     | Sergio
8     | Paulo

Gostaria de um comando para atualizar e inserir na tabela clientes do banco B os dados que estivessem na tabela clientes do banco A e que esse fosse o resultado:
B.clientes
id    | nome
-------------------
1     | Lucas    <- UPDATE
3     | Sergio
5     | Marcos   <- INSERT
8     | Paulo    <- INSERT

Meu SGDB é o PostgreSQL.
Comment: Esses bancos estão no mesmo servidor ou em servidores diferentes?
Comment: Mesmo servidor @JefersonAlmeida
Comment: @AnthonyAccioly passei esse mesmo link na minha resposta, caso ele precise realmente fazer isso
Answer: Existem algumas maneiras de se fazer isso no PostgreSQL.
Você pode utilizar o dblink por exemplo.
insert into clientes
select *
from dblink('dbname=postgres hostaddr=xxx.xxx.xxx.xxx dbname=A user=postgres',
            'select id,nome from clientes')
       as t1(id int,nome text);

Com esse comando acima você poderia consultar as informações no outro banco e atualiza-las ou inserir-las conforme sua necessidade.
Caso não saiba como fazer um comando de insert ou update você pode está verificando isso nesse link do SO InserOrUpdate
Comment: Vou testar e digo o resultado, obrigado.
Comment: @LaércioLopes qualquer dúvida ou problema é só avisar


Simple linear regression

Question: Consider the simple regression model $y=\beta_0+\beta_1x+u$, where $\text{corr}(x,u)=1$ and all random variables have normal distributions. Is it possible to provide asymptotically consistent estimates for $\beta_1$?
Since $corr(x,u)=1$, we can write  $u=ax+b$ and substitute it to get $y=\beta_0+b+(\beta_1+a)x$. So our observations lie on the straight line given by this equation. What sort of conclusion can we derive from this?
Comment: It would be nice to know how did you arrive at this question. I cannot imagine real life situation where such type of information about regression model would be available. (For that matter no imaginary life situation is possible too)
Comment: I am preparing for exam, so this is one from the last year's final.
Answer: This is a weird question: the simple regression model is defined conditional to the regressor $X$, hence (a) for each observation $y_1$, $x_i$ is observed as well and (b) if the noise $U$ is perfectly correlated with $X$, this means that the noise $u_i$ is also observed: $u_i=ax_i+b$.
Conclusion: there is no randomness and one only needs two observations to derive w/o error the parameters $(\beta_0+b,\beta_1+a)$, therefore $(\beta_0,\beta_1)$ if $(a,b)$ is known.
Note: If $(a,b)$ is unknown, w/o any additional assumption, all one can estimate is $(\beta_0+b,\beta_1+a)$.
Comment: @marcin63:  all your observations $(x_i,y_i)$ will be on the same line with parameters $(\beta_0+b,\beta_1+a)$. So you can only estimate the slope and intercept of this line.
Comment: And how to show rigorously, that if we don't know the coefficients in the linear relation $u=ax+b$, then we can not estimate $\beta_1$ consistently? (That is, we only know the fact that $corr(x,u)=1$)
Comment: Yes, i understand that we can only estimate $\beta_1+a$, so we are not able to recover estimate of $\beta_1$ from this model. But probably it can be shown more explicitly that we have an identification problem and can not suggest estimate of $\beta_1$?
Comment: @marcin63: the identifiability problem is explained in my previous answer. All you get is $\beta_0+b$, exactly. The proof of non-identifiability cannot be more explicit than that.
Answer: This is not simple linear regression. Simple linear regression is $y = \beta_0 + \beta_1x + u$, but with cor(x, u) = 0. Indeed, your second equation $y = \beta_0 + b + (\beta_1 + a)x$ is the simple linear regression for the situation, but you should add $u$ with $u \sim \mathcal{N}(0,0)$
One can conclude that this is fantasy land, because all the observations never lie exactly on the line. George Box said "all models are wrong but some models are useful". You've posited a model which is exactly right. No model error, no measurement error.

Simple linear regression


What are the quintessential characteristics of bebop?

Question: What are the characteristics that make bebop, bebop?
A well-written answer in my perspective includes but is not limited to the following (credit to @jdjazz for writing (a) through (e))

(a) the harmony/chords of bebop (upper extensions, alterations, presence more changes, lots of ii-V's, substitutions, reharmonizations)
(b) the melodies (heavy syncopation, up-tempo)
(c) the rhythmic patterns
(d) the structure of songs (head-solos-head, with a heavy emphasis on improvisation & virtuosity)
(e) the foundations in blues & swing (e.g., melodic ideas, harmonic ideas, contrafacts, but also the ways bebop intentionally deviated from these genres)
(f) the historical and cultural elements. (The rhythm section evolved quite a bit too in bebop.)
(g) IMPORTANT-> an analysis of the particular musical devices and phrases that are quintessential to bebop.

For example, in part (f), an answer may include 13 different musical devices, and for each of those devices, say, the use of the b13 as a passing tone on a major chord, your answer explains the concept in detail and gives examples of those devices listing specific timestamps to bebop masters such as Charlie Parker or Bud Powell using that musical device.
I know this may seem like a really long question with lots of research to be done, but I feel that it will be super beneficial to all the jazz lovers out there and to anyone learning the genre of bebop.
Comment: Would a brisk tempo also be a defining feature of bebop, or is there also such a thing as a "slow bebop ballad"?
Comment: @Dekkadeci, that's a good question. Ballads were played in bebop, and there were definitely some medium tempo tunes, but the really fast tempos were very prominent and represented a break from swing music, which was played at tempos people could dance to.
Comment: I agree that the information is valuable. The point about culture may or may not be off-topic--I would need to think more about that. (For the bebop movement, cultural influences are generally viewed as inextricable from the musical elements by academic scholars.) Looking at the question as edited, I am wondering if it would be best to split this into several different questions? The way the original Q was written, I was thinking of just a brief overview of each point. A detailed analysis of each point may be too hard to do in one question.
Comment: I have an Adobe Acrobat PDF of the Jamey Abersold's Jazz Handbook. I could uplink it but I don't know how to do that to this web service. It is an excellent overview of Jazz with specific sections about Bebop and the Blues with a lot of scales, hints, tricks and techniques.
Comment: The book is available on Jamey Aebersold's site: http://www.jazzbooks.com/mm5/download/FQBK-handbook.pdf
Answer: As David Baker puts it:

Complex harmonic ideas
Longer melodic phrases using odd intervals built on the extensions of chords (9ths, 11ths, 13ths, etc.).
Harmony gained equal footing with melody and rhythm (western influence).
A sound instrumental technique was mandatory.
A good ear and a quick mind were indispensable.
Eighth notes and sixteenth notes became the basic units of time.
Horns aimed for clean, piano-like execution.
Players followed the trend toward the vibrato-less sound(reducing the latitude
  and flexibility of sound production is another western concept). as a
  practical consideration, virtuosity demands an unencumbered sound.
The emphasis was more on content than on sound.
Complex chords provided soloists with a broader harmonic base; making possible a
  greater variety of note choices and a higher incidence of
  chromaticism.
Chords served as the improvisational referential rather than the melody.
Hot improvisation (fast, intense, impassioned) was the rule.
Collective improvisation was exclusively between the soloist and the rhythm section.
Bebop was primarily small band music but found some expression in a few select
  big bands.
A broadened concept of chord substitution came into being; this helped to provide a broader harmonic base.
The music moved ever closer to western European music because of its emphasis on harmony and instrumental facility and it's increasing
  use of other western musical devices.
The entire language of jazz was questioned, subtracted from, added to, purged, and reaffirmed.
Poly-rhythm became an important factor again.
Bebop tended to codify all that had gone before; it is considered the common practice period in jazz.
Unison melody statements were the rule of thumb because the increasing harmonic complexities made counterpoint and secondary
  lines less feasible.
The break as a structural device regained popularity.
Bebop players made liberal use of "quotes" or interpolations from other tunes.
Bebop reduced melody to its essentials.there were few backgrounds, some brief
  introductions and endings, and some unison interludes.
Melodic lines were scalar rather than chordal.
More sophisticated scales were introduced into the language; one example is the diminished scale (1 b2 b3 3 #4 5 6 b7 8)
There was more effort to make the solo lines cohesive by linking them together with turn-backs, cycles, and another musical adhesive
  devices.
The piano became the center of the new expression.
Asymmetrical solo construction became a fact.

My source is Jamey Aebersold's Jazz Handbook.
Comment: The source you've cited is extremely helpful. However, per the Help Center: "Do not copy the complete text of external sources; instead, use their words and ideas to support your own." Copying and pasting an complete text of an article someone else wrote can qualify as copyright infringement, even if you cite the source.
Comment: This is pretty good answer however it does not touch on all the points that I mentioned in my question. If you expand on these points and organize them it will be a great answer
Answer: Bebop characteristics include fast harmonic changes, modulations, ii-V-I cadences, dominant cycle progressions, the use of tritone substitutions and upper scale extensions. Use of altered sounds on functioning V7 chords (Those resolving to the tonic from the 5). These sounds are generated via triadic pairs, the altered scale, whole tone, harmonic and melodic minor and many other pitch collections, including diminished arpeggios and other four note arpeggios derived from min-major chords, major augmented, dominant chords and half diminished arpeggios.  Scales and arpeggios feature in the use of melodic improvisation, including the Lydian dominant for tritone chords, half whole and half whole scales, all in the pursuit of reconciling altered notes tension to provide melodic movement via the release of non diatonic sounds into resolved cadences.  Stylistically the bebop sound features techniques such as Coltrane changes for fast passages, and approach notes, both diatonic and chromatic, and also features such as enclosures over key chord tones. Other devices include 3-9, 5-11, 7-13 arpeggios, the "minorisation" of dominant chords sounds, conversion of singular dominant chords into ii-V substitutions. And the ii-V equivalents generated by using the tritone chord substitution. And also extensive use of upper harmony, altered fifths and 9ths. Also chord inversions, drop 2, drop 4 harmony and many other techniques.


How to find the expected distance between a point consisting of two random variables and the origin?

Question: Let ($X_1, X_2$) be two independent standard normal random variables. Compute $E[\sqrt{X_1^2+X_2^2}]$, the expected distance between ($X_1, X_2$) and the origin.
This is the question I need to solve. I have no idea where to start.
Comment: Use the polar coordinate trick that gives us the $\sqrt{2\pi}$ in the formula for the gaussian density function.
Answer: This question has been answered on the Cross Validated site of the StackExchange community. Check out the answer here.


jQuery Mobile não permite links internos

Question: Estou criando esboço de aplicação em HTML 5 para rodar em dispositivo mobile.
No meu projeto, precisei usar diferentes versões do jQuery para os eventos funcionarem:

Usei funções como Animate e Swipe do jQuery Mobile. O problema é quando adiciono o jQuery Mobile, meus links internos param de funcionar. O console dá a seguinte mensagem:

XMLHttpRequest cannot load
  file:///Users/nome-do-usuario/AndroidStudioProjects/WebViewOficial/app/src/main/assets/testeTouch.html.
  Cross origin requests are only supported for protocol schemes: http,
  data, chrome, chrome-extension, https, chrome-extension-resource.

Somente links externos funcionam. Obviamente que já pesquisei por aí. Mas nenhuma solução que se pareça com meu caso.
Código completo
<!DOCTYPE html>

    <title></title>

    </button>

<content >

    <canvas id="myCanvas" width="180" height="200" style="border:1px solid #000000;">Conteudo</canvas>

</content>

Evento arrastar para os lados em Jquery!

    <canvas class="deslizante" width="300" height="300" style="border:1px solid #000000;">Para testar o evento, arraste o touch para os lados/p>

Para instalar, copie e cole as pastas do projeto na raiz, cole os scripts no head, e configure uma div com a id deslizante!

  <canvas id="myCanvas" width="180" height="200" style="border:1px solid #000000;">Conteudo</canvas>

<canvas id="clicavel2" width="70" height="70" style="border:1px solid #87CEEB" class="clicavel"></canvas>
<canvas id="clicavel3" width="70" height="70" style="border:1px solid #87CEEB" class="clicavel"></canvas>
<canvas id="clicavel4" width="70" height="70" style="border:1px solid #87CEEB" class="clicavel"></canvas>

FLUTUANTE3

Comment: Como e onde você referencia `testeTouch.html`?
Comment: No footer. Coloquei o código completo na edição do post
Comment: Estranho. Não tenho ideia do que pode ser isso. +1.
Answer: Solução:
O Jquery Mobile é um framework voltado para aplicações híbridas. Incluindo aplicativos Mobile. Com isso, algumas requisições são tomados certos cuidados, por este motivo o COR (Cross origin requests) não tem suporte a request externo. Existem algumas formas de solucionar isso, mas a que encontrei no meu caso foi criar uma função de redirecionamento dentro do JS da mesma pasta da aplicação.
Assim:

Seu texto

Referências:
https://stackoverflow.com/questions/12910813/jquery-mobile-error-loading-page
https://jquerymobile.com/


Get the view object in a custom block plugin

Question: In Drupal 10, I want to create a custom block plugin. Blocks instances of this new block type would be placed in a region on a View page.
How can I gain access to the View object from a programmatic block?
I had thought perhaps adding a ContextDefinition in the block annotation, but I don't see that View is a possible option.
In the block I'd like to have access to the $view->result array, after the View has been executed.
Any thoughts?
Answer: To Get View object in custom block plugin you can follow this snippet code: (Drupal 9/10)
<code>use Drupal\views\Views;

// Get current route object.
  $route = \Drupal::routeMatch()->getRouteObject();
  if ($route) {
    // Get view id & display id from current route.
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    if (!empty($view_id) && !empty($display_id)) {
      // Get the view by id.
      $view = Views::getView($view_id);
      if ($view) {
        // Set display id.
        $view->setDisplay($display_id);
        // Run execute() to get result count.
        $view->execute();
        // Get view result count.
        $result_count = $view->total_rows;
      }
    }
  }
</code>
Note:  Don't skip $view->execute() otherwise result_count 'll be render null despite of having value
If the code works fine the can do code optimization, like instead of calling directly APIs like below: can use dependency injection
<code>\Drupal::routeMatch()->getRouteObject();
</code>
Reference link on dependency injection in a plugin (block)
Comment: This is a good answer. I'd like to have the View object after the query is executed, so the View doesn't have to execute twice, but I can't see how to do that.
Comment: Well , that's nice question from site optimisation perspective as well, however as you see above code basically get current view page id, then get current view object and execute view to get executed view results.
If there is  API() function provided by Drupal core to get view object from current view page (for eg as it is provided for node page to get node object from current node page) then it can be possible to get view object after view executed.
Comment: If you want to know view is executed or not then you can try this code:

    $view->executed;
      where $view denotes view object
Comment: I was using the views_remote_data module, to wrap API results to a View. SO I cached the API result by url parameters, then I could load the View programmatically as many times on the same page, and at least the API call was cached, so achieved the effect I needed
Answer: I am not sure I follow your question entirely, but when you make a views page, you should have all of the regions all of your other pages have, you just put your block in there like you would any other page -- unless you have changed the theme for that page and then you need to look to see what regions that theme is providing.
Comment: Yeah, I'm making a custom block plugin, and in the code for that, I want access to the View object, so I can programmatically sift through the results, and do some custom output in the block. I also don't want the View executed twice.
Comment: Imagine like a facets block but for a normal view.
Comment: You may want to add that clarification to the ticket :)
Comment: I think its impossible but we'll see. I'll ask ChatGPT too. stackexchange vs. AI grudge match. Lets go.
Comment: You may want to consider something like views json https://www.drupal.org/project/views_json_query
it will provide you with an api to get your views results that you can consume in your block code
Comment: you could also consider writing a controller that uses entity manager to do your query and not use views at all.
Comment: I was using the views_remote_data module, to wrap API results to a View. SO I cached the API result by url parameters, then I could load the View programmatically as many times on the same page, and at least the API call was cached, so achieved the effect I needed.


Consulta MySQL três tabelas

Question: Estou tentando fazer uma consulta no banco de dados MYSQL, mas a consulta não está voltando o que eu queria. Quero fazer uma consulta onde retorne todos os módulos e os módulos que a empresa tem com a cláusula where em Empresa_ID.
Tentativa do MySQL:
   SELECT empresas.empresa_id
         ,empresas.empresa_razaosocial
         ,modulos.modulo_id
         ,modulos.modulo_nome
         ,empresa_modulo.modulo_id
     FROM empresa_modulo
    RIGHT JOIN modulos
       ON modulos.modulo_id = empresa_modulo.modulo_id
    RIGHT JOIN empresas
       ON empresas.empresa_id = empresa_modulo.empresa_id
   UNION
   SELECT empresas.empresa_id
         ,empresas.empresa_razaosocial
         ,modulos.modulo_id
         ,modulos.modulo_nome
         ,empresa_modulo.modulo_id
     FROM empresa_modulo
    RIGHT JOIN modulos
       ON modulos.modulo_id = empresa_modulo.modulo_id
    RIGHT JOIN empresas
       ON empresa_modulo.empresa_id = empresas.empresa_id
    WHERE empresas.empresa_id = 1;

Resultado:

Fiz essa consulta, mas não tive sucesso. Como posso realizar esta consulta?
Uma consulta que retorne todos os modulos e os modulos que a empresa tem.
Comment: Sem ter um exemplo dos dados fica difícil ajudar. Aparentemente sua consulta está certa, não pode ser dados que não foram encontrados nos `right join`?
Comment: O que você quer? O que retorna? Explique melhor.
Comment: @JoanMarcos Você precisa mostrar uma amostra dos dados, o que você está recebendo no momento, e o que você gostaria de receber quando estiver certo.
Comment: Está ae, corrigir
Comment: @user94991 está ae o resultado.
Answer: Joan, o print do resultado é o que vc espera, certo?
A sua consulta esta errada, uma vez que você está querendo todos os modulo não há a necessidade de você usar right join.
--Nesse select você vai relacionar todos os modulo que tem relacionamento.
SELECT e.empresa_id
      ,e.empresa_razaosocial
      ,m.modulo_id
      ,m.modulo_nome
      ,em.modulo_id
  FROM empresa_modulo em
  JOIN modulos m
    ON m.modulo_id = em.modulo_id
  JOIN empresas e
    ON e.empresa_id = em.empresa_id
---Se adicionar o where, você selecionará apenas a empresa com o id 1.
 WHERE e.empresa_id = 1;

Você sabe a diferença de Union e Union ALL?
Quando você usar o UNION ele retornará apenas os registros unicos, com o ALL você terá linha repetidas.
Tente usar o seguinte:
SELECT e.empresa_id
      ,e.empresa_razaosocial
      ,m.modulo_id
      ,m.modulo_nome
      ,em.modulo_id
  FROM empresa_modulo em
 CROSS JOIN modulos m
    ON m.modulo_id = em.modulo_id
 CROSS JOIN empresas e
    ON e.empresa_id = em.empresa_id;

Consulta MySQL três tabelas


Using a factory and controller to return data

Question: I have the following factory:
app.factory('clientFactory', function ($http) {
    var factory = {};

    factory.getClients = function () {
        var url = "/tracker/api/client";
        $http.get(url).then(function (response) {
            return response.data;
        });
    };

    factory.getClient = function (id) {
        // TODO
    };

    factory.insertClient = function (firstName, lastName, city) {
        // TODO
    };

    factory.deleteClient = function (id) {
        // TODO
    };

    return factory;
});

And the controller:
app.controller('ClientController', function ($scope, clientFactory) {
    $scope.clients = [];

    init();

    function init() {
        $scope.clients = clientFactory.getClients();
    }

    $scope.insertCustomer = function () {
        // TODO
    };

    $scope.deleteCustomer = function (id) {
        // TODO
    };
});

In my controller, 'clients' is always null.  I've tried a couple of other approaches like what I see here but I got an error that 'success cannot be called on null' and if I make it past that error, my success function is never called.
What am I missing here?
Answer: In your controller, you are treating the getClients method as if it were synchronous.  Remember that when you do $http.get, a promise is returned.  You need to return that promise to the controller, so it can call .then with a method which will handle a successful result.
Your getClients method needs to look like this:
factory.getClients = function () {
    var url = "/tracker/api/client";
    return $http.get(url);
};

And I believe your init method needs to look like this:
function init() {
    clientFactory.getClients().then(function(response) {
        $scope.clients = response.data;
    });
}

Try that out!
Comment: Excellent!  Thanks very much... coming from the jQuery world, things were either async or not and there was some magic there (at least to me).  The promises stuff is new to me.
Comment: Yeah promises take a little bit to wrap your head around, but once you understand them you will love them.  They are a huge part Angular, so you will be seeing them much more often!


Correlation or independence on contingency table for large N

Question: I have a dataset with about 35,000 individuals described by around 15 categorical variables.
I'm trying to study the independence / correlation between these 15 categorical variables. My first idea was to, for each pair of variables, create a contingency table and calculate the $\chi^2$. Then, study the overall difference in the statistic. However, because the population is so large, $\chi^2$ is always significant. I'm having difficulty interpreting and comparing the results for each pair of variables.
So, I can summarize my question as follows:

For large datasets, when I know $\chi^2$ will almost always be significant, is there an alternative test that will give more reasonable results?

I have two ideas, as well

I was thinking of taking many bootstrap samples of say 1K individuals. On each sample calculate the correlation, then average over all the bootstrap samples. The average should be a good representation of the overall sample, but I feel like I'm somehow cheating.
Can I simply compare the magnitudes of the $\chi^2$ test between the different pairs of variables? The degrees of freedom are different (the categories are of different sizes), which leads me to think this won't make sense.
Comment: I have some thoughts that I hope will help add context why you're making some decisions in about your research. Keep in mind that your $\chi^2$ results will also be sensitive to how you transformed the continuous variables into categories. Rebinning could change the kinds of results that you obtain. Generally it's best practice to keep the data in the original units, so that the texture of the data is retained. Also, it's unclear to me why you want to do a $\chi^2$ test when you have binary outcomes and continuous predictors -- isn't that what logistic and similar regressions are for?
Comment: None of those reasons for binning are particularly persuasive. Binning lowers power *and* increases type I error. Missing data can be dealt with. In my view, binned models are harder to interpret, not easier. And data entry errors shouldn't just be shoved into a bin, they should be dealt with.
Comment: Well, since you have so many data points, it seems justifiable to reduce Type I and Type II error rates. At conventional rates, you've basically wasted resources by over-collecting data.
Comment: And a follow up question for Mr Flom. Are you saying that with regression on categorical variables, correlation analysis is unnecessary?
Answer: Answering my own question (because no one gave an answer) based on another post.

Unless your observations have a cost benefit tradeoff of some kind (e.g. paying subjects) then there's not really any such things as too many. More observations give better parameter estimates.
The test you used handled 10,000,000 observations just fine.
Your "problem" isn't a problem at all. The estimate of a parameter becomes very good when N is very large to the point that any measurable deviation from no difference becomes a statistically significant difference. That doesn't mean the difference is meaningful or practically significant. That's a judgment call you'll have to make.
One way to help you is to calculate an effect size. Typically Cramer's V (ϕc) is used. Note that for goodness of fit you use the rows instead of smallest dimension and it is interpreted as the tendency toward a singular outcome. Cramer's V for your experiment is going to be an extraordinarily tiny number, suggesting the effect is very small.
But in this case, the numbers so obviously tell a tale of a very small effect I think that just showing the numbers is sufficient. What you would say is that the expected probabilities are nearly identical to the observed and leave it at that.

In summary: The Chi-squared will show significant differences because N is large. In this case it is best to look at the size of the test statistic rather than the p-value. Random sampling can reduce N, but it is an un-satisfactory solution.
Alternatively, calculate the confidence intervals.
Comment: Uh, this looks like pretty much a direct copy of the other answer, to the point that it includes information that's relevant not to your question but to the other one. Can you edit so that this answer at least relates to the specifics of your question?
Comment: Correct. I feel bad answering my own question, but no one gave it a try. How about I keep that in quotes, then add my own bit of explaining?
Comment: you needn't feel bad for answering your own question; that's completely okay here - that's made explicit in the help. My concern was simply that your answer could have been replaced by a link to the other one. I'm sorry you didn't get a good answer when it came up originally.