Pesquisa de Filtro

Question: estou com um problema para criar um filtro de busca com select, fiquei bem confuso, vou postar o codigo e uma imagem do que necessito:
o codigo:
 <?php
    session_start();
    include_once("../../conexao/conexao.php");
    include_once("../../seguranca.php");
    include_once("../../header.php");
    include_once("../../menu.php");
    seguranca_adm();
    ?>

    <?php
    //Verificar se está sendo passado na URL a página atual, senao é atribuido a pagina
    $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1;
    if(!isset($_GET['pesquisar'])){
        header("Location: adinistrativo.php");
    }else{
        $valor_pesquisar = $_GET['pesquisar'];
    }

    //Selecionar todos os curriculos da tabela, tentei buscar por mais uma tabela tipo o OR tabela empresa mas não rola.
    $result_curriculos = "SELECT * FROM curriculos WHERE nome LIKE '%$valor_pesquisar%' OR empresa LIKE '%$valor_pesquisar'";

    $resultado_curriculos = mysqli_query($conn, $result_curriculos);

    //Contar o total de curriculos
    //Aqui gera um erro nessa linha - Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\curriculo\adm\administrativo\pesquisar\pesquisar.php on line 84
    $total_curriculos = mysqli_num_rows($resultado_curriculos);

    //Seta a quantidade de curriculos por pagina
    $quantidade_pg = 6;

    //calcular o número de pagina necessárias para apresentar os curriculos
    $num_pagina = ceil($total_curriculos/$quantidade_pg);

    //Calcular o inicio da visualizacao
    $incio = ($quantidade_pg*$pagina)-$quantidade_pg;

    //Selecionar os curriculos a serem apresentado na página - aqui também da o erro Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\curriculo\adm\administrativo\pesquisar\pesquisar.php on line 98
    $result_curriculos = "SELECT * FROM curriculos WHERE nome LIKE '%$valor_pesquisar%' OR empresa LIKE '%$valor_pesquisar' limit $incio, $quantidade_pg";
    $resultado_curriculos = mysqli_query($conn, $result_curriculos);
    $total_curriculos = mysqli_num_rows($resultado_curriculos);
    ?>

Curriculos

                    <form class="form-inline" method="GET" style="padding:20px 0px 20px 0px" action="pesquisar.php">

                                Nome do candidato

                                <input type="text" name="pesquisar" class="form-control" style="width:200px;" id="exampleInputName2" placeholder="Nome do candidato...">

            <?php if(!empty($row_curriculos['empresa_id'])){
                $empresa_id = $row_curriculos['empresa_id'];
            }?>

                Empresa

                    <select class="form-control" name="select_empresa">
                        <option value="">Selecione</option>
                        <?php
                        $result_empresa = "SELECT * FROM empresa";
                        $result_empresa = mysqli_query($conn, $result_empresa);
                        while($row_empresa = mysqli_fetch_assoc($result_empresa)){ ?>
                            <option value="<?php echo $row_empresa['id']; ?>"<?php
                            if(!empty($_SESSION['value_select_empresa'])){
                                if($_SESSION['value_select_empresa'] == $row_empresa['id']){
                                    echo 'selected';
                                    unset($_SESSION['value_select_empresa']);
                                }
                            }
                            if(!empty($row_curriculos['empresa_id'])){
                                if($empresa_id == $row_empresa['id']){
                                    echo 'selected';
                                }
                            }
                            ?> >
                            <?php echo $row_empresa['empresa']; ?></option>
                        <?php } ?>
                    </select>

            <?php if(!empty($row_curriculos['area_id'])){
                $area_id = $row_curriculos['area_id'];
            }?>

                Área de atuação

                    <select class="form-control" name="select_area">
                        <option value="">Selecione</option>
                        <?php
                        $result_area = "SELECT * FROM area";
                        $result_area = mysqli_query($conn, $result_area);
                        while($row_area = mysqli_fetch_assoc($result_area)){ ?>
                            <option value="<?php echo $row_area['id']; ?>"<?php
                            if(!empty($_SESSION['value_select_area'])){
                                if($_SESSION['value_select_area'] == $row_area['id']){
                                    echo 'selected';
                                    unset($_SESSION['value_select_area']);
                                }
                            }
                            if(!empty($row_curriculos['area_id'])){
                                if($area_id == $row_area['id']){
                                    echo 'selected';
                                }
                            }
                            ?> >
                            <?php echo $row_area['area']; ?></option>
                        <?php } ?>
                    </select>

           <?php if(!empty($row_curriculos['cargo_id'])){
                $cargo_id = $row_curriculos['cargo_id'];
            }?>

                Cargo

                    <select class="form-control" name="select_cargo">
                        <option value="">Selecione</option>
                        <?php
                        $result_cargo = "SELECT * FROM cargo";
                        $result_cargo = mysqli_query($conn, $result_cargo);
                        while($row_cargo = mysqli_fetch_assoc($result_cargo)){ ?>
                            <option value="<?php echo $row_cargo['id']; ?>"<?php
                            if(!empty($_SESSION['value_select_cargo'])){
                                if($_SESSION['value_select_cargo'] == $row_cargo['id']){
                                    echo 'selected';
                                    unset($_SESSION['value_select_cargo']);
                                }
                            }
                            if(!empty($row_curriculos['cargo_id'])){
                                if($cargo_id == $row_cargo['id']){
                                    echo 'selected';
                                }
                            }
                            ?> >
                            <?php echo $row_cargo['cargo']; ?></option>
                        <?php } ?>
                    </select>

            <?php if(!empty($row_curriculos['situacao_id'])){
                $situacao_id = $row_curriculos['situacao_id'];
            }?>

                Sit. do curriculo

                    <select class="form-control" name="select_situacao_curriculo">
                        <option value="">Selecione</option>
                        <?php
                        $result_situacao = "SELECT * FROM situacao_curriculo";
                        $result_situacao = mysqli_query($conn, $result_situacao);

                        while($row_situacao_curriculo = mysqli_fetch_assoc($result_situacao)){ ?>

                            <option value="<?php echo $row_situacao_curriculo['id']; ?>"
                            <?php
                            if(!empty($_SESSION['value_select_situacao_curriculo'])){
                                if($_SESSION['value_select_situacao_curriculo'] == $row_situacao['id']){
                                    echo 'selected';
                                    unset($_SESSION['value_select_situacao_curriculo']);
                                }
                            }
                            if(!empty($row_curriculos['situacao_id'])){
                                if($situacao_id == $row_situacao_curriculo['id']){
                                    echo 'selected';
                                }
                            }
                            ?> >
                            <?php echo $row_situacao_curriculo['nome']; ?></option>
                        <?php } ?>
                    </select>

                                    <button type="submit" style=" margin-left: 20px; margin-top: 19px;" class="btn btn-primary">Pesquisar</button>

                            </form>

                            ID
                            Data de cadastro
                            Nome
                            E-mail
                            Vaga de interesse
                            Empresa
                            Área de atuação
                            Cargo
                            Telefone
                            Obs. do candidato
                            Situação Curriculo
                            Observação do R.H.

                        <?php while($row_curriculos = mysqli_fetch_assoc($resultado_curriculos)){?>

                                <?php echo $row_curriculos["id"]; ?>
                                <?php echo date('d/m/Y H:i:s',strtotime($row_curriculos["created"])); ?>
                                <?php echo $row_curriculos["nome"]; ?>
                                <?php echo $row_curriculos["email"]; ?>
                                <?php echo $row_curriculos["vaga"]; ?>
                                <?php
                $situacao_atual = $row_curriculos['empresa_id'];
                $result_empresa = "SELECT * FROM empresa WHERE id = '$situacao_atual'";
                $result_empresa = mysqli_query($conn, $result_empresa);
                $row_empresa = mysqli_fetch_assoc($result_empresa);
                echo $row_empresa['empresa']; ?>

                                <?php
                $situacao_atual = $row_curriculos['area_id'];
                $result_area = "SELECT * FROM area WHERE id = '$situacao_atual'";
                $result_area = mysqli_query($conn, $result_area);
                $row_area = mysqli_fetch_assoc($result_area);
                echo $row_area['area']; ?>

                                <?php
                $situacao_atual = $row_curriculos['cargo_id'];
                $result_cargo = "SELECT * FROM cargo WHERE id = '$situacao_atual'";
                $result_cargo = mysqli_query($conn, $result_cargo);
                $row_cargo = mysqli_fetch_assoc($result_cargo);
                echo $row_cargo['cargo']; ?>

                                <?php echo $row_curriculos["telefone"]; ?>
                                <?php echo $row_curriculos["mensagem"]; ?>
                                <?php
                $situacao_atual = $row_curriculos['situacao_id'];
                $result_situacao = "SELECT * FROM situacao_curriculo WHERE id = '$situacao_atual'";
                $result_situacao = mysqli_query($conn, $result_situacao);
                $row_situacao_curriculo = mysqli_fetch_assoc($result_situacao);
                echo $row_situacao_curriculo['nome']; ?>
                                <?php echo $row_curriculos["mensagem_rh"]; ?>

                                    <a href="administrativo.php?link=17&id=<?php echo $row_curriculos["id"]; ?>">
                                        <button type="button" class="btn btn-xs btn-primary">
                                            Visualizar
                                        </button>

                                    <a href="administrativo.php?link=18&id=<?php echo $row_curriculos["id"]; ?>">
                                        <button type="button" class="btn btn-xs btn-warning">
                                            Editar
                                        </button>

                                    <a href="administrativo/processa/adm_apagar_curriculo.php?id=<?php echo $row_curriculos["id"]; ?>">
                                        <button type="button" class="btn btn-xs btn-danger">
                                            Apagar
                                        </button>

                        <?php } ?>

                <?php
                    //Verificar a pagina anterior e posterior
                    $pagina_anterior = $pagina - 1;
                    $pagina_posterior = $pagina + 1;
                ?>

                            <?php
                            if($pagina_anterior != 0){ ?>
                                <a href="pesquisar.php?pagina=<?php echo $pagina_anterior; ?>&pesquisar=<?php echo $valor_pesquisar; ?>" aria-label="Previous">
                                    «

                            <?php }else{ ?>
                                «
                        <?php }  ?>

                        <?php
                        //Apresentar a paginacao
                        for($i = 1; $i < $num_pagina + 1; $i++){ ?>

<a href="pesquisar.php?pagina=<?php echo $i; ?>&pesquisar=<?php echo $valor_pesquisar; ?>"><?php echo $i; ?>

                        <?php } ?>

                            <?php
                            if($pagina_posterior <= $num_pagina){ ?>
                                <a href="pesquisar.php?pagina=<?php echo $pagina_posterior; ?>&pesquisar=<?php echo $valor_pesquisar; ?>" aria-label="Previous">
                                    »

                            <?php }else{ ?>
                                »
                        <?php }  ?>

Se eu utilizo o campo "nome" onde ele faz a pesquisa até vai, funciona, mas removendo o OR empresa LIKE '%$valor_pesquisa' - funciona correto somente pelo nome.
$result_curriculos = "SELECT * FROM curriculos WHERE nome LIKE '%$valor_pesquisar%' limit $incio, $quantidade_pg";

O que eu preciso é que se o usuario realize um filtro, por empresa ou cargo ou area ele filtre  resultado,
Para isso eu tenho as tabelas assim:
tabela curriculos
Colunas id | nome | E-mail | Telefone | area_id | cargo_id | empresa_id | situacao_id
tabela area
colunas id | area
tabela cargo
colunas id | cargo
Tabela empresa
colunas id | empresa
tabela situacao_curriculo
colunas id | nome

Bom acho que mostrei tudo que estou fazendo
E ainda deixo uma imagem para ilustrar como esta sendo feito.
Espero que alguém possa me ajudar, pois estou a uns dias nisso para finalizar um projetinho.
Obrigado
Segue imagem
https://screenshot.net/pt/0my0qsg

EDITADO ------------------------------
Fiz o que o amigo Jeferson sugeriu, mas não rolou.
Quando coloco "SELECT * FROM curriculos as c, empresa as emp WHERE c.nome LIKE '%".$valor_pesquisar."%' OR emp.empresa LIKE '%".$valor_pesquisar."%'";
Talvez a sintaxe esteja errada, vou melhorar o raciocínio para ver se os amigos ajudam.
Na tabela curriculos eu tenho a coluna empresa_id, nela busca somente o ID da empresa referente a tabela empresa exemplo empresa_id=3
Na tabela empresa tem a coluna ID | empresa - exemplo id=3 | empresa=SULMINAS
Então nessa tabela EMPRESA tenho assim:
ID=1 | empresa=NORTEMINAS
ID=2 | empresa=LESTEMINAS
ID=3 | empresa=SULMINAS
Na tabela CURRICULOS tenho assim:
ID=1 | NOME=FULANO | firstname.lastname@example.com | area_id=1 | empresa_id=3
Então na pesquisa tenho um select option que puxa a tabela curriculos e quando informa a coluna empresa_id - puxa o ID da tabela empresa, informando o nome da empresa
<select class="form-control" name="select_empresa">
                    <option value="">Selecione</option>
                    <?php
                    $result_empresa = "SELECT * FROM empresa";
                    $result_empresa = mysqli_query($conn, $result_empresa);
                    while($row_empresa = mysqli_fetch_assoc($result_empresa)){ ?>
                        <option value="<?php echo $row_empresa['id']; ?>"<?php
                        if(!empty($_SESSION['value_select_empresa'])){
                            if($_SESSION['value_select_empresa'] == $row_empresa['id']){
                                echo 'selected';
                                unset($_SESSION['value_select_empresa']);
                            }
                        }
                        if(!empty($row_curriculos['empresa_id'])){
                            if($empresa_id == $row_empresa['id']){
                                echo 'selected';
                            }
                        }
                        ?> >
                        <?php echo $row_empresa['empresa']; ?></option>
                    <?php } ?>
                </select>

Então ao selecionar no select option a empresa=SULMINAS e clicar no botão pesquisar ele deve exibir somente o resultado com o ID | nome | email | area | empresa

Quando clicar no pesquisar exibir somente a lista de usuário que selecionou a empresa no select do cadastro.

Eu tenho essas duas Query
//As que selecionam todos os curriculos da tabela
$result_curriculos = "SELECT * FROM curriculos WHERE nome LIKE '%$valor_pesquisar%'";
//se ela é usada assim e eu uso o campo nome TEXT (digitando qualquer letra, a pesquisa filtra o nome).

e tenho essas query's para exibir o resultado da pesquisa
$result_curriculos = "SELECT * FROM curriculos WHERE nome LIKE '%$valor_pesquisar%' limit $incio, $quantidade_pg";
$resultado_curriculos = mysqli_query($conn, $result_curriculos);
$total_curriculos = mysqli_num_rows($resultado_curriculos);

Preciso entender da sintaxe que puxe o valor do select option da tabela CURRICULOS, coluna EMPRESA - puxando o ID e o resultado seja somente daquele ID.
E preciso entender a sintaxe que exiba o resultado da pesquisa.
Gostaria que a pesquisa trabalhe-se independente de como realiza a seleção no Select Option - tipo se ele utilizar somente a empresa para exibir o resultado, ou a combinação empresa e cargo. tipo quero resultados da empresa SULMINAS no cargo de ANALISTA, ou somente exibir o resultado da EMPRESA ou somente do CARGO.

Acho que agora a explicação está bem mais completo.
Ajudaria muito de uma solução
Agradeço a atenção de todos.
Comment: pelo exposto acima a coluna nome está na tabela curriculo e a coluna empresa na tabela empresa, portanto sua query não está correta.
Comment: no caso o like seria por nome ou id da empresa?
Comment: @LeoCaracciolo realmente o nome da empresa e o nome do candidato estão em tabelas diferentes. Alterei a Query na resposta, creio que agora resolva o problema.
Comment: hehehe, se mysqli fosse mais esperto, nesses casos, ele deveria procurar  o campo faltante nessa tabela em outras tabelas e sugerir o select no warning
Comment: Não somos um fórum, não coloque a **resposta** no corpo da **pergunta** e não é necessário o titulo RESOLVIDO e muito menos o uso desnecessário de CapsLock, simplesmente marque a resposta que acha correta, veja o tour e entenda o site primeiro http://pt.stackoverflow.com/tour
Answer: Considerando que você está buscando pelo Nome do Candidato ou Nome da Empresa, acredito que seja um pequeno erro de sintaxe na sua Query. Além de não estar fazendo a junção das tabelas já que nome do candidato está em uma tabela diferente de empresa. Tente:
 "SELECT * FROM curriculos as c, empresa as emp
  WHERE c.nome LIKE '%".$valor_pesquisar."%' OR emp.empresa LIKE '%".$valor_pesquisar."%'";

Comment: testei a query igual a dele - WHERE CustomerName LIKE '%Drachenblut Delikatessend%' OR ContactName LIKE '%Guillermo Fernández';  - em https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_like e funciona
Comment: Sim, ela funciona.. o problema é a sintaxe como o amigo Jeferson Leonardo comentou.

Pesquisa de Filtro


Factorization of matrices over GF$(2)$

Question: Suppose $A\in \mathbb{F}_2^{n\times n}$ is full rank non-symmetric matrix. Then, can we write $A=BB^T$ for some full-rank $B$? I know there exists a Cholesky factorization, but its not clear if that factorization works over $\mathbb{F}_2$.
Edit 1: Sorry for misleading, but I am more interested in the case where $A$ is not symmetric and has a zero diagonal!
Comment: I'm a bit curious as to what you want to do with this :-) I used the Seroussi&Lempel algorithm as a step in a decoding algorithm I cooked up for the self-dual McGuire-Calderbank code of length $32$ over $\Bbb{Z}_4$. The algorithm wasn't too hot, so I never bothered publishing it in forms other than a symposium abstract. It earned me a trip to Southern Italy though :-)
Answer: The matrix $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ in $\mathbb{F}_2^{2 \times 2}$ does not have a decomposition as $BB^T$ for any $B \in \mathbb{F}_2^{2 \times 2}$. Otherwise, the would exist $a,b,c,d \in \mathbb{F}_2$ such that
$$a^2+b^2=c^2+d^2=0,~ac+bd=1.$$
However, it follows from $a^2+b^2=c^2+d^2=0$ that $a=b$ and $c=d$ and so $ac+bd=ac+ac=0$.
Comment: If we enforce $A$ is non-symmetric with zero diagonal, could you come up with counterexamples for a factorization of the form $A=BB^T$? I'll accept your answer after that. Thanks!
Comment: symmetric with 0 diagonals needs one more column per the reference in the accepted answer. So $B=((1,0,1),(0,1,1))$ will work for your example. Relaxing the symmetric part is not possible since $BB^T$ is symmetric.
Answer: The relevant theory is explained in two articles, the first is actually enough. Also, I want to point out that the author is better known for inventing the Lempel-Ziv data compression algorithm used in zip-files and such. The second article (probably behind IEEE paywall for most of you) was more relevant to me, and was the route I found my way to the first article.

A. Lempel, Matrix factorization over $GF(2)$ and trace-orthogonal bases of $GF(2)$, SIAM J. Comput., vol. 4, pp. 175-186, June 1975.
G. Seroussi, A. Lempel, Maximum Likelihood Decoding of Certain Reed-Muller Codes, IEEE TRANSACTIONS ON INFORMATION THEORY, VOL. IT-29, NO. 3, MAY 1983.

The main result is the following.
Theorem. Let $A$ be a symmetric $n\times n$ matrix over $GF(2)$. Let $\rho(A)$ denote its rank, and let $\delta(A)=1$, if $A_{ii}=0$ for all $i$, and $\delta(A)=0$
otherwise. Let $B$ be an $n\times m$ matrix such that $BB^T=A$. Then
$$
m\ge \rho(A)+\delta(A).\qquad(*)
$$
Furthermore, there exists a matrix $B$ with $\rho(A)+\delta(A)$ columns such that $A=BB^T$, so the bound $(*)$ is tight in this sense.
Sketching the reasoning why we should expect that additive $\delta(A)$-term (explaining some of the ingredients in Lempel's result):

The rank of $A=BB^T$ is bounded from above by the rank of $B$, because the rows of $BB^T$ are linear combinations of the rows of $B^T$.
The matrix entry $A_{ij}$ is the inner product of rows $i$ and $j$ of $B$. So if $A_{ii}=0$ for $i$, all the rows of $B$ must have an even number of ones.
The subspace of $GF(2)^\ell$ consisting of all the vectors with an even number of ones has dimension $\ell-1$.
In particular if $A$ has full rank $n$ and all the diagonal elements are zero, then any matrix $B$ such that $A=BB^T$ must have at least $n+1$ columns.
Conversely, if $A$ has at least a single non-zero entry on the diagonal, then we can find a matching $B$ with $\rho(A)$ columns. This is the harder direction in Lempel's paper. It is not too difficult though. The idea is to do simple similarity transformations to the bilinear symmetric form determined by $A$. Mostly you get away with elementary transformations, but an extra trick is needed when making use of a non-zero diagonal entry.

The conclusion is that we can write a full rank symmetric matrix $A$ in the prescribed form (with a square matrix $B$) if and only if $A$ has a non-zero diagonal entry.
Comment: @wwjohnsmith Any matrix of the form $BB^T$ is automatically symmetric. Recall that the transpose of a product is the product of transposes in reverse order: $(CD)^T=D^TC^T$ for all matrices $C,D$ of compatible types. Consequently $(BB^T)^T=(B^T)^TB^T=BB^T$, so $BB^T$ is equal to its own transpose irrespective of what $B$ was.
Comment: Dear @Jyrki, Thanks for the detailed response. I did come across the paper by Lempel, but it seems like I am more interested in the case where $A$ is non-symmetric and has a zero diagonal. Do you have any refernces for this case?

Factorization of matrices over GF$(2)$


Exploratory factor analysis with 5 positively loaded and 1 negatively loaded factor. How to interpret?

Question: I conducted an EFA with Maximum Likelihood and Direct Oblimin Rotation. Following the Kaiser Eigenvalue 1 rule, I identified 6 latent factors. 5 of them are positively loaded, while 1 is not.
Here an example to make it a little less abstract:
Let's say I measure the trust in Jesus (just an example). I got multiple factors like predisposition, how strongly the person believes into heaven, how much time the person spends with studying the bible, how much money the person donates to the church etc pp. Now for 5 of the latent factors the structure makes total sense, but one latent factor (whose items also have positive cross-loadings over 0,2) only has negative loadings. Can I say sth about this last latent factor and it's relation to the other latent factors?
How do I interpret this one negative factor in relation to the other ones?
All that I found so far was aiming at how to interpret negative and positive loadings within one factor, not between multiple factors.
Comment: I think @mdewey 's comment was tongue-in-cheek and alluding to the fact that EFA interpretations are arbitrary.
Comment: I'm not sure your question can be answered without qualitative context. Maybe provide a description of your observed variables and possibly a table of their loadings?
Comment: @AlvaroFuentes I added an example, hope its clearer now. I can also add a screenshot of the structure matrix if that helps
Comment: Does multiplying them by minus one help?
Comment: So you have many variables that measure different religious behaviors. You ran a factor analysis and found that, following Kaiser's rule, those variables can be summarized by 6 factors. 5 of those factors have only positive loadings (5 latent characteristics of your individuals that drove them to report higher religiosity). The remaining factor has only negative loadings (a latent characteristic that drove them to report lower religiosity). Now it's your job to think up what that 1 characteristic might be, the same way you will try to give names to the other 5.
Comment: @AlvaroFuentes so, that factor would be 'tendency for atheism' in this example? I am just confused because some items have significant loadings for both 'belief in jesus' and 'tendency for atheism'
Comment: @mdewey this would help for sure, but I dont think it would be appropriate since I already made sure that every item is coded in the right (same) direction
Comment: There is no contradiction. You would expect the item "studying the bible" to have a positive loading for the factor "trust in Jesus" and a negative loading for the factor "tendency for atheism".
Comment: Haha, I see. Thank you very much @AlvaroFuentes I think I understood it now!
Answer: The signs on factors are essentially arbitrary. If you were measuring (say) political orientation you could get one that has negative loadings and measures (say) conservatism or positive loadings measuring liberalism.
A tiny change in the data can flip all the signs on a factor.
The negative sign just changes the interpretation from
"People who are high on this factor are high on this latent variable" to "People who are high on this factor are low on this latent variable".
Comment: thanks for the answer. So assuming the positive loaded factor is liberalism, while the negative is conservatism. What am I now doing with items that have significant loadings for liberal and conservative?


Ios 7 compitible app crashes on launch. Why?

Question: I have just launched app,with IOS deplyment Target to  ios 6 and latest IOS SDK 8.1.
 Now App runs fine on ios 8 but i have some users with ios 7, saying app crashes on launch. I have checked all code ,nothing used which was deprecated. please guide me here.
I checked back in 2013 when IOS 7 launched, Many Apps was crashing, is this problem still persist?? How do i check on device with IOS 7, I did downgrade my phone's beta to IOS 7 but my app was working fine in my phone. Cant figure problem. Please some one help me.
Comment: This is a very broad question. How are we to know why your app is crashing without knowing (in great detail) the code or situations in which the crashes occur? Next time, please try and provide a more focused query with code samples.
Comment: I dont have any crash report , not showing on itune, but user told me that he tried fon 2 different device one iphone 4s and iphone 5, but on both app crashed on launch..
Comment: I come across crittercism.com just now, going to integrate it in new version but what can cause this issue
Comment: Hi I m using appirater for app review, where "[Appirater appLaunched];" on this its showing deprecated, but i have added this on last version and app was crashing before that.
Comment: on Itune it only says ..."Too few reports have been submitted for a report to be shown."
Comment: If you cant reproduce it, you cant fix it
Answer: I have some advice for you problem.

You should use  https://try.crashlytics.com/ or https://mint.splunk.com/
Please update Project | iOS | Deployment Target 8.1
Please update Targets | Deployment Target 7.1

Question. when you compile your project . have you see any attention ?
good luck
Comment: No attention showing , only some on nslog statement.
Comment: why to set project and deployment Targets different?? Is it not true that Target settings over write Project settings?? Will that make any difference?? Please explain. Really appreciate your time.
Comment: App gets suspended when low memory occurs.. Can this cause app to crash on launch?? Please help me clarify here
Comment: Hello Friend, actually you should use breakpoint and check everything step by step, every method and every function.
Comment: yes but only problem is I don't have phone with IOS 7. I tried roll back to old IOS but it still runs fine on my phone with old IOS 7.
Comment: Ok. my advice is download virtual mac o.s x such as mountain lion. And you will have iOS 7 . or yoku can buy old iphone 4 device from eBay. Don't focus downgrade.
Comment: I just want to know that "App gets suspended when low memory occurs.. Can this cause any app to crash on launch??" Can it be reason in general??


Minimize $\sum_{i=1}^{n}a_i^2\sigma_i^2$ subject to $\sum_{i=1}^{n}a_i=1$

Question: I am having a little issue with this problem. I know that if we were to only have $$\sum_{i=1}^{n}a_i^2$$ subject to $$\sum_{i=1}^{n}a_i=1$$ then we can use Lagrange multipliers, and we get $a_i=1/n$ for all $i$.
In this case we have that the $\sigma_{i}$'s are known constants, but they are not necessarily equal to each other, so I cannot really do anything else with those.
I know the answer is $$a_i=\frac{(1/\sigma_i^2)}{\sum_{i=1}^{n}(1/\sigma_i^2)}$$
but I have tried to use this and have not had any luck thus far.
Any help given is much appreciated. Thank you.
Comment: Another simple way is to use Cauchy-Schwarz inequality:

$$\sum_{i=1}^n (a_i\sigma_i)^2 \sum_{i=1}^n \frac{1}{\sigma_i^2} \ge \left(\sum_{i=1}^n a_i\sigma_i\times\frac{1}{\sigma_i}\right)^2$$

Equality holds iff $a_i\sigma_i= k/\sigma_i$ for some $k(\ne 0)$. You can find $k$ from the restriction $\sum\limits_{i=1}^n a_i=1$.
Answer: Solve the first-order condition
$$\frac{\partial}{\partial a_j} \left(\sum_{i=1}^n a_i^2 \sigma_i^2 - \lambda(\sum_{i=1}^n a_i -1) \right) = 0$$
to obtain $$a_j = \frac{\lambda}{2\sigma_j^2}$$
Next solve for the multiplier $\lambda$ using the constraint $\sum_{i=1}^n a_i = 1$.
Comment: short and sweet, as it should be.
Comment: Thanks a lot RRL.
Comment: @StivenG: You're welcome.


How to cancel the term "sotto voce"

Question: I have always understood the term sotto voce to be more of an expressive instruction - a feeling - than a specific dynamic mark.  It's used to mark a passage (often in vocal music, but it's not limited to vocal music) that should be performed very quietly.  But it doesn't seem to take the place of a proper dynamic mark.
In this Brahms piece, for instance, it is paired with p to tell the performer not only to play at a soft dynamic, but also to play in an understated manner; with restraint.
Brahms Symphony 3

Now here is the question:  Assuming that a regular dynamic marking is also required, how does one "cancel" the sotto voce instruction?  Is there an opposite term like arco/pizz. that is expected?  Does the instruction disappear with the next dynamic marking to appear?  How should one cancel the indication of sotto voce?
If the context is important, the passage is soprano/alto in a choral piece, and the dynamic is indeed piano.
As a possible answer, a further search brought me to this bassoon moment in the same piece.  Is mezza voce (translated from Italian: half/medium voice) perhaps Brahms' answer?  EDIT: Aaron beat me to it!
Comment: Note, btw, the _f_ at rehearsal B. We can probably presume that there's no "forte sotto voce." I guess it's a fair question, how does "_p e sotto voce_" compare to "_pp_", e.g. after reh. A? For what it's worth, I think Brahms threw it in at the beginning and not thereafter because, as you say, it's an expressive instruction, and once the movement "gets going" the bassist presumably knows when to be subdued.
Answer: There are three "voce"s for music:

sotto voce: hushed voice (lit. "under the voice")
mezza voce: half voice
piena voce: full voice
Comment: Would a dynamic mark, especially at mp or above, cancel it out also?
Comment: @ToddWilcox Anything mp or lower, I would have to give it real interpretive thought; but, mf or higher I would interpret as a cancellation. I'm not aware of any convention.

How to cancel the term "sotto voce"


Javascript alert not working on button click

Question: I have typed in the javascript just as you have but on a separate file linked through the HTML file. The button shows up however I am not getting any alert when it is clicked. My code is as follows:
Javascript(index.js):
document.getElementById("myButton").onclick = function () {
    alert("Hi");
}

HTML:
<!DOCTYPE html>

<title>Javascript is Fun!(When it works)</title>

<button id="myButton">Click</button>

Anyone know why my button is not working? It seems to me all my code is in order unless I am overlooking something.
Answer: Your code is being executed prior to the element it refers to existing in the page. Move the JavaScript to the end of the document or wrap it in a window.onload function.
window.onload = function () {
    document.getElementById("myButton").onclick = function () {
        alert("Hi");
    }
}

jsFiddle example
Answer: You need to wait for the document to be constructed before you can reference elements in it.
Put your script tag in body, just before the end. This will ensure that the document is there when the script runs.
Or, you can wrap your js in a load listener like this
window.addEventListener("load", function(){
  //...your stuff here
})

Comment: Have my vote for making the code easier to coexist with. (`addEventListener` adds an event listener on top of any previously set ones, whereas `.onload` cancels any previously set `onload` event.). Here is what I mean: http://jsfiddle.net/v6ao73ap/
Comment: Thanks @blex! Definitely a much more sustainable approach to event handling!
Answer: You should not put
 before , because when the browser is trying to register the event, the <button> is not loaded already. So when you take a look at the control panel, you would get something like TypeError: document.getElementById(...) is null.
The right version might be
<!DOCTYPE html>

<title>Javascript is Fun!(When it works)</title>

<button id="myButton">Click</button>

Answer: Sometimes you should put script code below the button
<button id="myButton">Click</button>

document.getElementById("myButton").onclick = function () {
    alert("Hi");
}

Answer: first thing is you haven't included jquery in your code, change your HTML to this
!DOCTYPE html>

<title>Javascript is Fun!(When it works)</title>

<button id="myButton">Click</button>

and your index.js to
 $(document).ready(function(){
    $('#myButton').click(function(){
        alert("Hi");
    });
    });

this worked for me hope this work for you too


Restore missing main menu

Question: I have managed to hide/lose the main menu bar - drupal 7.x.
overview of work I was doing:

I added mediaelements.js
I began adding videos to the site with add content
I attempted to make a Videos menu in the main menu

It was during some point of this process that I noticed the main menu bar was missing.
I have searched SE for solutions similar to  mine and have not had success with what was presented as solutions (having main menu in block and appearance settings toggled).
I have, so far, tried to go through each setting and compared them against settings in dev environment.
Are their other troubleshooting tasks I should follow which may point to a resolution?
thank you
Comment: @josh - clearing the site cache did not restore.  I have not attempted suggestion 2, I will look up how to do this and give it a try.  Videos are uploaded/self hosted. -- thank you
Comment: 1. Does clearing all your site's cache restore it? 2. Have you replaced the core toolbar with a contributed module? (admin_menu) 3. How are you rendering videos? From YT/uploaded yourself Reasons that are likely to make it disappear are weird cache behaviour and missing closing html element tags.
Answer: resolved - I had restricted the main menu block to specific content types. Removing the restriction restored main menu block across all content types.

Restore missing main menu


The Abelian Finite Group Category has not arbitrary products.

Question: I want to prove that. I know an object of that category is: $\mathbb{Z}_{p_{1}}\times...\times\mathbb{Z}_{p_{n}}$, where $p_{i}$ are primes. But I'm stuck there.
Thanks
Answer: You can simply say that if $A,B$ are two finite abelian groups, then $\operatorname{Hom}(A,B)$ is a finite set.
However, the functor $A\mapsto\prod_{i\in\mathbb{N}}\operatorname{Hom}(A,\mathbb{Z}/p\mathbb{Z})$ does not always take a finite group to a finite set. Hence, it cannot be represented by a finite group. (An object representing this functor is by definition the product $\prod_{i\in\mathbb{N}}\mathbb{Z}/p\mathbb{Z}$).
Comment: Can you put me an example of this product is not always a finite set?
Comment: Take $A=\mathbb{Z}/p\mathbb{Z}$, so this is isomorphic to $\prod_{i\in\mathbb{N}}\mathbb{Z}/p\mathbb{Z}$.


Montando dados dinamicos com JavaScript

Question: Estou trabalhando em um aplicativo hibrido, estou utilizando HTML5 com Java Script, a minha ideia é quando o camarada fazer o login com a conta dele, o aplicativo vai no servidor e busca tudo que é relacionado a aquela pessoa e já monta em uma listview todas as salas daquele camarada.
function PesquisaTurma(){
EscreverConsole(console, "Pesquisando turmas");
var read_transition = db.transaction("tbl_TURMAS", "readonly"),
    store = read_transition.objectStore("tbl_TURMAS"),
    rows = store.openCursor(),
    flag,
    HTMLNovo,
    index,
    $wrapper;
rows.onsuccess = function(evt){
    var cursor = evt.target.result;
    if(cursor)
    {
    var bd =    db.transaction("tbl_PESSOA_TURMA").objectStore("tbl_PESSOA_TURMA");

        index = bd.index("COD_IDENT_TURMA");
        index.get(cursor.value.COD_IDENT_TURMA).onsuccess = function(event) {
            $wrapper = document.querySelector('#turma'),

                // Pega a string do conteúdo atual
                var HTMLTemporario = $wrapper.innerHTML;

            flag = event.target.result.FLG_IDENT_PESSO;

            // Novo HTML que será inserido
            HTMLNovo = '<ion-item class="item widget btn_ESCOLHE_TURMA item-avatar" data-uib="ionic/list_item_avatar" data-ver="0">'+'<input id="w_codigo" type="hidden" value="'+cursor.value.COD_IDENT_TURMA+'"/>'+''+'
'+cursor.value.TXT_NOMEX_TURMA+'
'+ '
'+((flag == "M") ? "Você é aluno." : "Você é professor")+'
'+'</ion-item>';

            HTMLNovo = HTMLNovo + HTMLTemporario;

            // Coloca a nova string(que é o HTML) no DOM
            $wrapper.innerHTML = HTMLNovo;

            //HTMLNovo = HTMLNovo + HTMLTemporario;

            // Coloca a nova string(que é o HTML) no DOM
           $('#turmas').append($wrapper);

        };
        cursor.continue();
    }
}
EscreverConsole(console, "Turmas pesquisadas com sucesso.");
};

Este código funciona legal, porem acontece 2 erros com ele, mais não é de programação.

1º Problema - Quando faço login, chamo esta função, porem ele não coloca as turmas imediatamente no aplicativo, é necessário atualizar a pagina para ela aparecer.
  2º Problema - Se caso faço login duas vezes ele coloca o dobro, e dessa vez ele coloca sem precisar de atualizar a pagina.
Comment: $wrapper.innerHTML aparentemente é o HTMLTemporário, então você não precisa somar com o HTMLNovo e depois atribuir de novo para o $wrapper.innerHTML, compreende ? acho que isso vai resolver seu problema de dobrar.
Comment: Este problema funcionou, porem o outro continua.
Comment: O outro problema não sei exatamente, mas na primeira vez realmente vem alguma coisa no $wrapper.innerHTML ?
Comment: É uma rotina e ela é a seguinte, busco no banco todos os dados, depois rodo uma rotina que salva todo este dados no banco local, após isso faço outro procedimento que busca no banco todas as turmas e monta este listview.
Comment: acredito que após o innerHTML, você vai ter que utilizar o appendChild(), dê uma olhada nesse exemplo: http://jsbin.com/diviyusufe/1/edit?html,js,console
Comment: Olha como eu fiz:                 HTML.innerHTML = HTMLNovo;
                $wrapper.appendChild(HTML);
Comment: legal @Renan Rodrigues, e funcionou o appendChild ? está incluindo as turmas sem precisar a página ? senão o problema é simplesmente no seletor que não é o correto
Comment: @ThiagoFriedman O problema de atualizar assim que faz o login eu consertei, era porque ele estava fazendo processos antes de outros finalizarem, porem agora ao pegar as turmas so vem a ultima, teria como formular uma resposta para min de como fazer ?
Comment: Atualizei meu código como está agora. A ideia é que preciso que ele pegue 1 e vai adicionando embaixo do outros, se tiver 10 aparece as 10.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29155/discussion-between-thiago-friedman-and-renan-rodrigues).
Answer: Bastou eu adicionar um for para que ele carrega-se tudo.
O erro ocorreu pois as turmas estavam na memoria, e quando recarregava ela permanecia apenas uma, fazendo um for, ele carrega todas as turmas de uma so vez.
Segue o código:
                for(i=0; i < cursor.length; i++)
            {
                // Coloca a nova string(que é o HTML) no DOM
                $('#turmas').append($wrapper);
            }

Montando dados dinamicos com JavaScript


How do I force ntfsresize to ignore the backup bootsector?

Question: I cloned one hard drive to another and things are working well. Except for my NTFS volume not taking up the entire partition (due to the older volume being smaller).
Doing this:
sudo ntfsresize -x /dev/sdb3

I get this error:
ERROR: Could not get the old volume parameters from the backup bootsector

How do I fix this?
Comment: Also, I can patch things up on a windows machine if that is easier.
Comment: It's now March 2013, did you find a fix for this?
Answer: In reply to Luciano (StackExchange wouldn't allow me to comment, so I must put this in an own anser) - I had the same problem today and will write here the exact steps for testdisk...

Choose disk (/dev/sda in my case)
Choose Intel
Choose Advanced
Choose with up/down arrows the correct partition and with left/right arrows the Option [Boot]
Choose [Rebuild BS]
Testdisk complains that "Extrapolated boot sector and current boot sector are different." - Choose [Write]
Confirm with Y and Quit

[Edit]
After reboot into Windows-Recovery using "starting-help" (or whatever it is called in English), it said something like "Disk is being repaired, this may take over an hour" - but it was finished after about 20 seconds.
And yay! I can now boot into Windows again, AND the NTFS-filesystem covers the entire partition. So thanks again, Luciano for the excellent suggestion.
Answer: I had a similar problem. I solved it in Windows by using Disk Management (diskmgmt.msc) and growing the partition by 1 MB. This resized the file system to fill the entire partition.
Answer: ntfsresize doesn't seem to have any options to ignore the backup sector. However, that message may indicate that there is something wrong with the filesystem. I suggest that you first run ntfsfix on the partition and then boot Windows and run chkdsk.
Comment: I did both, ntfsfix and chkdisk (including search for bad sectors) - no difference.
Answer: I ended up in this situation after trying to clone an ntfs partition onto an SSD. I didn't use the same starting sector (which is a no-no, as described e.g. here), as I wanted to ensure that everything was aligned to the 4K sector boundaries (whether this worked or not is another story). I initially shrunk the original disk to a smaller size than the target SSD, to ensure it would fit. After copying over the partition successfully with ntfsclone, I tried to expand it as you have done, and got the same error. After this, I did the following:
n.b. Do this at your own risk, as a last resort.

ran testdisk as per the wiki, which involved something along the lines of (sorry this is from memory):

Chose my partition e.g. /dev/sda1
Chose PC/Intel as mbr type
Option analyze. This should show the old boot sector and backup are identical (but as we know they're not).
Option write boot sector. This confusingly gives a warning saying that the boot sector you're going to write does not match what is on the disk.

Reboot. The disk is unbootable.
Reboot using a windows recovery media, loading the recovery console.

Run FSCK /F C: (where C: is your drive) - this finds errors and fixes them

Exit and reboot, and you should find that your disk has been extended to the max size.


Conteúdo renderizado por trás da StatusBar

Question: Estou fazendo um curso onde a tela do app deveria está dessa maneira, com o componente no topo não ultrapassando o limite do layout:

Porém no meu código ficou desse jeito:

Dá para ver até que o ícone foi cortado.
Segue o codigo do App.js, que está igual o do curso.
import React from 'react';
import { View } from 'react-native';

import Topo from './componentes/Topo';
import Texto from './componentes/Texto';
import Cards from './componentes/Cards';

export default function App () {
return (
  <View>
    <Topo />
    <Texto />
    <Cards />
  </View>
);
}

O código do componente (Topo) index.js:
import React from 'react';
import { View, Text, Image } from 'react-native';
import estilo from './estilo'
import churrasco from '../../assets/churrasco.png';

export default function Topo() {
  return (
    <View style={estilo.box}>
      <Image style={estilo.boxIcone} source = { churrasco } />

      <View>
        <Text style={estilo.boxTitulo}>Churrasco em casa</Text>
        <Text style={estilo.boxSubtitulo}>Calculando a comida e a bebida</Text>
      </View>
    </View>
  )
}

Eu acho que talvez possa ser a versão, já que esse curso deve ter um pouquinho de tempo.
Vocês podem me esclarecer por que isso acontece? E qual a solução?
Comment: Alguma resposta te ajudou? Dê uma olhada no [tour] e saiba como aceitar uma resposta.
Answer: No começo de um curso sobre React Native, tive um problema parecido, mesmo seguindo o tutorial a parte de cima ficava cortando, no começo coloquei apenas um marginTop: 20, então percebi que o problema é o StatusBar, acho que em versões anteriores ele já vinha automático, agora você tem que chamar-lo.
Você pode colocar uma marginTop na view:
<View style={estilo.box, {marginTop: 20}}>
      <Image style={estilo.boxIcone} source = { churrasco } />
  <View>
    <Text style={estilo.boxTitulo}>Churrasco em casa</Text>
    <Text style={estilo.boxSubtitulo}>Calculando a comida e a bebida</Text>
  </View>
</View>

OU
Você pode colocar a StatusBar no App.js, aconselho fazer isso: (Lembrar de colocar (<> </>) no inicio e no fim do return)
import React, { useState } from "react";
import { StatusBar } from "react-native";
import Routes from "./src/routes/routes";

export default function App({ navigation }) {
  return (
    <>
      <StatusBar barStyle="light-content" backgroundColor="#3e91e4" />
      <Routes />
    </>
  );
}

Comment: Era o statusbar mesmo, ele realmente não vem automatico como em versões passadas.
Answer: Opa, boa noite. pelo que pude compreender sua dúvida é em relação a ao cabeçalho que corta o seu component, certo? Você pode ocultar o mesmo, mas vale ressaltar que a implementação depende da versão do stack navigator que está usando.
A partir da versão 5 você pode fazer o seguinte:
<Stack.Navigator
 screenOptions={{
   headerShown: false
  }}>
 <Stack.Screen name="route-name" component={ScreenComponent} />
</Stack.Navigator>

Caso fique com dúvida só mandar, que tentarei explicar melhor pra você.
Answer: O problema é que sua tela não está considerando o tamanho da StatusBar.
Por exemplo, quando a StatusBar está com a propriedade translucent definida o aplicativo será renderizado por trás dela, o que pode ser útil em algumas situações, mas é um problema no seu caso.
Para resolver você pode renderizar a <StatusBar /> no componente que lhe convém, porém sem definir a propriedade translucent. Vale ressaltar que mesmo que você renderize a <StatusBar /> em vários componentes, o React Native considerará a última renderizada.
<StatusBar backgroundColor='#fff' barStyle='dark-content' />

Caso esteja utilizando o Expo, utilize o expo-status-bar.
Outra opção é fazer uso da SafeAreaView como root do seu componente ao invés de uma View. O funcionamento é o mesmo da View, porém a SafeAreaView leva em consideração alguns detalhes (como a StatusBar, barras de navegação, tab etc.) e adiciona um padding:
<SafeAreaView>
  {/* componentes */}
</SafeAreaView>

Também existe o react-native-safe-area-context. Caso esteja utilizando o Expo, veja aqui
Note que é preferível utilizar SafeAreaView ao invés de você colocar um estilo manual pois o tamanho da tela disponível varia de acordo com o dispositivo e também OS (Android / iOS).


Model approach for count data with a large range of y values

Question: I am modeling ridership data for specific routes by month over a number of years.  Some routes have as little as about 1000 riders per month while other routes may have over 20,000 riders per month.  I have been looking at different approaches to model this data including a panel data model and a generalized linear data model (poisson family).  However, I have found some information that says you should only use the poisson family when you have a small range in data for the y variable.
Is there a better approach to modeling count data with a large range of y values than Poisson?
Comment: Related:  http://stats.stackexchange.com/questions/7535/strategy-for-deciding-appropriate-model-for-count-data?rq=1
Answer: For count data it is indicated (for reasons of interpretability of estimated parameters) to use a generalized linear model (GLM) with logarithmic link function, see my answer to Goodness of fit and which model to choose linear regression or Poisson
But the distribution family can be choosen in different ways. The reason for the advice you refer, to use Poisson regression when the counts are not to large, is that usually with large counts there is overdispersion, that is, the variance is larger than the variance of the Poisson.
That can be solved in various ways, like using (in R terminology) a quasipoisson family, which can be good enough. Or you can use a negative binomial family. Or, especially if you only wants predictions from the model and not need interpretable parameters, use the traditional way of a usual linear model (that is, identity link function) for the response $\sqrt{Y}$. The square-root transformation is (approximately) variance stabilizing for the Poisson (and quasi-Poisson) families. Look at Why is the square root transformation recommended for count data?   for an explanation of this!
For more about overdispersion, see  Modelling a Poisson distribution with overdispersion    and    Comparing  overdispersion distributions
Comment: Thanks for you input. Just to clarify, When you mean using the square root, do you mean transforming the y by taking it sqrt and then running the model correct?  Running the model with an in transformed y did show extreme over dispersion, but running it with a neg binomial got it just under 1 but real close.
Comment: yes, I mean using as the response in a usual (least squares) linear model $\sqrt{Y}$
Answer: I am a little bit confused by the question (and the answer) as Box and Jenkins introduced ARIMA modelling by analyzing count data i.e. the number of people that flew in a particular month with their airline series. If the time series has small count numbers e.g. 0.0,1,1,0,1,0,2,1,0,0,1,2,1,2,0,1,..... there are definite problems/limitations applying ARIMA modelling procedures. I have been reasonably happy with count data that can average 5 or more as the assumption of continuity is less strained. Truncating/rounding the forecast is a way of providing an answer that must be an integer as integers only exist in the history.
Comment: You are correct in that without covariables we are just using the history of the observed series which may entail means/differences/lagged values/level shifts/time trends/seasonal pulses etc. . With covariables we can possibly incorporate supporting/helping/user-specified predictors. In both cases variance stabilizing transformations be they power transforms/weighted least squares/garch transforms may be needed to generate model errors that have constant variance and a zero constant mean.
Comment: See my most favored/loved response as to when and why http://stats.stackexchange.com/questions/18844/when-and-why-to-take-the-log-of-a-distribution-of-numbers/18852#18852 . He inadvertently thought that a log transformation was appropriate/needed  where http://www.autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/53-capabilities-presentation suggests that a few outliers were simkply needed . Th issue of co-variables is not relevant in my oipnion.
Comment: My idea with mentioning covariables is that without covariables, the parmeters just represent means, or differences of means. Hardly any interpretation problems.  With covariables the interpretation problem with transformation grows.
Comment: Yes. My point is/was is that with covariables, we might be better off transforming fitted values than observations. In practice that is done via a GLM/link function.
Comment: The whole idea is to select the transform based upon the errors NOT the fitted values ALTHOUGH  by chance (or arithmetic !) you might end up with the same answer. The reason for this is that you wish to generate a noise process that is a central ch-square distributed variable so that F tests are meaningful/valid/correct/useful in saluting/criticizing a tentative model . This has nothing whatsoever to do with whether or not a co-variable is in the model
Comment: I think we are misunderstanding each other. My concerns are different than your (not saying that yours are not valid, they are, but I was thinking about something else). My concern was about interpretability of parameter estimates, see my answer here:  http://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353   for an elucidation of that point.
Comment: If interpretability of the parameter estimates is the objective then what you are proposing could be useful but I genuflect to the statistical requirements not the "window dressing". But I do see your point that one often has to sell the solution in terms of  the client's needs to "understand' . Perhaps that is why I have had some non-successful encounters with the real world. As Martin L once said "Here I stand I can do no other"
Comment: The airline data did'nt have covariables (?), yes? So the interpretation problems do not arise.  Still, a square root transformation to stabilize variance could be useful, maybe.  But, of course Box knew very well about variance stabilizing transformations, if he didnt use one he must have had reasons.


What does the 'B' (or bonus) mean on a basketball scoreboard?

Question: I was looking at pictures of scoreboards today, and I noticed that some of them have 'B's on the boards:

The same thing appears on NBA games, often in the broadcast scoreboard as well:

I've never noticed those before. What do they mean?
Answer: That's a bonus marker.
A team who commits 7 fouls gives the other team a bonus - which gives a free throw with every foul from that point on.
The second B on the second image indicate that a team has reached 10 fouls (in HS and college this is the double bonus and means that you shoot 2 foul shots from there forward instead of 1 and 1)


Softlayer API: How to get a VSI's ipv6 info?

Question: I have create a virtual server withing ipv6 address. How can I get the IPv6 information by sl api?  I want the information likes:
Answer: take a look to this code to get the details of the bare metal servers:
here an example for VM
<code>"""
Get Virtual Guest details. It retrieves virtual guest information.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getObject
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getVirtualGuests

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <email@example.com>
"""
# So we can talk to the SoftLayer API:
import SoftLayer

# For nice debug output:
from pprint import pprint as pp

# Set your SoftLayer API username and key.

# Your SoftLayer API username and key.
API_USERNAME = 'set me'
API_KEY = 'set me'

# Set the server id that you wish to get details.
# Call the getVirtualGuests method from SoftLayer_Account
serverId = 5464742

# Retrieve the wanted server information using a mask
mask = 'operatingSystem.passwords, networkComponents, datacenter, notes'

# Make a connection to the Virtual_Guest service.
client = SoftLayer.Client(
    username=API_USERNAME,
    api_key=API_KEY
)

try:
    # Make the call to retrieve the server details.
    virtualGuestDetails = client['Virtual_Guest'].getObject(id=serverId,
                                                    mask=mask)
    pp(virtualGuestDetails)

except SoftLayer.SoftLayerAPIError as e:
        pp('Unable to get the Virtual Guest infomrmation faultCode=%s, faultString=%s'
            % (e.faultCode, e.faultString))
</code>
this one is for bare metal
<code>"""
Get Bare Metal details.

Retrieve a list of bare metal servers in the account and print
a report with server hostname, domain, login info, network, CPU,
and RAM details.
This script makes a single call to the getHardware() method in the
SoftLayer_Account API service  and uses an object mask to retrieve
related information.
See below for more details.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Server/

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <firstname.lastname@example.com>
"""
import SoftLayer

"""
Your SoftLayer API username and key.

Generate an API key at the SoftLayer Customer Portal:
https://manage.softlayer.com/Administrative/apiKeychain
"""
USERNAME = 'set me'
API_KEY = 'set me'

"""
Add an object mask to retrieve our hardwares' related items such as its
operating system, hardware components, and network components. Object masks
can retrieve any information related to your object. See
# http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Server
# for a list of the relational properties you can retrieve along with hardware.
"""
objectMask = 'processors, processorCount, memory, memoryCount, networkComponents, primaryIpAddress, operatingSystem.passwords'

# Declare a new API service object.
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
accountService = client['SoftLayer_Account']

try:
    # Make the call to retrieve our bare metal servers.
    hardwareList = accountService.getHardware(mask=objectMask)
except SoftLayer.SoftLayerAPIError as e:
    """
    If there was an error returned from the SoftLayer API then bomb out with the
    error message.
    """
    print("Unable to retrieve the bare metal list. "
          % (e.faultCode, e.faultString))

for hardware in hardwareList:
    passwords = {}
    passwords['username'] = "no username"
    passwords['password'] = "no password"
    if len(hardware['operatingSystem']['passwords']) >= 1:
        passwords = hardware['operatingSystem']['passwords'][0]
    networks = hardware['networkComponents']
    """
    Go through the hardware's network components to get it's public and
    private network ports. Save MAC addresses.
    """
    publicMacAddress = 'not found'
    privateMacAddress = 'not found'
    for network in networks:
        """
        SoftLayer uses eth0 on the private network and eth1 on the public
        network.
        """
        if network['name'] == 'eth' and network['port'] == 0:
            privateMacAddress = network['macAddress']
        elif network['name'] == 'eth' and network['port'] == 1:
            publicMacAddress = network['macAddress']

    """
    Hardware can only have like processors in them, so use the first item in
    the processors array to get the type of processor in the server.
    """
    processorType = hardware['processors'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['capacity'] +\
                    hardware['processors'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['units'] + " " +\
                    hardware['processors'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['description']

    # Treat memory the same way we did processors.
    memoryType = hardware['memory'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['capacity'] +\
                 hardware['memory'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['units'] + " " +\
                 hardware['memory'][0]['hardwareComponentModel']['hardwareGenericComponentModel']['description']

    # All done! Print hardware info.
    print("Hostname: " + hardware['hostname'])
    print("Domain: " + hardware['domain'])
    print("Login: " + passwords['username'] + "/" + passwords['password'])
    print("Public IP Address: " + hardware['primaryIpAddress'])
    print("Public MAC Address: " + publicMacAddress)
    print("Private IP Address: " + hardware['privateIpAddress'])
    print("Private MAC Address: " + privateMacAddress)
    print("CPUs: " + str(hardware['processorCount']) + "x " + processorType)
    print("RAM: " + str(hardware['memoryCount']) + "x " + memoryType)
    print(" ")
</code>
Basically you need to use an object mask to get the properties of the server, you can see all the properties in documentation http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Server
Let me know if you have more questions


Allow user to flag only those node that associated to a particular term of a vocabulary?

Question: I have content type  "product" term referenced by Taxonomy "Product category" having terms
-Cook tops
-Heaters
-Chimneys
Now if i flagged nodes associated with term "Cook tops" , after that if i flag node associated with "Heater". I should get a error message.
Actually I am using this flag to show flagged item in BASKET(as done in many shopping site). But i do not want to put a "Cook tops" node with "Heater" nodes.
Comment: Flag hasn't module that can do it. But it's possible programmatically print Flag in node template dependly your taxonomy field value.
Answer: Found these links which solved my question
https://www.drupal.org/node/2235353
https://www.drupal.org/node/952114


OpenLayers Icon className SVG - Change Fill Via CSS?

Question: I'm trying to use CSS classes in openlayers to change an svg fill colour:
eg say in open layers I have
style = new Style({
                image: new Icon({
                    src: styleConfig.image.src,
                    scale: styleConfig.image.scale,
                    offset: [styleConfig.offsetX, styleConfig.offsetY],
                    className: 'icon--blue'
                }),
                zIndex: styleConfig.zIndex
            });

and then I have an SVG like so:
<svg xmlns="http://www.w3.org/2000/svg" width="49" height="44" viewBox="0 0 580 515" class="icon--blue"><circle fill="inherit" cx="475" cy="106.9" r="102.9"/><g class="cat"><circle fill="inherit" cx="475" cy="106.9" r="102.9"/></g></svg>

and some CSS like so:
.icon--blue circle {
fill: #0000ff !important;
}
.icon--blue .cat {
display: none;
}

Try as I might I cannot get the css based fill effect to be applied. I was wondering if this is supported?
Also the hiding of the grouping with the class name of "cat" also doesn't work.
Seeing is OpenLayers is rendering to canvas, debugging this kind of stuff is very difficult.
Comment: For this to work, the fill inside SVG should have `inherit` value.
Comment: Unfortunately that didn't get me there
Comment: Thanks for your reply. Unfortunately that didn't get me there. It doesn't seem like the CSS class is even having any effect. I'd say it is because although className exists, because Features use canvas in OL css classes have no effect
Comment: css applied to the original mage will not be reflected when it is drawn to canvas.  Instead you should use the color option in the OpenLayers icon style as in this example https://openlayers.org/en/latest/examples/icon-color.html
Answer: Start with a Proof of Concept SVG in a JSFiddle or CodePen, to get your SVG and CSS selectors right.
Learn CSS Specificity to understand why the .inner circle below is green and not red;
Most likely no need for fill attribute and hardly ever !important

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
  <circle id="outer" cx="10" cy="10" r="8" />
  <g class="inner">
    <circle cx="10" cy="10" r="4" />
  </g>
  <circle class="hidden" cx="15" cy="15" r="4" />
</svg>


Identifying two points on an algebraic curve

Question: Given a smooth algebraic curve $C$, say projective over an algebraically closed field $k$, is it always possible to identify two distinct closed points $x, y$ on $C$ to produce a curve with a single node?
In more precise terms, does there always exist a nodal curve $C'$ whose normalization is $C$ such that $x, y$ are the points above the node? Thanks in advance!
Comment: A geometric approach would be to embed the curve nondegenerately in $\mathbf P^3$, project away from a general point on the secant line $\overline{xy}$, and then resolve any nodes other than the one you want.  It might take some work to make that rigorous, though.
Answer: The answer is yes. Here is the basic idea. Take a very large degree line bundle $L$ and consider the sections $s$ of $L$ such that $s(x)=s(y)$ for the two given points $x,y$. These sections define a morphism from the curve to a nodal curve identifying just the two points $x,y$ if the degree of $L$ is sufficiently large.
Comment: If degree of $L$ is large, the vector space of sections of $L$ with $s(x)=s(y)$ is codimension one in the space of all sections.
Comment: Thank you. One thing is unclear to me though, and I would appreciate any help: $L$ will set up a projective embedding by the standard Riemann-Roch arguments (for a high enough degree), but how is it ensured that there are enough sections $s$ with $s(x)=s(y)$? Or can we simply take generating sections for $L$ and somehow alter them such that they take identical values on $x$ and $y$?


Does $D_4$ have a verbal subgroup of order 4?

Question: Does $D_4$ have a verbal subgroup of order 4?
How did this question arise:
In the comments $Q_8$ ad $D_4$ were pointed to be a possible counterexample to this question: Is it true, that for any two non-isomorphic finite groups $G$ and $H$ there exists such a group word $w$, that $|V_w(G)| \neq |V_w(H)|$?
However, $Q_8$ does not have a characteristic subgroup of order $4$, whereas $D_4$ has $3$ normal subgroups of order $4$. So, if one of those subgroups happens to be verbal for some group word $w$, then $Q_8$ ad $D_4$ are definitely not a counterexample.
If such $w$ exists, then it is clearly not an identity in $D_4$. Also, $w \neq [x, y]$,  as $D_4' \cong C_2$, $w \neq x$,  as $V_{x^3}(D_4) \cong D_4$, $w \neq x^2$  as $V_{x^2}(D_4) \cong C_2$ and $w \neq x^3$,  as $V_{x^3}(D_4) \cong D_4$.
However, I do not know, how to proceed further.
Comment: Is $Q_8$ the quaternion group of order $8$? That has a few normal subgroups of order $4$.
Comment: @MattSamuel, that was a typo. I meant "characteristic subgroups", when I talked about $Q_8$.
Answer: The answer is apparently no:  none of the three subgroups of $D_4$ of order $4$ are verbal.
Incidentally,  any subgroup of order four in $Q_8$ is normal (since of index $2$).


Lightbox2 doesn't open html content and links

Question: I installed Lightbox2 module and I tried to link an image to a webpage, say google.com, this is my code
<img  src="<?php print $base_url;?>/sites/all/themes/MY-THEME/image/fp/map.jpg">

but it displays nothing in Lightbhox. This is the print screen of the Lightbox using Firebug

as you can see there is nothing in body.
Comment: Look at your browser error console: REFUSED TO DISPLAY IN A FRAME BECAUSE IT SET 'X-FRAME-OPTIONS' TO 'SAMEORIG, ie it is a cross domain restriction. This works: google map
Comment: And probably not of much help, but if you install this [extension](https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe/related) for Chrome it strips away the X-Frame headers. Otherwise just append &output=embed to the url and set the other parameters as needed.
Comment: @J.Reynolds you are right, then what shall I do to link to google? I also added this code `header('X-Frame-Options: GOFORIT');` but didn't work
Answer: This link works to get google search in the ligtbox:
Search

I got it from this post: How to show google.com in an iframe?
Comment: thanks, for google map adding `&output=embed` works as well


Sqlite query using where condition having more than one condition to satisfy

Question: Please find what is wrong here
here _id and chek is the column of my db  i to write a query to search those which has  id =id and check =number
 public Cursor query(int id){
    return myDataBase.query("question", null,"_id = "+id+ "AND " +  "chek ="+number,null, null, null, null);

}

Comment: What exactly is wrong? the query isn't working, or there is an error (if that is what is wrong please also supply a logcat.)
Just based off that, I'd assume you need a space so the query is like

myDataBase.query("question", null,"_id = "+id+ " AND " +  "chek ="+number,null, null, null, null);
Answer: May this help you:
Replace your query with these lines..
public Cursor query(int id){
return myDataBase.query("question", null,"_id = "+id+ " AND " +  "chek ="+number,null, null, null, null);

keep space between the double quotes in And :" And " otherwise the string will be Example: _id=3And check =9
Answer: Firstly check your sql query syntax are right or not
You can use raw query
 String SQL= "select * from question where _id = "+id+ " and chek ="+number+";
    Log.d("SQL::", SQL);
    Cursor cursor = db.rawQuery(SQL, null);

Answer: try
return myDataBase.query("question", null,"_id = "+id+ " AND " +  "chek ="+number,null, null, null, null);

Answer: Replace your query with these lines if not yet solved..
public Cursor query(int id){
return myDataBase.query("question", null,"(_id = "+id+ " AND " +  "chek ="+number+")",null, null, null, null);


Economics SE vs Quant SE?

Question: Probably asked before but anyhoo thought of this from that: English SE vs ELL SE?
Might I break any (site-specific) rule for asking questions here instead of Quant SE? Sure I could get better answers but let's say I don't care about that. Like is there anything on-topic Quant SE that is off-topic in Economics SE?
Answer: If a question is off topic in Economics SE then it will obviously be closed by users/mods.
If the question is not off topic you can ask it here even if it would be better suited at Quant SE, but off topic questions are against our rules.
Comment: @BCLC as long as you are writing your quant question in English, I recommend posting it on English SE! Except if it is about a theoretical scenario/model, then move it to Worldbuilding. You could also accept that some SEs have specialized.
Comment: i mean to ask for an example. what's on-topic in quant SE that isn't here? like what's on-topic in stats SE that isn't in maths SE or in English SE that isn't in ELL SE?
Comment: @BCLC if that's the only question you are asking why is this sentence in your question: "Might I break any (site-specific) rule for asking questions here instead of Quant SE?"
Comment: lol how can a question be on-topic on quant SE but off-topic in economics SE when quantitative finance is finance and when finance is economics? The only thing I can think of is maybe those soft questions or something.

Economics SE vs Quant SE?


Create external tables without the EXTERNAL keyword?

Question: I am using hive for work. When I created some external tables today, I forgot to type the EXTERNAL keyword, and the HiveQL is like:
CREATE TABLE year_2012_main (
    some BIGINT,
    fields BIGINT,
    should BIGINT,
    beee BIGINT,
    here STRING,
    buttt STRING,
    Iveee STRING,
    decide STRING,
    tohide STRING,
    them BIGINT)
    ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ','
    COLLECTION ITEMS TERMINATED BY ' '
    MAP KEYS TERMINATED BY ':'
    STORED AS TEXTFILE location '/data/content/year_2012_main';

Then I tried select count (*) from year_2012_main; , and it worked well.
So, just out of curious, what's the difference with or without EXTERNAL?
Answer: A Hive table that's not external is called a managed table. One of the main differences between an external and a managed table in Hive is that when an external table is dropped, the data associated with it (in your case /data/content/year_2012_main) doesn't get deleted, only the metadata (number of columns, type of columns, terminators, etc.) gets dropped from the Hive metastore. When a managed table gets dropped, both the metadata and data get dropped. I have so far always preferred making tables external because if the schema of my Hive table changes, I can just drop the external table and re-create another external table over the same HDFS data with the new schema. However, most (if not all) of the changes to schema can now be made through ALTER TABLE or similar commands so my recommendation/preference to use external tables over managed ones might be more of a legacy concern than a contemporary one.
You can learn more about the terminologies here.
Comment: Yep I know the differences between external tables and non-external tables. But I created tables using the HiveQL mentioned and then dropped them, but the data files didn't get deleted.


WCF MVC calling stored procedures

Question: I'm developing an MVC3 application for a university project. I am hoping to use WCF as the web service to be able to connect to a remote database, using stored procedures. I don't really have the time to learn Entity Framework at present.
My question is where should the stored procedure names be held? Should the MVC model pass the stored procedure names to the WCF service along with the values, etc or should the model simply call a method within the WCF service, which will hold the stored procedure name and handle that aspect?
Thanks.
Answer:
My question is where should the stored procedure names be held?

In the data access layer which is located in your WCF service project. The ASP.NET MVC 3 application only invokes a method on this service. Remember that an ASP.NET MVC application doesn't know what a database is and even less what a stored procedure is. An ASP.NET MVC application works only with Models, Controllers and Views.
So in your WCF service project you will have a service contract:
[ServiceContract]
public interface IMyService
{
    SomeModel Get(int id);
}

then you could have an implementation in the WCF service that will go and fetch the data wherever it is stored (in your case that would be a SQL database and the way to fetch this data is to invoke a stored procedure):
public class MyService: IMyService
{
    public SomeModel Get(int id)
    {
        // here you can call the stored procedure and return the corresopnding model
        ...
    }
}

Obviously this will tightly couple your service layer with a given data access technology. In order to decouple it you could bring another level of abstraction between the service and the actual data access:
public class MyService: IMyService
{
    private readonly IMyRepository _repository;
    public MyService(IMyRepository repository)
    {
        _repository = repository;
    }

    public SomeModel Get(int id)
    {
        // you could do additional things in the service method
        // like validating the arguments, call data access methods, ...
        return _repository.Get(id);
    }
}

and the actual stored procedure call will be performed in the specific SQL implementation of the repository that will be injected into your service by your DI framework.
In the ASP.NET MVC application you will only consume the WCF service from the strongly typed client proxy that was generated for you when you added the service reference.
Comment: Thanks Darin.  That makes sense.  One other thing if I may.  Can a WCF service only work on primitive types or those types declared within the WCF solution?  For example, if I have a Person class in my MVC app, is there a way to pass a Person object into a WCF method, or would I need to pass in the primitive types?  Thanks.
Comment: @DarrenYoung, no. Define the Person class inside the WCF service project. Then when you import the service definition of this WCF service the Person class will be automatically imported in your ASP.NET MVC application (assuming it appears either as input or output of some of the service operations in your service contracts). The methods and types that intervene in them in the service contract will all be imported in your MVC application.
Comment: Thanks.  I'll do a little reading on the service definitions and such.
Answer: Stored procedure names should be held in a data access layer/library that sits between your WCF service and your actual database. I.e. in the classes whos methods you call within your WCF service to get the data.

WCF MVC calling stored procedures


Wald confidence interval with delta method

Question:
Using the delta method, show that the Wald confidence interval for the logit of a binomial parameter $\pi$ is $$\log \left(\frac{\hat{\pi}}{1-\hat{\pi}} \right) \pm z_{\alpha/2} \sqrt{\frac{1}{n\hat{\pi}(1-\hat{\pi})}}$$ Explain how to use this interval to obtain one for $\pi$ itself.

Since $Y\sim \mathrm{Bin}(n,\pi)$ and $\hat{\pi}=\frac{y}{n}$ then
$$\begin{cases} \operatorname{E}[y]=n\pi\\ \operatorname{Var}(y)=n\pi(1-\pi)\end{cases}\qquad \begin{cases} \operatorname{E}[\hat{\pi}]=\pi\\ \operatorname{Var}(\hat{\pi})=\frac{\pi(1-\pi)}{n} \end{cases}$$
Let $g(\hat{\pi})=\log(\frac{\hat{\pi}}{1-\hat{\pi}})$ then $g'(\hat{\pi})=\frac{1}{\pi(1-\pi)}$
The delta method says that variance of $g(\hat{\pi})$ is
$$\operatorname{Var}(g(\hat{\pi}))=(g'(\hat{\pi}))^2\times \sigma^2(\hat{\pi})$$
$$=\frac{1}{\hat{\pi}^2(1-\hat{\pi})^2}\times\frac{\hat{\pi}(1-\hat{\pi})}{n}=\frac{1}{n\hat{\pi}(1-\hat{\pi})}$$
So
$$\sqrt{n}\left(\log\left(\frac{\hat{\pi}}{1-\hat{\pi}}\right)-\log\left(\frac{\pi}{1-\pi}\right)\right) \overset{D}\rightarrow N\left(0,\frac{1}{\hat{\pi}(1-\hat{\pi})}\right)$$
Finally a Wald confidence interval is
$$\operatorname{E}[g(\hat{\pi})]\pm z_{\alpha/2} \sqrt{\operatorname{Var}(g(\hat{\pi}))}$$
$$\log \left(\frac{\hat{\pi}}{1-\hat{\pi}}\right) \pm z_{\alpha/2} \sqrt{\frac{1}{n\hat{\pi}(1-\hat{\pi})}}$$
Is this right?
Answer: Your final result is ok but there's a little mistake in the procedure. Escentially, $\mathrm{Var}(g(\hat{\pi}))$ is a function of the parameter $\pi$. Only $\widehat{\mathrm{Var}}(g(\hat{\pi}))$, the estimator of this variance, is a function of $\hat{\pi}$, the maximum likelihood estimator of $\pi$.
Finally, to show how to use this interval to obtain one for $\pi$ itself, notice that you have a confidence region, say $R1$ , for $\log(\frac{\pi}{1-\pi})$. Now, you can obtain a second confidence region $R2$ for $\pi$ so that every value of $\pi$ in this region generates a value of $\log(\frac{\pi}{1-\pi})$ that belongs to $R1$.


Sum greater than 1; minimization for non-strict inequalities

Question: I want to show that if $x_k>0$ for $k=1,2,...,n$ and $\sum_{k=1}^n x_k=1$, then $\sum \frac{x_k^2}{y_k}\ge 1$ for any $y_1, y_2,...,y_n>0$ so that $\sum_{k=1}^n y_k=1$.
I tried solving the minimization problem $\min \sum_{k=1}^n \frac{x_k^2}{y_k}$ $s.t. p_k>0, \sum_{k=1}^n p_k=1$. But I'm not sure how to solve such a problem since there are non-strict inequalities in the constraints.
So I am hoping for:
(1) Any pointers as to proving this inequality $\sum \frac{x_k^2}{y_k}\ge 1$ , and
(2) References/tips for a general method to solve such non-strict inequality minimization problems.
Thanks!
Answer: By the Cauchy-Schwarz inequality,
\begin{align*}
1 &= \left(\sum_{k = 1}^n x_k\right)^2 \\
&= \left(\sum_{k = 1}^n \frac {x_k} {\sqrt{y_k}} \sqrt{y_k}\right)^2\\
&\le \left(\sum_{k = 1}^n \frac{x_k^2}{y_k}\right) \cdot \left(\sum_{k = 1}^n y_k\right) \\
\end{align*}
from which the result follows.

The fact that a) the terms can naturally be recognized as squares and b) we have specific information about the sums of non-squared terms together suggested this route. Had the powers not been $2$, then we could perhaps have used something like Holder's inequality.
Comment: Excellent, thanks Mr. Bongers!


General function to color applicable comboxes

Question: I'm running some VBA code in Excel and I made a a combo box that will turn red and set the focus on it when there is no value entered.
 If cmb = "" Then
    cmb.BackColor = vbRed
    lbl.ForeColor = vbRed
    cmb.SetFocus
    Exit Sub

    Else

    cmb.BackColor = vbWhite
   lbl.ForeColor = vbBlack
End If

As I have many combo boxes on my form, I want to build a function or procedure that I can call for any combo box that I want.
Can anyone help?
Answer: Here's a general function that you can pass a ComboBox to:
Function ValidateComboBox(c As ComboBox) As Boolean

    If Len(c.Text) = 0 Then
        c.BackColor = vbRed
        Controls(c.Tag).ForeColor = vbRed    ' Set associated label color, also
        c.SetFocus
        ValidateComboBox = False
    Else
        c.BackColor = vbWhite
        Controls(c.Tag).ForeColor = vbBlack  ' Set associated label color, also
        ValidateComboBox = True
    End If

End Function

You call it like this, for example when the form is submitted:
' [OK] clicked. Submit form...
Private Sub cmdOK_Click()

    If Not ValidateComboBox(ComboBox1) Then Exit Sub
    If Not ValidateComboBox(ComboBox2) Then Exit Sub
    If Not ValidateComboBox(ComboBox3) Then Exit Sub
    ...

End Sub

The tricky part is that you have a label that corresponds to each combo box that needs to be updated as well. You can either design the function to accept both a ComboBox control and a Label control and pass both each time, or you take advantage of the combo box's Tag property, as I've done above. For each combo box, just enter the name of the corresponding Label control into its Tag property using the Properties window in the designer.
For example, if ComboBox1 has a label named Label1, then enter "Label1" (without the quotes) into ComboBox1's Tag property. The routine above will look for the label/control with that name and set its color appropriately as well.
Comment: HI Bud, it worked like a charm, Only thing I dunno why it not when I'm trying to leverage it to the TextBox a so:

Function ValidateTextBox(T As TextBox) As Boolean

  '  If Len(T.Text) = 0 Then
        T.BackColor = vbRed
        Controls(T.Tag).ForeColor = vbRed    ' Set associated label color, also
        T.SetFocus
        ValidateTextBox = False
    Else
        T.BackColor = vbWhite
        Controls(T.Tag).ForeColor = vbBlack  ' Set associated label color, also
        ValidateTextBox = True
    End If
Comment: @Hamdi - It doesn't work with the TextBox? Are you getting an error? Feel free to post a new question and add your code and I can take a look.
Comment: /* Function ValidateTextBox(T As TextBox) As Boolean

    If Len(T.Text) = 0 Then
        T.BackColor = vbRed
        Controls(T.Tag).ForeColor = vbRed    ' Set associated label color, also
        T.SetFocus
        ValidateTextBox = False
    Else
        T.BackColor = vbWhite
        Controls(T.Tag).ForeColor = vbBlack  ' Set associated label color, also
        ValidateTextBox = True
    End If

End Function */
Comment: @ Bond
It highlights the function with a type mismatch error
Comment: Replace `Function ValidateTextBox(T As TextBox) As Boolean` with `Function ValidateTextBox(T As MsForms.TextBox) As Boolean`


Printing coordinates from an array in Android

Question: I'm working on an image processing application that analyzes ECG graph. To do so, I need to detect certain peaks of the graph.
How can I print the "coordinates", "xcoor" and "ycoor" in the user interface? I tried toasting it but it doesn't work. I tried textView but the application force closes.
package com.thesis.results;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;

import com.example.edgedetection.R;

public class MainActivity extends Activity {

    // initialize variables
    static int i = 0;
    static int bl_ = 0; // number of black; pixels in the image
    static int op_ = 0;
    static int Al = 0;
    static int Re = 0;
    static int Gr = 0;
    static int Bl = 0;
    static int Alp = 0;
    static int Red = 0;
    static int Gre = 0;
    static int Blu = 0;
    static int stop = 0;
    static int stopx = 0;
    static int stopy = 1000;
    static int xcoor[];
    static int ycoor[];
    static int width;
    static int height;
    static int RRdistance;
    static double voltage;
    static int peakcoordinates;

    ImageView imageSource, imageAfter;
    Bitmap bitmap_Source;
    ProgressBar progressBar;
    Button process;
    TextView counter;
    TextView coordinates;
    private Handler handler;
    Bitmap afterProcess;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        process = (Button) findViewById(R.id.btn_process);
        imageSource = (ImageView) findViewById(R.id.imageSource);
        imageAfter = (ImageView) findViewById(R.id.imageAfter);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        counter = (TextView) findViewById(R.id.counter);
        coordinates = (TextView) findViewById(R.id.coordinates);

        process.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                bitmap_Source = BitmapFactory.decodeResource(getResources(),
                        R.drawable.test_ideal_graph);
                handler = new Handler();
                StratBackgroundProcess();
            }
        });

    }

    private void StratBackgroundProcess() {

        Runnable runnable = new Runnable() {

            public void run() {
                afterProcess = processingBitmap(bitmap_Source, 0, 0, 0);

                handler.post(new Runnable() {

                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        imageAfter.setImageBitmap(afterProcess);

                        calculatevoltage();
                        //  calculateRRdistance();
                        counter.setText("" + bl_ + "@ (" + stopx + "," + stopy
                                + " " + "and" +
                                ")" + " {" + width + "," + height + " } = "
                                        + voltage + "mV" + " " + "R-R distance:" + " "
                                        + RRdistance);

                        coordinates.setText(" " + xcoor + "," + ycoor + " " );
                    }

                    private void calculatevoltage() {
                        // TODO Auto-generated method stub
                        voltage = ((0.1 * height) * (height - stopy)) / height;
                        // 1.5 mV is the total voltage of the graph, 1 box =
                        // 0.1mV
                    }

                    //private void calculateRRdistance() {
                    // TODO Auto-generated method stub
                    //     RRdistance = stopx1 - stopx;
                    // 1.5 mV is the total voltage of the graph, 1 box =
                    // 0.1mV

                    //   }

                });
            }
        };
        new Thread(runnable).start();
    }

    public static Bitmap processingBitmap(Bitmap src, double red, double green,
            double blue) {
        // image size
        width = src.getWidth();
        height = src.getHeight();
        // create output bitmap
        Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
        // color information
        int A, R, G, B;
        int pixel;
        int flag = 0;

        //array
        int[] trial = new int[width];
        // scan through all pixels

        for (int x = 0; x < width; ++x) {

            flag = 0;

            for (int y = 0; y < height; ++y) {
                // get pixel color
                pixel = src.getPixel(x, y);
                // apply filtering on each channel R, G, B
                Al = Color.alpha(pixel);
                Re = (int) (Color.red(pixel));
                Gr = (int) (Color.green(pixel));
                Bl = (int) (Color.blue(pixel));
                // set new color pixel to output bitmap

                if ((Re == 0) && (Gr == 0) && (Bl == 0) && (flag == 0)) {
                    bmOut.setPixel(x, y, Color.argb(255, 0, 0, 0));
                    flag = 1;
                    trial[x] = y;

                } else
                    bmOut.setPixel(x, y, Color.argb(255, 255, 255, 255));

            }
        }

        //detect all possible peaks

        for (int x = 1; x < width; x++) {
            if (trial[x] < trial[x - 1] && trial[x] < trial[x + 1]) {
                peakcoordinates = src.getPixel(x, trial[x]); //get pixels, how to display? (textview, toast?)
                //Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_LONG).show();
            }

            //detect all R peaks
            for (int y = 1; y > (trial[1]-50); y++ ){

                xcoor[i] = x;
                ycoor[i] = y;
            }
            return bmOut;
        }
        return bmOut;
    }
}

Comment: can you show us more code? is this code in an activity?
Comment: hi, I put my whole java code above. :)
Comment: When I add the line   coordinates.setText(" " + xcoor + "," + ycoor + " " );, the application fails to launch.
Answer: Your application crashes because you're trying to access your Views from a worker thread, which is prohibited in Android. I'd recommend using the AsyncTask class, which runs a certain task on a worker thread and provides methods that run on UI thread, where you can update your Views. Hope this helps.
Comment: Views? Sorry but I am kinda new to Android programming. I am not familiar with Views or AsyncTask. :(
Comment: If you want to update your textview or show a toast message or other updates to the UI, you cannot do it from the Runnable's run method. Check this stackoverflow question: [AsyncTask](http://stackoverflow.com/questions/9671546/asynctask-android-example)
Answer: You can modify your view (something like TextView, ImageView) only in UI thread. Try AsyncTask:
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        process = (Button) findViewById(R.id.btn_process);
        imageSource = (ImageView) findViewById(R.id.imageSource);
        imageAfter = (ImageView) findViewById(R.id.imageAfter);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        counter = (TextView) findViewById(R.id.counter);
        coordinates = (TextView) findViewById(R.id.coordinates);

        process.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                        // TODO Auto-generated method stub
                        bitmap_Source = BitmapFactory.decodeResource(getResources(),
                                        R.drawable.test_ideal_graph);
                        handler = new Handler();
                        new BackgroundTask().execute();
                }
        });

}

private class BackgroundTask extends AsyncTask<String, Long, String> {

    @Override
    protected String doInBackground(String... s) {
        afterProcess = processingBitmap(bitmap_Source, 0, 0, 0);
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        progressBar.setVisibility(View.GONE);
        imageAfter.setImageBitmap(afterProcess);

        calculatevoltage();
        //  calculateRRdistance();
        counter.setText("...");
        coordinates.setText(" " + xcoor + "," + ycoor + " " );
    }
}

Comment: I tried doing this but it still does not launch. What must be in the position of (String... s) ?
Comment: I copied from my old project, but you don't need to change the code. What's the error message now?
Comment: It does not have an error but it fails to launch. I don't understand why and I'm getting frustrated. :((
Comment: Logcat says it can't open keycharmap file.
Comment: Can you send your project to my email? I will check it later.
Comment: Okay, sure. What is your email? :)


$\lim_{x \rightarrow 0} \frac{\sin(x)}{x}$ using $\epsilon - \delta$ definition

Question: So I'm trying to evaluate this limit without using squeeze theorem and doing it by $ \epsilon - \delta$ definition.
Here's my attempt:
$$ \left| \frac{\sin(x)}{x} - 1 \right| \leq \left| \frac{\sin(x)}{x}\right| + |1| \leq \frac{1}{|x|} + 1 $$
Let $\epsilon > 0 $ and $ \delta = \frac{1}{\epsilon}$
$$ |x| < \delta \Rightarrow \frac{1}{|x|} + 1  < \epsilon + 1$$
And I'm stuck here. I also tried $\delta = \frac{1}{\epsilon - 1} $ but that won't work since I'll only proof for $\epsilon > 1$.
Can someone help me? Thanks.
Comment: Your technique is bound to fail. The only thing you're using about sin(x) is that |sin(x)/x)| is less than or equal to 1/x, but 1/x blows up at x = 0 so this bound can't give you that the limit exists (let alone help you compute it). In other words, no algebra trick is going to work if the only thing you use about sin is that it's less than 1, you have to use something deeper about the sin function.
Comment: What are you allowed to use? Are you allowed the Taylor expansion of $\sin$ at $0$? Are you allowed that $\sin(0) = 0$ and that $\frac{\mathrm{d}}{\mathrm{d}x} \sin(x) |_{x = 0} = 1$ and that $\sin$ is differentiable?
Comment: See the answers in http://math.stackexchange.com/questions/285313/prove-lim-x-rightarrow-0-frac-sinxx-1-with-the-epsilon-delta-def?rq=1
Answer: Hint:
Since $\cos\theta<\frac{\sin\theta}{\theta}<1$
$$\bigg|\frac{\sin\theta}{\theta}-1\bigg|<1-\cos\theta$$
and $1-\cos\theta=2\sin^2\frac{\theta}{2}\leqslant\frac{\theta^2}{2}$  hence
$$\bigg|\frac{\sin\theta}{\theta}-1\bigg|\leqslant\frac{\theta^2}{2}$$
Comment: How can I proof the first inequality? I verified numerically that it is valid for $| \theta | < 4.4934... $ but I failed to proof this.   Despite that I believe I did the exercise, choosing $\delta = \sqrt{2 \epsilon} $.


Gold paint this year used in the NFL

Question: Does anyone know for sure (and could possibly give a source) as to why the NFL this year is using gold paint for the 50-yard markers?
I assume this is somehow related to an anniversary, since it is the 50th Superbowl, but I haven't been able to verify it, and I hadn't actually heard any commentator say it.
Thanks.
Answer: Super Bowl 50 is exactly the reason for it.  Here's a source that also mentions some of the other things (much gold-related) that the NFL is doing to commemorate the milestone:
http://www.cbssports.com/nfl/eye-on-football/25120528/nfl-going-gold-in-2015-to-celebrate-super-bowl-50-5-things-to-know
There was even a mini-controversy recently about the Oakland Raiders not painting their 50 yard line gold:
http://www.sbnation.com/2015/9/22/9377843/raiders-50-yard-line-gold-rebellion-49ers
Comment: Very nice answer.  I did notice this weekend, actually, that the branding in the broadcast had the SB trophy with a gold 50 in the background.

Gold paint this year used in the NFL