Ao concatenar no LINQ me retorna erro

Question:
Fiz essa LINQ. Na concatenação entre DDD e numero do telefone, o qual eu chamo de telefone1 está dando pau.
var agendamento = (
    from pdv in db.T_PDV
    from tarefa in db.T_TarefaParceiro.Where(trf => trf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
    from parceiro in db.T_OsParceiro.Where(prf => prf.IDTarefaParceiro == tarefa.IDTarefaParceiro)
    from acao in db.T_Acao.Where(ac => ac.IDAcao == tarefa.IDAcao).DefaultIfEmpty()
    from proxima in db.T_ProximaAcao.Where(pxm => pxm.IDAcao == acao.IDAcao).DefaultIfEmpty()
    from info in db.T_InfoClientePdv.Where(inf => inf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
    from cliente in db.T_Cliente.Where(clie => clie.IDCliente == info.IDCliente).DefaultIfEmpty()
    from usuariopdv in db.T_UsuarioPDV.Where(usu => usu.IDPDV == pdv.IDPdv)
    from usuario in db.T_Usuario.Where(us => us.IDUsuario == usuariopdv.IDUsuario)

    where pdv.CNPJ == _agendamento.Cnpj //&& parceiro.NumOs == _agendamento.Os

    orderby parceiro.DataVisita descending

    select new
    {
     pdv.CNPJ,
     pdv.DataCadastro,
     cliente.RazaoSocial,
     acao.Acao,
     proxima.ProximaAcao,
     parceiro.IDOsParceiro,
     parceiro.NumOs,
     parceiro.DataVisita,
     parceiro.DataAgendamento,
     parceiro.Tecnico,
     usuario.Nome,
     telefone1 = "(" + usuario.DDD + ")" + usuario.Telefone
    })
    .ToList()
    .FirstOrDefault();

O erro que está dando é o seguinte:

Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
Comment: pnet qual os tipos do DDD e Telefone?
Comment: int e string, acho que é isso, certo? Mas numa concatenação ele não faz o cast automático?
Comment: Sim, os nomes dos tipos são `int` e `string`. Sim, o cast dos tipos primitivos para string é automático. Não é necessário o `.ToString()` nesse caso. Veja a correção que fiz na minha resposta. Deve te ajudar.
Answer: Coloque assim:
var agendamento = (
    from pdv in db.T_PDV
    from tarefa in db.T_TarefaParceiro.Where(trf => trf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
    from parceiro in db.T_OsParceiro.Where(prf => prf.IDTarefaParceiro == tarefa.IDTarefaParceiro)
    from acao in db.T_Acao.Where(ac => ac.IDAcao == tarefa.IDAcao).DefaultIfEmpty()
    from proxima in db.T_ProximaAcao.Where(pxm => pxm.IDAcao == acao.IDAcao).DefaultIfEmpty()
    from info in db.T_InfoClientePdv.Where(inf => inf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
    from cliente in db.T_Cliente.Where(clie => clie.IDCliente == info.IDCliente).DefaultIfEmpty()
    from usuariopdv in db.T_UsuarioPDV.Where(usu => usu.IDPDV == pdv.IDPdv)
    from usuario in db.T_Usuario.Where(us => us.IDUsuario == usuariopdv.IDUsuario)

    where pdv.CNPJ == _agendamento.Cnpj //&& parceiro.NumOs == _agendamento.Os

    orderby parceiro.DataVisita descending

    select new
    {
     pdv.CNPJ,
     pdv.DataCadastro,
     cliente.RazaoSocial,
     acao.Acao,
     proxima.ProximaAcao,
     parceiro.IDOsParceiro,
     parceiro.NumOs,
     parceiro.DataVisita,
     parceiro.DataAgendamento,
     parceiro.Tecnico,
     usuario.Nome,
     telefone1 = "(" + usuario.DDD ?? "00" + ")" + usuario.Telefone
    })
    .FirstOrDefault();

Obs: Não precisa dar um ToList() e depois um FirstOrDefault(), já coloque o FirstOrDefault() que vai resolver o problema, além de ser desnecessário o ToList() vai trazer tudo da sua tabela e o FirstOrDefault() pega a primeira ocorrência na memória, isso acarreta performace.
Comment: Ele diz que não reconhece o ToString() no LinqToEntities
Comment: Acho que eu vou concatenar no jquery e resolve esse problema. Sempre que eu tento concatenar ou renomear um campo como eu tentei fazer, dá pau
Comment: Eu sei, foi o que eu fiz e continua dando erro. Concatenando no jquery é mais fácil. Sempre q tento no LINQ dá erro, sempre. Nunca consegui fazer, renomear campos como eu fiz, criar um Alias
Comment: Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
Answer: Pode ser que o seu problema seja com o a variável usuario
Mude:
telefone1 = "(" + usuario.DDD + ")" + usuario.Telefone

Para:
telefone1 = usuario == null ? "não informado" : "(" + usuario.DDD + ")" + usuario.Telefone

Ao concatenar no LINQ me retorna erro


O meu calendário só exibe o primeiro compromisso agendado de cada dia

Question: Montei um calendário com agenda em PHP + MySQL , o mesmo já esta em 80% do desenvolvimento.
Mas, estou com um problema, tipo se eu cadastro em evento para o dia 20/07, esse compromisso é exibido normalmente no calendário. Se eu marco outro compromisso para o mesmo dia, o calendário só exibe o primeiro compromisso agendado. Mas eu queria que fosse exibido todos os compromissos do dia.
Segue o código completo do mesmo.

<?php

 $idUsuario = ($_SESSION['UsuarioID']);

 $mes=date('m');
 $ano=date('Y');

 if($mes == 1)
 {
 $qtdDiasMes=31;
 $nomeMesMes="Janeiro";
 }
 if($mes == 2)
 {
 $qtdDiasMes=28;
 $nomeMes="Fevereiro";
 }
 if($mes == 3)
 {
 $qtdDiasMes=31;
 $nomeMes="Março";
 }
 if($mes == 4)
 {
 $qtdDiasMes=30;
 $nomeMes="Abril";
 }
 if($mes == 5)
 {
 $qtdDiasMes=31;
 $nomeMes="Maio";
 }
 if($mes == 6)
 {
 $qtdDiasMes=30;
 $nomeMes="Junho";
 }
 if($mes == 7)
 {
 $qtdDiasMes=31;
 $nomeMes="Julho";
 }
 if($mes == 8)
 {
 $qtdDiasMes=31;
 $nomeMes="Agosto";
 }
 if($mes == 9)
 {
 $qtdDiasMes=30;
 $nomeMes="Setembro";
 }
 if($mes == 10)
 {
 $qtdDiasMes=31;
 $nomeMes="Outubro";
 }
 if($mes == 11)
 {
 $qtdDiasMes=30;
 $nomeMes="Novembro";
 }
 if($mes == 12)
 {
 $qtdDiasMes=31;
 $nomeMes="Dezembro";
 }
?>

                <button type="button" class="btn btn-success btn-default">Novo Compromisso</button>

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

                                        Cadastro de novo compromisso

                                        <form class="form-horizontal" method="POST" action="<?php $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data" id="addEvent" autocomplete="off">

                                                            Data do evento

                                                                    <input type="date" class="form-control" id="txtData"  name="txtData">
                                                                    <input type="hidden" class="form-control" id="txtIdUsuario"  name="txtIdUsuario" value="<?=$idUsuario;?>">

                                                            Assunto

                                                                    <input type="text" class="form-control" id="txtAssunto"  name="txtAssunto">

                                                            Lembrete

                                                                    <textarea id="txtMensagem" name="txtMensagem"> </textarea>

                                            <button type="submit" name="btnSubmit" class="btn btn-success btn-default">Salvar</button>
                                            <button type="button" class="btn default" data-dismiss="modal">Fechar</button>

                                            </form>

                                Minha Agenda

                                            <?php echo $nomeMes . " de " . $ano;  ?>

                                            Dom
                                            Seg
                                            Ter
                                            Qua
                                            Qui
                                            Sex
                                            Sab

        <?php

                echo "
";

                        for($i=1; $i<=$qtdDiasMes;$i++)
                            {
                                $diadasemana = date("w",mktime(0,0,0,$mes,$i,$ano));
                                    $cont = 0;
                                    if($i == 1)
                                        {
                                            while($cont < $diadasemana)
                                                {
                                                    echo "   	";
                                                    $cont++;
                                                }
                                        }

                                        if($i >=1 and $i <= 9){
                                            $dataCalendar = $ano.'-'.$mes.'-'.'0'.$i;  //pega o Ano  , o mes  , e o dia que recebe o valor de $i
                                        } else{
                                            $dataCalendar = $ano.'-'.$mes.'-'.$i;  //pega o Ano  , o mes  , e o dia que recebe o valor de $i
                                        }

                                            $sql = mysql_query("SELECT * FROM tblAgenda where data = '$dataCalendar' and idUsuario = $idUsuario");
                                            $row = mysql_fetch_array ($sql);

                                                $assunto = $row['assunto'];
                                                $idModal = $row['id'];

                            echo " "
                                    .$i;
                                    // dia da semana

                            echo"

                                            ".$assunto."

                                    ";

                                echo    "	";

                                if($diadasemana == 6)
                                    {
                                        echo "
";

                                        echo "
";
                                    }
                            }

                echo "
";
?>

<?php

    // parte que faz os Modals aparecerem.

    $sql2 = mysql_query("SELECT * FROM tblAgenda where idUsuario = $idUsuario");
    while($row2 = mysql_fetch_array ($sql2))
    {
        $assuntoModal = $row2['assunto'];
        $mensagem = $row2['mensagem'];
        $idEvent = $row2['id'];
        echo '

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

'.$assuntoModal.'

                                '.$mensagem.'

                                            <button type="button" class="btn default" data-dismiss="modal">Fechar</button>

';
    }

if(isset($_POST['btnSubmit'])){

$idUsuario = $_POST['txtIdUsuario'];
$data = $_POST['txtData'];
$assunto = $_POST['txtAssunto'];
$mensagem = $_POST['txtMensagem'];

            $sqlCadastro = "INSERT INTO tblAgenda
            (idUsuario,assunto,mensagem,data) VALUES ($idUsuario,'$assunto','$mensagem','$data')";

            mysql_query($sqlCadastro) or die (mysql_error() . 'Por favor , verifique se todos os dados estão preenchidos corretamente');

            if(mysql_affected_rows() == 1) //verifica se foi afetada alguma linha, nesse caso inserida alguma linha
                    {
                        echo"   ";
                    }

                else
                {
                    echo"";
                }
}

A minha tabela tblAgenda:
id  int(11) AUTO_INCREMENT  Primária
idUsuario   int(11)
assunto varchar(200)    latin1_swedish_ci
mensagem    varchar(999)    latin1_swedish_ci
data    date

O código esta bem bacana e da para alguém usar se quiser, pois está de fácil entendimento. Sempre procurei na internet mas nunca tinha achado algo do tipo.
Se alguém me puder ajudar a melhorar o código vai me ajudar e ajudar muitos outros.
Comment: Gosto de usar esse cara aqui quando trabalho com calendários: http://fullcalendar.io/. Ele integra bem com o backend utilizando Ajax.
Comment: Na edição do AP: "Mostrei a um amigo , e foi só adcionar um while entre os   que exibe o assunto . Fica aqui o código para quem quiser um calendário com agenda em php + mysql . Que puder ajudar a melhorar o código ,via ajudar \o/ "
Comment: Henrique eu vou reverter a sua pergunta. Coloque o código com as alterações como resposta. Aqui fazemos perguntas e respostas. E depois marcamos a resposta certa.
Answer: @Jorge B.
Desculpe, nao sabia .
Segue o código com o problema resolvido.

<?php

 $idUsuario = ($_SESSION['UsuarioID']);

 $mes=date('m');
 $ano=date('Y');

 if($mes == 1)
 {
 $qtdDiasMes=31;
 $nomeMesMes="Janeiro";
 }
 if($mes == 2)
 {
 $qtdDiasMes=28;
 $nomeMes="Fevereiro";
 }
 if($mes == 3)
 {
 $qtdDiasMes=31;
 $nomeMes="Março";
 }
 if($mes == 4)
 {
 $qtdDiasMes=30;
 $nomeMes="Abril";
 }
 if($mes == 5)
 {
 $qtdDiasMes=31;
 $nomeMes="Maio";
 }
 if($mes == 6)
 {
 $qtdDiasMes=30;
 $nomeMes="Junho";
 }
 if($mes == 7)
 {
 $qtdDiasMes=31;
 $nomeMes="Julho";
 }
 if($mes == 8)
 {
 $qtdDiasMes=31;
 $nomeMes="Agosto";
 }
 if($mes == 9)
 {
 $qtdDiasMes=30;
 $nomeMes="Setembro";
 }
 if($mes == 10)
 {
 $qtdDiasMes=31;
 $nomeMes="Outubro";
 }
 if($mes == 11)
 {
 $qtdDiasMes=30;
 $nomeMes="Novembro";
 }
 if($mes == 12)
 {
 $qtdDiasMes=31;
 $nomeMes="Dezembro";
 }
?>

                <button type="button" class="btn btn-success btn-default">Novo Compromisso</button>

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

                                        Cadastro de novo compromisso

                                        <form class="form-horizontal" method="POST" action="<?php $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data" id="addEvent" autocomplete="off">

                                                            Data do evento

                                                                    <input type="date" class="form-control" id="txtData"  name="txtData" required />
                                                                    <input type="hidden" class="form-control" id="txtIdUsuario"  name="txtIdUsuario" value="<?=$idUsuario;?>">

                                                            Assunto

                                                                    <select class="form-control" id="txtAssunto"  name="txtAssunto" required>
                                                                        <option value="Retorno">Retorno</option>
                                                                        <option value="atualizar dados">Atualizar dados de venda</option>
                                                                    </select>

                                                            Lembrete

                                                                    <textarea id="txtMensagem" name="txtMensagem" required> </textarea>

                                            <button type="submit" name="btnSubmit" class="btn btn-success btn-default">Salvar</button>
                                            <button type="button" class="btn default" data-dismiss="modal">Fechar</button>

                                            </form>

                                Minha Agenda

                                            <?php echo $nomeMes . " de " . $ano;  ?>

                                            Dom
                                            Seg
                                            Ter
                                            Qua
                                            Qui
                                            Sex
                                            Sab

        <?php

                echo "
";

                        for($i=1; $i<=$qtdDiasMes;$i++)
                            {
                                $diadasemana = date("w",mktime(0,0,0,$mes,$i,$ano));
                                    $cont = 0;
                                    if($i == 1)
                                        {
                                            while($cont < $diadasemana)
                                                {
                                                    echo "   	";
                                                    $cont++;
                                                }
                                        }

                                        if($i >=1 and $i <= 9){
                                            $dataCalendar = $ano.'-'.$mes.'-'.'0'.$i;  //pega o Ano  , o mes  , e o dia que recebe o valor de $i
                                        } else{
                                            $dataCalendar = $ano.'-'.$mes.'-'.$i;  //pega o Ano  , o mes  , e o dia que recebe o valor de $i
                                        }

                                        $sql = mysql_query("SELECT * FROM tblAgenda where data = '$dataCalendar' and idUsuario = $idUsuario");

                            echo " ";

                                    echo $i;    // dia da semana

                                    while($row = mysql_fetch_array ($sql)){

                                        $assunto = $row['assunto'];
                                        $idModal = $row['id'];

                            echo"

";

                                                    if($assunto != null){
                                                     echo "<button class='btn btn-success'>".$assunto."</button>";
                                                    } else{
                                                        echo $assunto;
                                                    }

                                        echo  "

                                        ";
                                    }

                                echo    "	";

                                if($diadasemana == 6)
                                    {
                                        echo "
";

                                        echo "
";
                                    }
                            }

                echo "
";
?>

<?php

    // parte que faz os Modals aparecerem.

    $sql2 = mysql_query("SELECT * FROM tblAgenda where idUsuario = $idUsuario");
    while($row2 = mysql_fetch_array ($sql2))
    {
        $assuntoModal = $row2['assunto'];
        $mensagem = $row2['mensagem'];
        $idEvent = $row2['id'];
        echo '

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

'.$assuntoModal.'

                                '.$mensagem.'

                                            <button type="button" class="btn default" data-dismiss="modal">Fechar</button>

';
    }

if(isset($_POST['btnSubmit'])){

$idUsuario = $_POST['txtIdUsuario'];
$data = $_POST['txtData'];
$assunto = $_POST['txtAssunto'];
$mensagem = $_POST['txtMensagem'];

            $sqlCadastro = "INSERT INTO tblAgenda
            (idUsuario,assunto,mensagem,data) VALUES ($idUsuario,'$assunto','$mensagem','$data')";

            mysql_query($sqlCadastro) or die (mysql_error() . 'Por favor , verifique se todos os dados estão preenchidos corretamente');

            if(mysql_affected_rows() == 1) //verifica se foi afetada alguma linha, nesse caso inserida alguma linha
                    {
                        echo"   ";
                    }

                else
                {
                    echo"";
                }
}


R regular expression scientific notation

Question: I'm pretty sure what I'm looking for is a Regular expression in R for reading scientific notion.  Below is what I have done and the specifics. I very much appreciate any help.
I have a text file where some numbers are scientific notation and some are just decimals or integers. I'm trying to read them into R using regular expressions. I wrote a program to do this, and I was successful as long as the numbers did not use scientific notation or negative numbers.
The program I wrote was
getBig <-function(fileName,rows,columns)
{

  dat <-readChar(fileName, file.info(fileName)$size)
 gregexpr('[0-9][/.0-9]+',dat,perl = TRUE)

  s <- regmatches(dat,m)
  s <- s[[1]]
  s<-s[-1] #the first element is the list size
  S <- matrix(s,ncol=rows,nrow=columns)
  S<- t(S)
  return(S)
}

I tried to modify the regular expression to include negative numbers and scientific notation by modifying the above program with the below regular expression but was not successful. Does anyone have an idea where I am going wrong? Any help is appreciated, and I have the example file format below as well.
 m <- gregexpr(' [-+]?[0-9]*(/.?[0-9]*([eE][-+]?[0-9]?))?',dat,perl = TRUE)

[-+]?    + or - optional
[0-9]*  a digit 0-9 at most 0 times
(       start non optional block
/.?     optinal
[0-9]*   match 0 or more times
( start another block
[eE][-+]?  e or E  + or - optional
[0-9]* a digit 0-9 1 or more times
)?)?  close blocks matching optional
The file format below  is  rows,columns
where  (rowN,rowN,rowN) refers to columns 1-3 for the Nth row.
i.e
[3,1]    ((1,1,-1),-2.542611418857958448210085379141884323299379672715620518130686999531487002844642281770330354890802745e-05,8.586192002176000052697976968885158408090751670240233300961472896241959822732337130019333683974778635e-05))

Comment: The last line is a line from your file? What's your desired output?
Comment: http://www.regular-expressions.info/floatingpoint.html
Comment: Pretty sure this question has an answer on SO. Did you do any searching?
Answer: Based on Regex for numbers on scientific notation? the following could work in R:
Regex for scientific notation only:
only_sci_notation_numbers_regex <- "^(-?[0-9]*)\\.?[0-9]+[eE]?[-\\+]?[0-9]+$"

Regex for scientific notation and non-scientific notation decimals or integers:
 all_numbers_regex <- "^(-?[0-9]*)((\\.?[0-9]+[eE]?[-\\+]?[0-9]+)|(\\.[0-9]+))*$"

Example of some of the patterns this matches and doesn't match:
 examples_match <- c(
  "0", "1", "1.5", "0.2", "-0", "-1", "-1.5", "-0.2", ".1", "-.1",
  "1.05E+10", "1.05e+10","-1.05E+10", "-1.05e+10", "1.05E-10", "1.05e-10","-1.05E-10", "-1.05e-10",
  ".1e5", ".1E5", "-.1e5", "-.1E5")

  examples_not_match <- c("1.", "1.e5", "1e5.")

  # matches only numbers in scientific notation (so not examples 1-10)
  lapply(examples_match, function(x) grepl(only_sci_notation_numbers_regex, x))

  # matches numbers in scientific and non-scientific notation
  lapply(examples_match, function(x) grepl(all_numbers_regex, x))

  # doesn't match mis-formatted numbers
  lapply(examples_not_match, function(x) grepl(only_sci_notation_numbers_regex, x))
  lapply(examples_not_match, function(x) grepl(all_numbers_regex, x))

These regular expressions assume that the full string represents your number. If you want to match a scientific / non-scientific number that constitutes only part of a string (e.g. to extract it from a longer string via stringr::str_extract), you'd have to remove the ^ in the beginning and the $ in the end of the respective expression.
Comment: These regexes aren't that great. They think `.0+0` and `4-4` are numbers.


Existe um laço de repetição por trás do código de um CTE?

Question: Estou quebrando a cabeça para entender como um comando tão simples pode gerar valores de 1 até o 100.
Há um laço de repetição por trás de um CTE? Pois no código abaixo existe um WHERE e não um WHILE.
WITH CTE_EXEMPLO AS
(
SELECT 1 AS QNT
UNION ALL
SELECT QNT + 1 FROM CTE_EXEMPLO WHERE QNT < 100
)

SELECT * FROM CTE_EXEMPLO

Comment: Completando a resposta do @Maniero, sempre lembre de pesquisar sobre qual banco de dados você está aplicando a CTE. Cada *engine* de cada banco trabalha de uma forma e o desempenho pode variar muito podendo, em alguns casos, não ser a melhor saída utilizar CTE's.
Comment: @DouglasVieira O código que postou é um exemplo de CTE recursiva.
Answer: Não é só o CTE, é todo o SQL. SQL é uma linguagem (não de programação como alguns acham) declarativa, ou seja, você diz o que quer e é problema do engine que está por trás dela resolver isso da melhor forma que ele puder. Então meio que ele interpreta o que seu código deseja e manda o computador executar, ao contrário da maioria das linguagens de programação tradicionais que são imperativas o código diz mais exatamente o que fazer em vez do que deseja.
Só deixando claro que códigos mais imperativos podem se tornar um pouco declarativos, desde uma simples abstração até sintaxes e abstrações mais fortes que realmente mudam a forma de fazer por completo.
Então de certa forma tem um laço sim, mas bem de certa forma, porque a forma como executa é problema do engine e se pensar bem, o conceito de laço já é abstrato, um computador não entende isso, então existe uma repetição de execução, como ocorre o tempo todo em tudo o que executa e você nem está percebendo. De alguma forma isso será interpretado e executado através de uma repetição bastante complexa.
O SELECT simples já fará um "laço" de alguma forma na maioria dos casos (o primeiro é um que não fará isto, não tem vários dados para avaliar). Este CTE em si não tem laço algum, o que está nele é que tem.
Por isso que eu digo para as pessoas aprenderem como o computador funciona, com profundidade, e depois vai subindo as abstrações em cima dele, isto dá uma força muito grande pra programar bem. Eu não acredito em programadores que não sabem isso, mesmo alguns experientes e que são considerados bons por muitos, se não souber isso eu garanto que são supervalorizados, pelo menos mais do que deveriam.
Comment: Neste caso eu devo estudar o engine do SQL Server?
Comment: Não sei, não conheço sua necessidade.
Comment: Só queria entender de ponta a ponta como esse comando é executado.
Comment: Tem que começar pelos fundamentos da computação, não tem atalhos, caso contrário aprenderá mais ou menos e servirá para nada, ou até piorará porque criará um monte de mitos por entender tudo pela metade.


Por que preciso relançar a exceção mesmo depois de tratar ela?

Question: Em uma explicação de Java de um canal no Youtube diz que precisamos relançar a exceção no throw e como se fosse uma nova tentativa de criação do arquivo se algo desse errado no código abaixo, por exemplo uma restrição de criar arquivo no sistema operacional. Eu fiquei mais em dúvida do porquê ele lançou aquele throw e.

Quando ele lança a exceção no throw e, ele está lançando o método criar arquivo de novo?

Por que precisa lançar ela de novo para tentar criar um novo arquivo caso algo de errado?

E porque quando eu lanço esse throw e o método pede para eu declarar na assinatura o throws IOException mesmo tratando a exceção com try e catch?

package academy.devdojo.maratona.javacore.Oexception.exception.test;

import java.io.File;
import java.io.IOException;

public class ExceptionTest02 {
    public static void main(String[] args) {
        criarNovoArquivo();
        System.out.println("Criou arquivo");

    }

    public static void criarNovoArquivo() throws IOException {
        File file = new File("arquivo\\teste.txt");
        try{
            file.createNewFile();

        }catch(IOException e){
            e.printStackTrace();
            throw e;
      }

    }

}

Comment: No seu caso, não há uma nova tentativa de criar o arquivo. Se `createNewFile` lançar um `IOException`, o `catch` só imprime detalhes da exceção e a relança. E no método `main` não há qualquer tratamento desta exceção. Não dá pra saber se o curso explicou pela metade ou vc que ainda não viu tudo, porque só com isso não dá pra avaliar nada. Aliás, tem certeza que o código é esse mesmo? [**Porque ele nem sequer compila**](https://ideone.com/s30Ux1). Para compilar, o `main` precisaria ter um `try`/`catch` também (ou então ele mesmo ter um `throws`). Enfim...
Comment: E só pra constar que são 2 coisas diferentes: uma é o `try`/`catch`, que pega a exceção que pode ocorrer em `file.createNewFile()`. Outra é o `throws`, que é necessário porque indica que o método pode lançar uma exceção (já que dentro dele tem um `throw`). Basicamente, `throw e` está relançando a mesma exceção que o `catch` capturou. É como se ele só estivesse "passando pra frente".
Comment: E só pra terminar, `createNewFile()` retorna um *boolean* indicando se conseguiu criar o arquivo ou se ele já existia: *Returns: `true` if the named file does not exist and was successfully created; `false` if the named file already exists*, então um código completo verificaria isso pra saber se o arquivo foi de fato criado ou se já existia. A exceção é para verificar se outra situação ocorreu (por exemplo, usuário não tem permissão, disco cheio, etc)
Comment: @Maniero A documentação diz que retorna `false` se já existir um arquivo com o mesmo nome. Então eu entendo que para todos os outros casos, lança exceção
Comment: @hkotsubo se tiver um problema de permissão por exemplo, ele nem retorna nada, a exceção é que é lançada, certo? Em que casos poderia não ter sido criado sem lançar a exceção? ou seja, quando o arquivo não é criado por uma situação não excepcional? Não é esquisito ter as duas situações?
Answer: É bem, simples, não precisa. Isso é um erro muito comum. Alguém fez errado (ou fez certo em algum caso muito específico) e os outros copiaram. Foi de cópia em cópia, até que praticamente virou verdade.
É o mesmo processo de fake news de política. Vai se espalhando tanto que fica difícil convencer as pessoas do contrário.
Por isso que tudo, mas tudo mesmo, que você não sabe porque está sendo usado, não use. Aprenda a usar corretamente em todos os sentidos para depois usar. Agora está fazendo o certo, questionou para ver se isso tem necessidade mesmo.
Veja bem, não estou dizendo que isso deveria ser banido da programação, mas é muito raro você ter que fazer isso. Eu nem consigo te dar um exemplo agora onde seria adequado.
Posso te dar um exemplo hipotético em cima de um trecho hipotético, mas ele não deveria contar. O seu código pode ter sido feito para ilustrar apenas. Ele é um caso em que pode ter sido útil sim. Mas só por uma razão, a exceção não foi tratada efetivamente, por isso provavelmente ela terá que ser tratada em outro lugar, aí precisa que ela continue sendo propagada.
Na verdade, não é bem assim, ela lança outra exceção completamente diferente perdendo a informação original de onde ocorreu a exceção, portanto se não é o que queria fazer, e geralmente não é, isso é um erro.
Se não pode fazer nada útil com a exceção não a capture. Simples assim. Só capture para tratar de verdade. Se não pode fazer nada aí, deixe para outro local do código tratar.
Tratar significa que vai resolver a questão ou vai quebrar a aplicação.
Novamente, pode ter um caso que isso não deveria ser feito assim? Claro, pode ter, mas é raro. Você pode justificar porque precisou capturar e só imprimir o stack trace sem resolver a questão ou quebrar a aplicação? Se puder, então pode usar.
Tudo em código precisa ser justificado. Voltamos ao começo da resposta.
Programar é entender o que está fazendo e não só jogar códigos quase aleatórios.
Porque ele fez isso é algo que pode perguntar para ele. Pode ser só ilustrativo.
Muitos exemplos que encontramos por aí, até, e principalmente, em documentação são só para mostrar o mecanismo funcionando, não é uma receita de código para copiar e colar. E isso a maioria das pessoas não sabem. Esses códigos mostram como funciona e não qual é a "melhor prática".
É parecido com exemplo de OOP que Cachorro herda de Animal, onde todo mundo aprende OOP errado porque é um exemplo para ilustrar simbolicamente a herança de um jeito que as pessoas já entendem o mundo, e não como você deve fazer herança em código real.

Quando ele lança a exceção no "throw e", ele está lançando o método criar arquivo de novo?

Não. Não é possível lançar um método. Ele está lançando uma exceção em um local diferente. Não está criando uma nova exceção, está usando a que já recebeu.

Por que precisa lançar ela de novo para tentar criar um novo arquivo caso algo de errado?

Não está tentando criar o arquivo de novo. Pode ser a intenção, mas não faz isso em lugar algum. Poderia fazer. Poderia ter criado um loop que tente, talvez passando um tempo entre uma tentativa e outra, talvez contando quantas vezes pode retentar.
Eu sempre falo para capturar a exceção mais específica que pode fazer algo útil. Muita gente é contra isso sei lá porque, talvez só porque outras pessoas também o são. Se você não capturar algo específico não pode dar um bom direcionamento. O que é o mais específico necessário depende de cada caso.
Mais do que retentar a esmo, eu acho que deveria informar o usuário que a tentativa falhou para ele ver se pode fazer algo para resolver. Em grande parte dos casos falhará por algo que não se consertará sozinho.
Pode ser falta de permissão, espaço cheio, o dispositivo quebrou, e mais um monte de coisa. A IOException não diz o que é, porque ela não é a mais específica possível. Pode ser que tenha uma mensagem genérica nela que informe, e pelo menos mostrando o stack trace ajude, e aí uma nova tentativa seria interessante, mas é feio fazer isso, ter algo mais específico ajuda mais.
Na verdade, você poderia até mesmo interagir com o usuário aí. Mas quase sempre isso seria um erro. Não parece que em um bom código um método que só criaArquivo() deveria interagir com o usuário. Em grande parte dos casos você nem sabe se está interagindo com console, alguma GUI específica ou web ou até não ter um usuário para interagir.
Outra parte do código que sabe, deveria interagir. Deveria separar as responsabilidades.

E porque quando eu lanço esse throw e o método pede para eu declarar na assinatura o throws IOException mesmo tratando a exceção com try e catch?

O que são checked exceptions?
Usando as palavras-chave Throws e Throw

Uma das maiores desgraças das checked exceptions é isso, as pessoas capturam sem motivo para cumprir a exigência da linguagem. Só não capture, deixe que outro lugar capture:
import java.io.File;
import java.io.IOException;

class ExceptionTest02 {
    public static void main(String[] args) {
        try {
            criarNovoArquivo();
            System.out.println("Criou arquivo");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void criarNovoArquivo() throws IOException {
        File file = new File("arquivo\\teste.txt");
        file.createNewFile();
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que para cumprir a exigência de capturar eu coloquei outro throws IOException delegando a responsabilidade para outro método.
Eu poderia fazer o mesmo no main() e não precisaria usar o try-catch nem nele. Daria no mesmo exceto pelo detalhe que finalizaria com um erro, do jeito que está nesse código termina sem erro.
Eu não estou dizendo para fazer isso, estou capturando ali no final só para cumprir o exigido, o ideal seria fazer algo mais, que ajude resolver o problema, que informe melhor usuário de uma forma agradável, que interaja para tentar resolver. Mas se é pra quebrar depois disso então não é um grande problema, ainda mais em um exemplo para aprendizado.
Veja o comentário acima do hkotsubo sobre ter que verificar se o arquivo já existia, ou seja, além de lidar com a exceção tem que colocar alguma if para identificar outro tip ode erro. Conseguiram fazer uma API com o pior dos dois mundos.
Conclusão
Espero que depois ele mostre uma forma melhor de fazer. Eu sempre torço para cursos serem bons, não ensinem errado. Mas entendo que tem momentos para aprender a ideia básica. Mas como é frequente as pessoas se confundirem como se aquilo fosse o jeito certo de fazer, os cursos deveriam alertar melhor para o fato, talvez dizendo que não está completo.


A simple probability question about two types of cards

Question: There is a hidden box that contains two different types of cards--1 Card A and 1 Card B. Card A has both sides of the card red while Card B has one side red and the other blue. If you randomly picked a card and saw a red face, what is the probability that this card is of type A. Using the conditional probability equation, I seem to be getting $0.5$ as the answer, however, the true answer is $2/3$. And I dont see how you can get $2/3$?
Comment: @Aapeli There is only one type A and one type B in the box
Comment: You don't ever mention what proportion are of type A and what are type B.
Answer: I understand there are as many A cards as B cards in the box.
By conditional probability: $$\begin{align}\quad\Pr(A \mid\text{red}) & = \dfrac{\Pr(A \cap \text{red})}{ \Pr(\text{red})} \\ ~ & = \dfrac{\Pr(A)\Pr(\text{red}\mid A)}{\Pr(A)\Pr(\text{red}\mid A)+\Pr(B)\Pr(\text{red}\mid B)} \\ ~ & = \dfrac{{^1\!/\!_2}\cdot 1}{{^1\!/\!_2}\cdot 1+{^1\!/\!_2}\cdot{^1\!/\!_2}} \\ ~ & = \dfrac{{^1\!/\!_2}}{{^3\!/\!_4}} \\ ~ & = {^2\!/\!_3}\end{align}$$
cheers
Comment: Isn't the probability that it is of one face red and the other also red (0.5)^2
Comment: @John  Pr(get a red face) = Pr(card A) or Pr(card B and its red side) = 1/2 + 1/2.1/2 =3/4
Comment: I am referring to the Pr(AandRed). If you get a red face, it has a 0.5 chance and if it is also red on the other side then it is (0.5)^2
Comment: Pr(A and red) =Pr (to get simultaneously A and red)= Pr(to get a red card A) =Pr(to get a card A) (because A both faces are red), =1/2
Comment: I assumed that the two events were independent. Thanks
Answer: If we assume there are the same number of type 'A' cards as type 'B' cards then if you pull a card at random and look at one side only there are 4 equally likely results
Red or Red from card A.
Red or Blue from card B.
By observing a red face we can eliminate one of these options so we now have only 3 equally likely results and of these how many are using Card A?
Answer 2 of the 3 equally likely outcomes use card A so probability is $\dfrac{2}{3}$.


Better understanding of the pre sheaf kernel

Question: I'm currently reading chapter II of Hartshorne's algebraic geometry and there defines kernel ,cokernel.....etc. everything is define on sheaf of Abelian groups.
we know that for  a sheaf morphism $\phi :\mathcal{F}-\mathcal{G}$ kernel is $\ker{\varphi}$ for sheaf of  abelian group or ring ...etc. But if $\mathcal{F},\mathcal{G}$ are sheaf of sets, then what is the equivalent condition of kernel .
Thanks in advance.
Comment: If the topological space $X$ you're working over, then sheaves of sets, groups, etc are just sets, groups, etc.

What is the kernel for a map of sets? I don't know of a nice notion of kernel even in this setting.
Comment: The kernel of $\phi$ is the equalizer of $\phi$ and $0$. Is that what you mean? See https://en.wikipedia.org/wiki/Equaliser_(mathematics)
Answer: If $C$ is an abelian category (i.e. if it has kernels, cokernels, and some additional properties), then the category of sheaves of elements of $C$ is itself an abelian category, by the constructions you mentioned. This means sheaves of abelian groups, rings, modules, etc. have well-defined kernels and cokernels. However, $\text{Set}$ is not an abelian category, and so we should not expect the category of sheaves of sets to be abelian, either.


find out total balance of employee

Question: SELECT c.cName,(c.nOpBalance+CT.nAmount) DrAMount
FROM Customer c
INNER JOIN Client_Transaction CT ON CT.nClientPk = C.nCustomerPk
AND CT.cTransRefType='PAYMENT'
GROUP BY c.cName

How can I find out total amount .Please help me on this thanks in advance.
Below is the data from the client transaction table data.
`nTransPk`, `dTransDate`, `nClientPk`, `cClientType`, `nTransRefPk`, `    cTransRefType`, `nAmount`, `cRemarks`
(1, '2015-04-06 00:00:00', 75, 'Samsu Bhai', 0, 'PAYMENT', 50, 'rere'),
(2, '2015-04-14 00:00:00', 30, 'PROVIDER', 0, 'PAYMENT', 12, 'fdf')

And that's the customer table:
`nCustomerPk`, `cName`, `cAddress`, `cCity`, `cState`, `cPincode`, `cContactPerson`, `cWorkPhone`, `cHomePhone`, `cCellNo`, `cFaxNo`, `cEmail`, `cLstNo`, `cCstNo`, `cTinNo`, `dLstDate`, `dCstDate`, `nOpBalance`, `dOpBalDate`, `bIsActive`
(2, 'SAURABH', 'NA', 'Udaipur', 'Rajasthan', '313001', '', '', '', '434344545', '', '45Q2452Q45DFBSDGQ345Q3456', '', '', NULL, '2015-04-23 00:00:00', '2015-05-05 00:00:00', 99999999, '2015-04-23 00:00:00', 1),
(3, 'Nitin', 'D', 'Jaipur', 'Rajasthan', '444', 'c', '45', '545', '545', '45', 'firstname.lastname@example.com', '', '', NULL, '1900-01-01 00:00:00', '1900-01-01 00:00:00', 1111, '1900-01-01 00:00:00', 1),

Comment: What is the problem that you are having?  Please include sample data and desired results in your question.
Answer: You need to use SUM() to total all the amounts for each group. Use LEFT JOIN instead of INNER JOIN to get customers with no transactions.
Select c.cName,SUM(c.nOpBalance+IFNULL(CT.nAmount, 0)) DrAMount
From Customer c
LEFT JOIN Client_Transaction CT ON CT.nClientPk = C.nCustomerPk
    AND CT.cTransRefType='PAYMENT'
Group By c.cName

Comment: but ct.namount somtime may be null in this case its not showing balance
Comment: You have to use `LEFT JOIN` to get clients with no transactions.

find out total balance of employee


MCMC proposition from an underlying distribution

Question: I'm a newbie when it comes to MCMC. I'm working with a program that is used to fit a number of parameters given some data. The documentation is leaving me a bit confused, I'm hoping someone here could help put me on the right track.
For example, say I am fitting 3 parameters, $\alpha$, $\beta$, and $\gamma$. I have some knowledge of the underlying distributions of $\alpha$ and $\beta$, but not $\gamma$.
This program allows me to input my prior knowledge of these distributions by indicating the underlying distribution of each parameter. For example, I can tell the program:
$\alpha$~$N(0,1)$
$\beta$~$exponential(3)$
$\gamma$~$uniform(0,\infty)$
After writing up a control file indicating these parameters and distributions, I need to set up the 'MCMC' run. There are a number of different moves I can choose from, including (copied from the manual):

log uniform proposal: A Metropolis-Hastings move for continuous scalar variables that are constrained to be positive only
  (or negative only). If x is the current state then the proposed state is $xe^U$, where $U$ is simulated from a continuous uniform distribution with range 0 ± half-width. This move is equivalent to the uniform proposal on the logarithmic scale.
logit uniform proposal: A Metropolis-Hastings move for continuous scalar variables that are constrained between 0 and 1.
  If x is the current state then the proposed state is
  $\frac{1}{1+e^{-log{\left(\frac{x}{1-x}\right)-U}}}$ where $U$ is simulated from a continuous uniform distribution with range 0 ± half-width. This move
  is equivalent to the uniform proposal on the logit scale.
uniform proposal: A Metropolis-Hastings move for continuous scalar variables. If $x$ is the current state then the proposed state is $x$ + $U$, where $U$ is simulated from a continuous uniform distribution with range 0 ± half-width.

Now I'm confused by this, because it appears the moves are determined by the MCMC proposals, not the underlying distributions that I previously defined.
I'm hoping someone can help me understand how (if) the underlying distributions inform the proposed jumps in the MCMC.
Thanks!
Comment: Gamma uniform (0,infinity) is noninformative but also is an improper prior.
Comment: Hi Michael. Thanks for your comment. Is there a different way I should represent this uniform distribution? The program does allow for improper uniform distributions.
Comment: Yes you could use a uniform on [a,b] if you have prior information to support that.
Comment: For some parameters I have no knowledge, therefore used an improper uniform priors. However, my real concern is how the MCMC sampling is informed by the underlying distributions. The descriptions of the MCMC sampling makes it seem like they aren't...
Comment: A uniform [a,b] is uniformed also.  It only restricts the parameter to be contained in the interval but shows no preference for any point.
Comment: Yes, I'm aware of that. I don't believe that this discussion is related to my question, though. Or am I missing something? Sorry, I don't mean to be rude, I do appreciate you replying to my question.
Comment: Sorry but you said you are a newbie to MCMC. So I was just trying to help.  I don't know enough about the software you are using to implement the Metropolis-Hastings algorithm.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/52501/discussion-between-lstbl-and-michael-chernick).
Answer: Perhaps you are confusing the prior distribution with the proposal distribution.
The prior distribution is part of the posterior distribution. In particular, the posterior distribution is proportional to the product of the likelihood $p(y|\theta)$ and the prior distribution $p(\theta)$:
$$
p(\theta|y) \propto p(y|\theta)\,p(\theta) ,
$$
where $y$ denotes the data and $\theta$ is the unknown parameter (or parameters). In your case $\theta = (\alpha,\beta,\gamma)$. As you say, you have some prior information. In particular, $\alpha \sim \textsf{N}(0,1)$ and $\beta \sim \textsf{Exp}(3)$. You also have some prior information about $\gamma$, namely $\gamma > 0$. Beyond that sign restriction, you wish to use an improper prior $p(\gamma) \propto 1_{[0,\infty]}(\gamma)$.
The proposal distribution plays a role in the Metropolis-Hastings MCMC sampler that is used to make draws from the posterior distribution. Let $q(\theta'|\theta)$ denote the density of the proposal distribution for $\theta'$ given $\theta$. Let $\theta^{(r)}$ denote the current state of the Markov chain. Then
$$
\theta^{(r+1)} = \begin{cases}
\theta' & R \ge u \\
\theta^{(r-1)} & \text{otherwise}
\end{cases}
$$
where $u \sim \textsf{Uniform}(0,1)$ and
$$
R = \frac{p(y|\theta')\,p(\theta')}{p(y|\theta^{(r)})\,p(\theta^{(r)})} \times \frac{q(\theta^{(r)}|\theta')}{q(\theta'|\theta^{(r)})} .
$$
It appears the software allows you to choose different proposal distributions depending on the prior bounds of the parameters. Since $\alpha \in (-\infty, \infty)$ you would choose the uniform proposal for it. Your other two parameters are constrained to be positive, so you would choose the log-uniform proposal for them.
(I am not endorsing these proposal distributions; I am only trying to help you understand what I think the user guide is trying to tell you.)


A woman has 10 friends

Question:
A woman has $10$ friends, of whom $5$ are women and $5$ are men. In how many ways can she invite three or more to a party? In how many ways can she invite three or more to a party if she wants the same number of men as women (including herself)?

My attempt so far:
I am unsure on how to answer if there are $3$ or more people.
If she chooses $3$ men and two women = $6$ people including herself
$\dbinom{5}{3}=10$ $\dbinom{5}{2}=10$
The answer would be $20$ different combinations?
Comment: If she invites $3$ men and $2$ women, there are $\binom{5}{3}\binom{5}{2} = 100$ combinations.  When choices are made independently, you should multiply.
Answer:
A woman has ten friends, of whom five are women and five are men.  In how many ways can she invite three or more to a party?

Hint:  In this case, the gender of the friends she invites does not matter.  Therefore, the woman invites three of her ten friends or four of her ten friends or five of her ten friends or ...

A woman has ten friends, of whom five are women and five are men.  In how many ways can she invite three or more to a party if she wants the same number of men as women (including herself)?

Hint:  Since she invites at least three friends, she must two of the five men and one of the five women or three of the five men and two of the five women or four of the five men and three of the five women or all five men and four of the five women.
The Multiplication Principle states that when one task can be performed in $m$ ways and a second task can be performed independently of the first in $n$ ways, then there are $mn$ ways of performing both tasks.
The number of ways the woman can select which three men to invite and which two women to invite are independent.  Therefore, the number of ways of inviting three of the five men and two of the five women to the party is
$$\binom{5}{3}\binom{5}{2}$$
The Addition Principle states that if one task can be done in $m$ ways and a second task that cannot be done at the same time as the first task can be done in $n$ ways, there are $m + n$ ways of performing one of these tasks.
For instance, the woman can invite three of her ten friends in $\binom{10}{3}$ ways.  She can invite four of her ten friends in $\binom{10}{4}$ ways.  Therefore, the number of ways the woman can invite three or four of her ten friends is $$\binom{10}{3} + \binom{10}{4}$$
The word and is an indication that you should multiply, while the word or is an indication that you should add.

A woman has 10 friends


Utility optimization question

Question: Having trouble with how to put this together. I have an answer key, but the individual steps I am struggling with.
Two period economy with a representative consumer that maximizes the utility function
$$
U(C_1,C_2)=\ln(C_1)+\beta\ln(C_2)
$$
Subject to the lifetime budget constraint
$$
\frac{C_1+C_2}{(1+r)}=W
$$
Where $0<\beta<1$ and $C_1$ and $C_2$ are consumption levels in period 1 and 2 respectively. $r$ is the real interest rate and total wealth $W$ is the sum of housing wealth H and the present discounted value of after tax life time income.
Derive the levels of optimal consumption in the two periods as a function of $W$. Provide economic intuition for the optimality condition.
In the solution, we have:
Let $R=(1+r)$. Maximize $U(C_1,C_2)$ subject to budget constrain. Substitute $C_2$ as a function of $C_1$ into the utility function. Take the FOC, derive the optimality condition
$$
U'(C_1)=\beta RU'(C_2)
$$
Can anyone step this out for me? Giving me some pointers on how to start the problem would be ideal, so I can work through the rest on my own, and perhaps ask for further assistance if I need it.
Comment: All the pointers that can be given have already been given: "Substitute C2 as a function of C1 (using the budget constraint) into the utility function. Take the FOC" (i.e. the first derivative and set it equal to zero).
Answer: You have the wrong life time budget constraint, it should be $$ \mathbf{C_1+\dfrac{C_2}{R}=W}\Rightarrow C_2=RW-RC_1$$
So the utility is $u(C_1)+\beta u(RW-RC_1)$. Take derivatives with respect $C_1$ to get the FOC.
Please do not use $U$ for the life-time utility and for the period utility, it will only confuse you more: $$U(C_1,C_2)=u(C_1)+\beta u(C_2)\text{ where } u(x)=\ln(x).$$

Utility optimization question


How to handle categorical predictors with too many levels?

Question: I think it may be a problem if we directly use dummy variable for a categorical predictor having hundreds of levels.
I have found one solution from the book 'Elements of Statistical Learning' (p.329). The solution is mentioned in classification tree sections. Specifically, the solution orders the levels of the categorical predictor by the number of occurrence of each level in one class, and then treats the predictor as an ordered predictors.
I wonder for models other than classification tree, such as linear regression, what would be proper ways of handling categorical predictors with too many levels.
I found an old post asking similar questions, but no answers have been posted:

Categorical logit Predictor with too many different levels
Comment: Your country-scenario seems perfectly suited for a multilevel aka hierarchical aka mixed model, where participants would be located on level 1 and countries on level 2 treating country as a random factor. If the example you gave matches your actual research question, go for multilevel; if not, maybe you can provide an example closer to your question?
Comment: You can add country-level predictors to your model (e.g., size, wealth, continent), but these can - without another superordinate level - only be estimated as fixed effects, i.e., the slope is modeled for ALL countries. Having hypotheses and models for every single country probably makes no sense. Either focus on a few, or build one multilevel model including all countries with broader hypotheses (e.g., country wealth increases the prob of people answering 'yes').
Comment: 1) Can you provide us with the categorical predictor of interest (or a similar example) so that we know what these "hundreds of levels" mean? 2) What is the distribution of the outcome throughout these levels? Thanks!
Comment: Suppose we have a data-set collecting the answer (Yes or No) to a question from participants of different regions, represented by their county name. Is it possible to add the factor county name as a predictor to predict the probability of people answering 'Yes'? I just make up this example and I hope it makes sense.
Comment: @hajöpe, I could understand your reasoning of using mixed model, because I tend to believe the collected response will have correlations within each county. And using the county as random effect term could model such correlation. But if I use it as random effect I would be estimating the variance of the random effect (suppose I add the effect as the intercept, which is assumed normal distribution), so I could not give prediction on specific county. Also, can you explain a bit more why using random effect model could address the questions of predictors with too many levels?
Comment: Fused lasso or:  https://stats.stackexchange.com/questions/227125/preprocess-categorical-variables-with-many-values/277302#277302
Answer: I can't see that ordering the levels by frequency creates an ordinal variable.
Shrinkage is necessary to deal with this problem, either by using penalized maximum likelihood estimation (e.g., R rms package's ols and lrm functions for quadratic (ridge) L2 penalty) or using random effects.  You can get predictions for individual levels easily using penalized maximum likelihood estimation, or by using BLUPS in the mixed effects modeling context.
Comment: Thanks for this clarification. I really appreciate it. Perhaps the ordering approach only works for classification tree. For your reference, this approach is explained on page 329 of the book element of statistical learning (http://www-stat.stanford.edu/~tibs/ElemStatLearn/)
Answer: If I understand your problem ( and the old post you linked too) - you are saying that some of the levels have very little data to accurately estimate the effect.
So either reduce the levels by "hand" (creating a new "other" level for all those levels with insufficient data) or what about using L2/L1 regularisation


Finding $\lim \limits_{x \to 0} \frac{1 - \cos x}{x}$, given $\lim \limits_{x \to 0} \frac{\sin x}{x} = 1$

Question: I am working on a textbook problem. The first step is to prove that
$$\lim \limits_{x \to 0} \frac{\sin x}{x} = 1$$
(which I did). The exercise goes on

Use this limit [i.e. the one above] to find
  $$\lim \limits_{x \to 0} \frac{1 - \cos x}{x}$$.

How can this be done? I don't really see a connection between the two...
Comment: Hint: $1-\cos x=\frac{1-\cos^2 x}{1+\cos x}=\frac{\sin^2 x}{1+\cos x}$.
Comment: Use $\cos  \theta=1-2\sin^2(\theta/2)$
Comment: @N.S.: A good comment for the OP to consider! I was just giving a hint on how to start.
Comment: @AndréNicolas: Maybe you should point that this is natural: $1-\cos(x)= 1- \sqrt{1-\sin^2(x)}$ and you rationalize....
Comment: More solutions to this limit are [here](http://math.stackexchange.com/q/420698/43351) and [here](http://math.stackexchange.com/q/36299/43351).
Answer: Using half-angle formula, we have $1-\cos x = 2\sin^2\frac x2$ so
$$
\lim\limits_{x\to 0}\frac{1-\cos x}{x} = 2\lim\limits_{x\to 0}\frac{\sin^2\frac x2}{x} = \lim\limits_{x\to 0}\frac{\sin\frac x2}{x/2}\cdot\lim\limits_{x\to 0}\sin\frac x2 = 1\cdot0 = 0
$$
where we used the fact that both limits exist.
Answer: $$
\begin{eqnarray*}
\lim_{x \to 0} \frac{1 - \cos{x}}{x}
&=& \lim_{x \to 0} \frac{(1-\cos{x})(1+\cos x)}{x(1+\cos x)}
\\ &=& \lim_{x \to 0} \frac{1-\cos^2 x}{x(1 + \cos x)}
\\ &=& \lim_{x \to 0} \frac{x\sin^2 x}{x \cdot x(1+ \cos x)}
\\ &=& \lim_{x \to 0} \frac{\sin x}{x} \times \frac{\sin{x}}{x}\times \frac{x}{1+\cos x} = 0 .
\end{eqnarray*}
$$
Answer: \begin{align*}
L = \lim_{x \to 0} \frac{1-\cos{x}}{x} &= \lim_{x \to 0} \frac{\sin^{2}{x} + \cos^{2}{x} -\cos{x}}{x} \\ &= \lim_{x \to 0} \cos(x) \cdot \frac{\cos{x}-1}{x} + \lim_{x \to 0} \frac{\sin^{2}{x}}{x} \\ &=-L \Rightarrow 2L =0 \Rightarrow L=0
\end{align*}
Comment: Aren't you presupposing the limit exists?
Answer: Using L'Hopital
$$\lim \limits_{x \to 0} \frac{1 - \cos x}{x} = \lim \limits_{x \to 0}\frac{(1 - \cos x)'}{x'} =  \lim \limits_{x \to 0} \sin x = 0$$
Comment: That seems quite a circular argument if you take the definitions of $\sin$ and $\cos$ from the unit circle. How do you know the derivative of $\cos x$ without using what you are trying to prove?


Verificar se GPS está habilitado em todas versões do Android?

Question: Eu utilizo este código para verificar se o GPS está habilitado para que exiba um dialog:
<code>            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
</code>
mas só funciona até a versão 19 se não me engano, gostaria de implementar para que funcione em todas as versões do android, mas não consegui, alguém me da essa ajuda ai, vlw!
Answer: <code>public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    }else{
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }

}
</code>


Standard errors of hyperbFit?

Question: I want to fit a hyperbolid distribution according to my notation:
\begin{align*}
H(l;\alpha,\beta,\mu,\delta)&=\frac{\sqrt{\alpha^2-\beta^2}}{2\alpha \delta K_1 (\delta\sqrt{\alpha^2-\beta^2})} exp\left(-\alpha\sqrt{\delta^2+(l-\mu)^2}+\beta(l-\mu)\right)
\end{align*}
I use the HyperblicDistr package, my R for the first step, the estimation of the parameters (data):
hyperbFit(dat,hessian=TRUE)

The output is

Now I transform the parameters to my notation:
hyperbChangePars(from=1,to=2,c(-0.002494,0.002035,0.090747,0.204827))

Which gives

Now, I want to calculate the standard errors of my parameters, if I do:
summary(hyperbFit(dat,hessian=TRUE))

I get

But these are the standard errors in case of the parameter notation I don't want. So my first question:

To which parameters (in my notation) do the standard errors belong? So what is the standard error of $\hat{\alpha}, \hat{\beta}, \hat{\mu}$ and $\hat{\delta}$?
The values stay the same, right, so they do not change or?
Comment: ok: I already noticed one big mistake: My "from" vector in hyperbChangePars is wrong, so I have to use the order of the output. But my question stays the same!
Answer:
Information about the relationship between $(\alpha,\beta,\mu,\delta)$ and $(\pi,\zeta,\delta,\mu)$ can be found in the following link:

https://github.com/sjp/GeneralizedHyperbolic/blob/master/R/hyperbFit.R
hyperbPi <- beta / sqrt(alpha^2 - beta^2)
zeta <- delta * sqrt(alpha^2 - beta^2)

Since the output of hyperbFit corresponds to the MLE, then they can be inverted directly using the aforementioned reparameterisation.
Although it is possible to calculate the corresponding errors for $(\alpha,\beta,\mu,\delta)$ using the delta method (if you do not know it, google will tell you), I think it requires a significant effort. I would rather go for using bootstrap as follows:

Obtain B bootstrap samples of the estimators of $(\pi,\zeta,\delta,\mu)$.
Transform those values into estimators of $(\alpha,\beta,\mu,\delta)$ using the reparameterisation mentioned above (you have to calculate it, recall that this is your thesis).
Obtain bootstrap intervals using the sample of estimators of $(\alpha,\beta,\mu,\delta)$.

The following R code shows how to obtain the intervals for $(\pi,\zeta,\delta,\mu)$. Once you calculate the reparameterisation you can easily obtain those for the parameters of interest.
n = length(dat)
B=10000

sampB <- data.frame(matrix(ncol = 4, nrow = B))

for(i in 1:B){
print(i)
dat1 <-sample(dat,n,rep=T)
sampB[i,] <- hyperbFit(dat1,hessian=TRUE)$Theta
}

# quantile bootstrap interval for pi
c(quantile(sampB[,1],0.025),quantile(sampB[,1],0.975))

# quantile bootstrap interval for zeta
c(quantile(sampB[,2],0.025),quantile(sampB[,2],0.975))

# quantile bootstrap interval for delta
c(quantile(sampB[,3],0.025),quantile(sampB[,3],0.975))

# quantile bootstrap interval for mu
c(quantile(sampB[,4],0.025),quantile(sampB[,4],0.975))

As it was already mentioned in one of the answers to your questions, the MLE of this family of distributions converge slowly. These issues are inherited by the bootstrap algorithm. Any method that gives you stable results is worthy of suspicion.
Moreover, the use of standard errors in this family is completely unreliable since the distributions of the estimators are quite asymmetric as shown by the histogram of the bootstrap samples
hist(sampB[,1])
hist(sampB[,2])
hist(sampB[,3])
hist(sampB[,4])

Comment: mh, I am not really  looking through this - I guess I have to refrain from using the std errors of the hyperFit output.
Comment: mh, but I do not like the bootstrap method, I already kicked it out because it gave me to much different results. These were not useable. So I did not get this from your answer: Is it possible to just convert those values from the output? And yes, how can I do this? I also did not get the answer to my first question: To what parameters do these std errors belong (in my notation)?
Comment: ok, I uploaded it again and I got a different name! BTW: Your name is also quite interesting, eh?
Comment: @StatTistician Good. If you are only interested in the standard errors of the MLE, then you will probably have to use the delta method, which in turns requires the calculation of the Fisher information. [This answer](http://stats.stackexchange.com/q/14471/24471) shows how to do it. I have included a code for the bootstrap part. You still have to work on the reparameterisation part. I have removed my comment about the name of your data set since it looks like you are innocent.

Standard errors of hyperbFit?


What argument to pass hook_update_n()?

Question: We have a custom module, mymodule, that we are using to create a custom block programmatically. We tried to do the following and it does enable the module successfully, but i get the following warning.
What is the argument that needs to be passed in?

Missing argument 1 for mymodule_update_8501()

mymodule.install
function mymodule_install() {
  // Run update on install.
  mymodule_update_8501();
}

function mymodule_update_8501(&$sandbox) {
  // Do something.
}

Answer: A hook_update_N implementation is generally supposed to be invoked by the system, not manually.
Instead of thinking of it as "run an update on install", you could think of it as "perform an action on both install and update". A fairly common pattern for that is:
function MYMODULE_install() {
  _MYMODULE_install_something();
}

function MYMODULE_update_8501(&$sandbox) {
  _MYMODULE_install_something();
}

function _MYMODULE_install_something() {
  // Shared functionality here.
}

You don't have to use a global function; you could implement the shared functionality in a service and make use of that instead. The point is to separate out the logic for what needs to be done, and consume it in the same way wherever you need to.
If you do want to continue with your current approach, just pass it any initialised variable - doesn't matter what it is if you're not using it, and if your code is the only caller, it won't have any side-effects.
Comment: we were discussing different scenarios and found that we should most likely use the "perform action on update". In testing, we found that if we ran it in both, the `mymodule_update_8501()` would fail because we already have a block with that same ID. Your response led to that conclusion and it is marked as such.

What argument to pass hook_update_n()?


Sharepoint authentication without using sharepoint development environment or service references?

Question: I am trying to access a local SharePoint site using a .net program and am having difficulties.
I don't want to use the SharePoint development environment (may have many developers work on this, and that is just one more thing to install).
I would also like to make this configurable so that I can change the site and list name without recompiling.  I don't think I can do that with the Service References.  If I can, how?
I also don't want the user to enter sharepoint validation information, I am ok with storing sharepoint login information in a .config file.
I believe I could do this with REST, but can't figure out how to create an AccessToken without using the Sharepoint development environment.
Any help would be appreciated.
Comment: Honestly, you've chosen the wrong application to mess with. SP is hard enough without trying to bypass the recommended development paths. Even doing REST development with SP is easier with VS and I hate VS. Isn't your SP integrated to the domain? If it is, you can ignore SP for the user stuff, just use Windows authentication. Sorry if that is rubbish, I do SP Online.
Comment: Thanks for the reply.  I may be close to figuring it out.  I'll post it if I do.
Comment: So you want to have developers dev without a local SharePoint environment?  It is going to be a terrible experience, and they will hate it. You really need a local SharePoint environment in order to develop, deploy and test properly. If your concerned about having on more thing to install, you will have a lot more issues to deal with not having a local SharePoint environment.
Answer: The main problem I was having was not understanding that you could put other types of credentials in the request.Credentials property.  Here is the code I created:
<code>    public bool CopyFileToSharePoint(string fileName, Stream fileStream)
    {
        var data = new byte[fileStream.Length];
        fileStream.Read(data, 0, (int) fileStream.Length);
        fileStream.Close();

        var sharePointPath =
            SharePointWebSiteUrl + "/_api/web/lists/getByTitle('" + SharePointListName + "')" +
            "/RootFolder/Files/add(url='" + fileName + "',overwrite='true')";

        var request = (HttpWebRequest) WebRequest.Create(sharePointPath);
        request.Credentials = new NetworkCredential(SharePointUserName, SharePointPassword, SharePointLoginDomain);
        request.Method = "POST";
        request.Accept = "application/atom+xml";
        request.Headers["X-RequestDigest"] = GetFormDigest(SharePointWebSiteUrl);
        request.ContentType = "application/txt";
        request.ContentLength = data.Length;
        request.GetRequestStream().Write(data, 0, data.Length);

        var response = (HttpWebResponse) request.GetResponse();
        return response.StatusCode == HttpStatusCode.OK;
    }
</code>
I'm sure it's not perfect, but it works.


How to return an array in .toString method

Question: How can I return an array in this .toString method of my Shelf class?
public class Book
{
    int wys, szer;
    String imie, tytul;

public Book(int wys, int szer, String imie, String tytul)
    {
        this.wys = wys;
        this.szer = szer;
        this.imie = imie;
        this.tytul = tytul;
    }

@Override
public String toString()
{
    return imie;
}

}

public class Shelf
{

int wys;
    private Book book[] = new Book[20];

public Shelf(Book[] ks, int j)
{
    for (int i = 0; i < ks.length - 1; i++)
    {

        this.book[i] = ks[i];

    }
}

@Override
public String toString()
{
    for (int i=0;i<book.length;i++)
    {
    return book[i].toString();
    }

}

}

Main class

public class Test
{

public static void main(String[] args)
{
Book ks[]={
            new Book (13,2, "Rhonda Byrne", "Sekret"),
            new Book(12, 1, "Graham Greene", "Monsignore Kichote"),
            new Book(19, 3, "Hugo Steinhaus", "Slownik racjonalny"),
            new Book(10, 4, "RE.M. Remarque", "Trzej towarzysze"),
            new Book(13, 3, "A.A. Milne", "Kubus Puchatek"),
            new Book(11, 4, "Paulo Coelho", "El Aquimista"),
            new Book(13, 5, "Mitch Albom", "Tuesday with Morrie"),
            new Book(11, 2, "John Fowles", "Mag"),
           };

    Shelf s = new Shelf(ks, 15);
    System.out.println(s);
}

}
It is doesn't want to compile if the return statement is in the loop.
It will compile if I return in that way:
return book[0].toString+book[1].toString... etc....

But how to do it automatically?
--->I Updated all of the code of a class.
Comment: You don't, you return a string from toString.
Comment: So, you have array `book[]`, and you want to create a matching `String[]` array from it? Or, you want to join `book[]` array's items to produce a single `String` you can return for `toString` method? Or something else? Please clarify the question, because the code in it now doesn't make enough sense to know what you actually want!
Answer: The Arrays utility class has a method to create a string from an array.
return Arrays.toString(book);
Comment: thanks, it works :) But this way gives me chars: "[" on the beginning and "]" on the end. Is it a way to delete this without using "\b"?
Comment: If you want to have a different format you need to write to code to make the string yourself.  Use a loop to iterate over the array and append each element to a `StringBuilder`
Comment: i dont know why, but it gives me a NullPointerException;/
Answer: public String toString()
So you must return a String.
I suggest using A StringBuilder and Appending to it in your loop.
  public String toString()
{
    StringBuilder sb =new StringBuilder();

    for (int i=0;i<book.length;i++)
    {
        sb.append(book[i].toString());
    }
    return sb.toString();
}

You are getting A NullPointerException Because of the way you initialize your Array
private Book book[] = new Book[20];

Change That to something like this:
   private Book book[] ;

public Shelf(Book[] ks, int j)
{
    book=new Book[ks.length];
    for (int i = 0; i < ks.length ; i++)
    {

        this.book[i] = ks[i];

    }
}

Comment: bro provide proper example and explanation of it
Comment: it gives me NullPointerException ;/
Answer: Maybe calling the method in a loop?
Then you need a parameter and you can use the method on every element of the array.
for (int i=0; i<book.length; i++) {

    toString(int i);

}

And the method:
public String toString(int i) {

    return book[i].toString();

}

Not nice, but maybe it helps.
Answer: This day and age, I would suggest something along these lines:
@Override
    public String toString() {
        return Arrays.stream(book).map(Book::toString)
                .collect(Collectors.joining(", "));
    }


Manufacture a topology on $\mathbb{N}$ such that the boundary of finite intervals consists of its extreme points.

Question:
Manufacture a topology on $\mathbb{N}$ such that the boundary of finite intervals consists of its extreme points.

The answer to this question correctly says this is impossible.  But I've set myself the challenge of doing it anyway.  Can this this impossibility be surmounted by assigning each integer a pair of points, one arbitrarily less than the other?
This is partly motivated by dissatisfaction with the conventional discrete topology of $\mathbb{N}$, partly as an exercise in learning topology concepts and testing my understanding of the subject, but I've also got it into my head that something similar to this might be of utility in the Parity Problem.  But that's just background... on to the actual question.
Let any integer $n$ be the union of two points $n_l,n_r$ such that $n=\{n_l\}\cup \{n_r\}: n_l\leq n_r$ and $n_r-n_l=\epsilon$
Now if the desired boundary of $A=\{a,a+1,a+2,...,a+n\}$ is to be $\{a,a+n\}$ (which is impossible under conventional rules) we actually have in this new sense its boundary is $\{\{a_l\},\{a+n_r\}\}$ and its interior is $\{\{a_r\},a+1,a+2,...,\{a+n_l\}\}$:
Does this achieve the stated aim of a topology on $\mathbb{N}$ in which the endpoints of a sequence of integers are the boundary?  Is this anything more than pointless exercise?
Answer: As you describe it, it is not a topology on $\Bbb N$ because the base set is not $\Bbb N$.  However, your set is actually $\Bbb N$ in disguise, as it consists of countably many discrete points in a total order.  We can make a bijection by taking $n_l \leftrightarrow 2n, n_r \leftrightarrow 2n+1$.  The difference in spacing between $\epsilon$ and $1-\epsilon$ does not matter because we have not talked about a metric.  You are then trying to define a basis of open sets as $[2k+1,2m]$ for $m \gt k$.  The closure of the topology under unions requires that $(-\infty,2k]$ and $[2m+1,\infty)$ must be open as well, so $[2k+1,2m]$ is closed and therefore clopen.  We therefore get the discrete topology with the points being $[2k+1,2k+2]$.  It is not $T_0$ because there is no way to distinguish $2k+1$ from $2k+2$, or in your original discussion, $n_r$ from $(n+1)_l$
Comment: Thanks. The question asks to make a topology on $\mathbb{N}$ such that the boundary of finite intervals consists of its extreme points so perhaps the answer is to augment the above with a metric whereby $d: \mathbb{N}_l\times\mathbb{N}_r\to\mathbb{N}_{>0}$ or pseudometric in which $d(x_l,x_r)=0$. Perhaps this gets closer to the objective?


Which are reasons to change the default VPS hostname?

Question: I'm configuring a VPS that I recently subscribed to and I follow other devs' blogposts to help me setting my own up. I often see them changing the VPS hostname. The default VPS hostname doesn't look very pretty (e.g. vps-1343-8332.myvpsprovider.cloud), so they change it to their domain name. For instance:
hostnamectl set-hostname --static www.yourdomainname.com

However, to my understanding, as long as DNS is resolving the domain names to the correct IPs, hostname has no influence at all on the hosted domain name.
Then I wonder, for what reasons do fellow devs change their default VPS hostname?
Answer: Prevent mistakes
Logging into productive systems interactively opens up ways to commit various dangerous mistakes. If $PS1 is configured so your shell prompt and window title is showing what machine you are working on, that better be something that helps you notice "whoops, i am on the wrong machine!"
A good server may include numbers, but should include a word that helps admins distinguish different machines.
Ease administration
Network configuration gets a lot simpler when each service can just default to one host name set in OS. In email context, you often want to greet other servers announcing your host name (matching your reverse name) that is demonstrating your actions are attributable to you.
Few servers will receive mail from *.myvpsprovider.example, as such host name has so far exclusively sent them spam.
Comment: How is the VPS hostname used in the context of email? Mail servers are also located from the DNS (MX records).
Answer: Changing the hostname assigned by the hosting provider to something matching your own organisation's naming convention is usually a good idea.
Predictable and memorable host names help humans remember and identify systems much more easily than the ip-address and will likely help prevent mistakes.
From a branding perspective you usually also want your servers to identify themselves as part of your domain, not the hosting providers.

Keep in mind that a hostname must uniquely identify a specific server and a server can (should) have only one hostname.

The forward DNS entry for the hostname should exist and the FQDN should point to the servers main ip-address. (Also see this Q&A)
That also implies that you usually use a domain that you actually own, not something you make up.
The name of the host does not need to be the same as the service running on that host.
I.e. avoid the situation where a single web server  is hosting multiple websites and that has the hostname www.example.com. You can spend hours checking and finding nothing wrong with that website before realizing that the issue is with "www other-site" running on www.example.com
You want to avoid recycling hostnames, it gets annoying fast when you need to distinguish individual hosts by "the old www.example.com" and "the new www.example.com" and similar such non-sense.
The hostname will be used in system prompts, banners, error messages , log files etc.
When you have for instance a cluster of web servers all with the same hostname www.example.com identifying the specific misbehaving node is unnecessarily difficult.
With forward DNS you can point an unlimited number of different and unrelated  host and domainnames to a server's ip-address, but for reverse DNS you can effectively only map the ip-address to a single hostname. Align the reverse DNS record with the hostname set in the server.
Comment: @user2923322  Two reasons : - reliable mail delivery , the typical mailserver will identify itself to the receiving smtp server by its host name and the receiver will do a reverse (and forward) lookup to see if the ip-address resolves to that hostname - and debugging client connections , frequently  error messages will convert the ip-address And you get *"connection refused for `user` from `hostname` "*
Comment: Thank you. Could you explain why you suggest to align the reverse DNS record with the hostname?


A lock has has buttons, $0$ and $1$. To open the lock, an 8 bit sequence must be entered.

Question: If your first try of opening the lock fails, what is the probability that your second try succeeds?
Is the answer $\frac{2}{256}$ because you get to try two combos, or is it $\frac{1}{255}$ because you get to try one combo from 255 remaining?
I'm confused and not sure which is correct
Comment: In this case I think the question includes sufficient thoughts from the asker. It's mainly a question of which understanding of the original problem is correct.
Answer: The probability that your second try succeeds given that the first failed is 1/255.  The probability of succeeding on at most two tries is 2/256.
Answer: Initially there are $256$ possibilities, the first failure disclose that the code is certainly not the right combination and should be avoided. Hence he should only choose $1$ out of the remaining $255$ possibilities.
The answer is $\frac{1}{255}$ assuming that the person has learned his lesson and remember the earlier combo to avoid.


Update Specific fields in a document record using MONGODB

Question: I am new to mongodb.So in sql to update the specific fields the query is
In sql::
update students set marks = 95, grade = 'A' where _id = '1234';

In mongo shell ::
db.students.update({_id:'1234'},{"$set":{"marks":95,"grade":'A'}},{multi:false});

Using mongotemplate , how can we acheive this. I have tried using the following code for single field update and it is working.
String uniqueId = student.getSection() + "#" + student.getRollNo();
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(uniqueId));
    Update update = Update.update("marks", student.getMarks());
    logger.info("[Updating the Student marks using the id=]["+uniqueId+"]");
    UpdateResult result =  mongoTemplate.updateFirst(query, update, Student.class);

But how we acheive to update grade also using mongo templete?
Note :: I want to update specific fields in the document , not replacing the entire document
Answer: Call .set(key, value)
Update update = Update.update("marks", student.getMarks()).set("grade", student.getGrade());

//Alternative
Update update = new Update().set("marks", student.getMarks()).set("grade", student.getGrade());

Comment: Hi @Valijon, thanks for the answer. It is working. But if i want to update the multiple fields without disturbing the existing fields, how can i acheive through pojo object ?. Is there any function like( saveorUPDATE like present in hibernate) ?
Comment: @user11790395 Give an example please


How to move scroll view up 100 pixels when button is clicked

Question: I have a scrollview and need to move 100 DP up when button click event is happening.
I'm using scrollTo (0,1) but not working properly.
Answer: Try something like this. Hope it will work
it px = (int) (100 * Resources.getSystem().getDisplayMetrics().density)
yourScrollView.scrollTo(0, px);

Answer: scrollTo(0,1) will bring you to height 1 of the ScrollView layout.
As far as I know, you cannot scrollTo using arbitrary amount of pixels in ScrollView (pls correct me if I'm wrong).
You could try having a View inside the ScrollView as a "guide" for your ScrollView where does it need to stop.
Example:
//inside your button onClick
yourScrollView.scrollTo(0, someView.getBottom());

This will make your ScrollView scrolls to the bottom of a View that you can put 100dp above.
Hope it solves your problem.


Proving $9$ divides $n^3 + (n+1)^3 + (n+2)^3$

Question: I'm trying to prove by MI. I have already distributed n+1, but now I'm stuck on how I can show 9 divides the RHS since $42n$ and $3n^3$ does not divide evenly.
$$(n+1)^3+(n+2)^3+(n+3)^3=3n^3+18n^2+42n+36$$
Answer: HINT:
Induction:
Let $f(n)=n^3+(n+1)^3+(n+2)^3$
$f(m+1)-f(m)=(m+3)^3-m^3=9(m^2+3m+3)$
So, $f(m+1)$ will be divisible by $9\iff f(m)$ is.
Check for the base case
Comment: Is there a rule that if 9|p(x) then 9|p(x+1)- p(x)
Comment: @wannabe_n00b, No, if any number $n$ divides $a-b$ and $b,n$  must divide $a$
Answer: $$(n-1)^3+n^3+(n+1)^3=3n^3+6n=3(n^3-n)+9n$$
Now $n^3-n=(n-1)n(n+1)$ is product of three consecutive integers, hence divisible by $3!$
Also, $$(n+1)^3+(n+2)^3+(n+3)^3=3n^3+18n^2+42n+36\equiv3(n^3-n)\pmod9$$
Comment: Could I prove this by simply showing mod 9 on p(n) and p(n+1) is the same, therefore p(n+1) is divisible by 9
Comment: @wannabe_n00b, Exactly. That's what is  http://mathworld.wolfram.com/Congruence.html
Comment: I didn't know you could have a negative remainder with modulus operator
Comment: @wannabe_n00b, Conventionally for $r=n%m 0\le r<m$. But, it is sometimes useful to set $-\dfrac m2<r\le \dfrac m2$
Answer: your term is equivalent to
$3(n+1)(n^2+2n+3)$
if $n\equiv 0\mod 3$ then $n^2+2n+3\equiv 0 \mod 3$
if $n\equiv 1 \mod 3$, then $n^2+2n\equiv 0 \mod 3$
if $n\equiv 2 \mod 3$ then $n+1 \equiv 0 \mod 3$
Answer: If the property is true for $n$, then it is true for $n+9$ (all three cubes will increase by a multiple of 9). So it suffices to check for $n=0,1,...8$.
$$0^3+1^3+2^3=9=1\cdot 9$$
$$1^3+2^3+3^3=36=4\cdot 9$$
$$2^3+3^3+4^3=99=11\cdot 9$$
$$3^3+4^3+5^3=216=24\cdot 9$$
$$4^3+5^3+6^3=405=45\cdot 9$$
$$5^3+6^3+7^3=684=76\cdot 9$$
$$6^3+7^3+8^3=1071=119\cdot 9$$
$$7^3+8^3+9^3=1584=176\cdot 9$$
$$8^3+9^3+10^3=2241=249\cdot 9$$
Actually, as you showed that the sum is a multiple of $3$, it even suffices to show that the average is a multiple of $3$ for $n=0, 1, 2$.
$$\frac{0^3+1^3+2^3}3=3=1\cdot 3$$
$$\frac{1^3+2^3+3^3}3=12=4\cdot 3$$
$$\frac{2^3+3^3+4^3}3=33=11\cdot 3$$
Comment: So if I factor out the 3, it will be proof that it is divisible by 9?
Comment: If you factor out the $3$ you need to prove that the remaining factor is a multiple of $3$: $9|3x\iff 3|x$. In your case, just prove that $n^3+14n$ is a multiple of $3$ for $n=0, 1, 2$.
Answer: $$9\Big|\Big(n^3 + (n+1)^3 + (n+2)^3\Big)\iff9\Big|\Big(3n^3+9n^2+15n+9\Big)\iff3\Big|(n^3+5n)\iff3\Big|\Big(n(n^2+5)\big).$$
It is obviously true when $3|n$.
If the property is true for $n$, then it is true for $n+3$, so it only remains to check that for $n=1,2$, $3\Big|(n^2+5)$.
$$3|6,\\3|9.$$


Como formatar campos de dinheiro no django?

Question: Tenho um campo no meu Django admin que recebe um valor em reais, porém eu gostaria que esse valor ficasse formatado e não recebesse mais que duas casas decimais.
tentei usar um javascript pra modificar a pagina do django admin, mas isso gera muitos side effects:
let valor = document.querySelector('#id_valor');
        let oldVal = '';
        valor.addEventListener('keyup', function(){
            let parts = this.value.split('.');
            console.log(parts)
            if (parts && parts[1] && parts[1].length > 3)
                this.value = oldVal;
                oldVal = this.value;
        });

Existe alguma maneira melhor de fazer isso no django?
Answer: Leonardo, no próprio model vc poderia fazer isso
dinheiro = models.DecimalField(max_digits=10, decimal_places=2)

caso o usuário coloque 3 casas ou mais, aparece mensagem de erro informando a quantidade máxima de casas decimais que se pode usar.
Comment: Eu já tenho esse decimal_places ativo, eu gostaria que  o usuário não conseguisse digitar mais casas decimais, para que ele nem chegue a ver esse erro.
Comment: Tenta usar esse plugin https://igorescobar.github.io/jQuery-Mask-Plugin


Regex no Web Scenario do Zabbix 4.2

Question: Como recuperar valores com regex do retorno de um web scenario no Zabbix que chama uma API. O Web Scenario é para testes de paginas web e APIs no Zabbix.
Eu já tenho a expressão regular que recupera o valor e segundo a documentação do Zabbix, preciso apenas passar a expressão dessa maneira: regex:\w{54} documentação, porém ele não recupera o response, ele não entende a expressão. Abaixo a configuração do step:
Erro:
Error: error in step variables "{access_token}=regex:[A-Za-z0-9]{54} {be}=Bearer ": cannot extract the value of "{access_token}" from response

Retorno da API, da qual eu preciso recuperar o access_token:
Comment: posta a parte do código referente ao erro. Assim fica mais fácil de entenderem e te ajudarem
Comment: então, não tem código em si, é td configurado no Zabbix, eu adicionei o response da API, talvez seja isso que vc quiz dizer.
Answer: Depois de analisar bem a documentação e achar um exemplo bem escroto:
E descobrir q não é igual esse exemplo, rs. De qualquer forma isso me ajudou, repare que após o content="(.. tem esse parênteses e foi ai que fiz o teste e deu certo, mas olha como ficou o resultado final:

Minha regra de expressão é: \w{54} e eu testei conforme manda a documentação abaixo, que devia ser assim: regex:access_token is (\w{54}), mas isso não funciona, pelo menos para o meu caso:

Resumo: Use a regex dessa maneira: regex:"(\w{54})" lembrando que estamos falando do Web Scenario do Zabbix e sua expressão regular deve ficar dentro dos parênteses.

Regex no Web Scenario do Zabbix 4.2


isolating function from a difficult equation using ln to show it's continuous

Question: can you please help me isolate  a function from a difficult equatation?
i need to prove that g(x) is continuous, and to do so, i need to isolate it to prove it using arithmetics of continuous functions.
i have $\left(\frac{\left(1+h\left(x\right)\right)^{\frac{1}{h\left(x\right)}}}{e}\right)^{\frac{1}{x}}=exp\left(\frac{h\left(x\right)}{x}g\left(x\right)\right)$
basically, both of them define f(x) so i compared them. h(x) is continuous on I that contains $x=0$, $h(0)=0,h(x)>-1,h(x) \ne 0$ for every $0 \ne x \in I$.
$f(x)=\left(\frac{\left(1+h\left(x\right)\right)^{\frac{1}{h\left(x\right)}}}{e}\right)^{\frac{1}{x}}$ is defined for every $0 \ne x \in I$.
i need to show that a continuous function in I, g(x), exists so that $g(0)=-\frac{1}{2}$ and $f(x)=exp\left(\frac{h\left(x\right)}{x}g\left(x\right)\right)$.
i don't know how to isolate g(x) from the equation, but i supplied all the details from the question. is isolating g(x) is the only way to prove continuity under the given conditions or is there a smarter way? (seems like a mclaurins polynom)?
basically i need help in isolating g(x), but if you think there's a smarter way to show that g(x) is continuous i would like to learn from it.
thank you very much and sorry for not being able to provide additional attemps as i'm stuck on how to get g(x) out of the first equation to prove it's continuous.
Comment: (For $x \ne 0$) take logarithm of both sides, and multiply by $x/h(x)$.  Then worry about what happens as $x \to 0$.
Comment: this is what i already know, what i don't know is how to do it lol
Comment: It simplifies quite a bit...
Answer: As hinted at in the comments, take logs.
$$\begin{align}\left(\frac{\left(1+h\left(x\right)\right)^{\frac{1}{h\left(x\right)}}}{e}\right)^{\frac{1}{x}}&=\exp\left(\frac{h\left(x\right)}{x}g\left(x\right)\right)\\\frac1x\log\left(\frac{(1+h)^{\frac1h}}{e}\right)&=\frac hx g\\\frac1x\frac1h\log(1+h)-\frac1x\log e&=\frac hxg\\\implies g&=\frac1{h^2}(\log(1+h)-h)\end{align}$$
Now take the limit as $x\to 0$
$$g(0)=\lim_{x\to 0}\left\{\frac{\log(1+h(x))-h(x)}{h(x)^2}\right\}$$
Then using the fact that $h(0)=0$,
$$\begin{align}g(0)&=\lim_{h\to 0}\left\{\frac{\log(1+h)-h}{h^2}\right\}\\
\text{(l'hopital)}\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,&=\lim_{h\to 0}\left\{\frac{\frac1{1+h}-1}{2h}\right\}\\
\text{(re-arrange)}\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,&=\lim_{h\to 0}\left\{\frac{-1}{2(1+h)}\right\}\\
&=-\frac12\end{align}$$
Comment: thank you so much! i understand what i did wrong and i'm glad that the way i wated to prove is correct, even though i didn't know how to take log correctly.

thank you so much again!


Continuous Interest with Continuous Withdrawal

Question: A person places an initial deposit of 25000 in an account with a rate of 5% per year, compounded continuously. The person continuously withdraws 700 per year from the account. Find the value of the account at time t after the initial deposit.
I get this linear DE. Is the question just a matter of solving this equation?
$$dA/dt = (0.05)A - 700$$
so $$ln(A-14000)^{20} = t + C$$
I greatly appreciate any help
Comment: So yes, you need to solve $dA/dt=0.05A-700,A(0)=25000$. That exponent of $20$ makes me a little bit uneasy. To me you have $\frac{dA}{0.05A-700}=dt$, or equivalently $\frac{dA}{A-14000}=\frac{dt}{20}$. Alternatively you could get the factor of $20$ from the "du" upon integration by substitution. Either way you're going to want to move it to the other side so that you wind up with $Ce^{t/20}=\dots$
Comment: You look good so far. Since the initial deposit is 25000, you get that when $t = 0$ you have $A = 25000$. So plug that in to your equation to solve for $C$.
Comment: Ian is right, it makes more sense to put the 20 outside the logarithm like this $20 \ln(A - 14000) = t + C$
Comment: I like questions with some nice background.  More fun to do IMO.
Comment: Thanks for the help. So we get C = 11000?
Comment: That depends on how your $C$ appeared, but if you mean $A=Ce^{t/20}+14000$ then yes $C=11000$. (Note that this $C$ is not the same as the $C$ that appeared immediately from the integration.)
Answer: I don't know how you did your calculations, but saw this question at the same time that I had the thought "how do I get the most of my money?", so I did what anyone would do, and dusted off my Calculus book and quickly found that an equation of the form
$\frac{dy}{dx} + p(x)y = q(x)$ (with $x$ as time in years)
is a first order linear non-homogeneous differential equation and that is the same as your equation given that we set
$p(x)=-r=-0.05$. (the rate)
and
$q(x)=U_{flow}=-700$. (denoting the flow in on the account)
The book had two methods for solving this, and we can use the one with an integrating factor $\mu(x)$ which can be any antiderivative of $p(x)$ so we can set the constant to $0$ giving us
$\mu(x)=\int p(x)dx=-rx$
The solution comes from multiplying both sides by $e^{u(x)}$ such that the left-hand side will be the derivative of $e^{\mu(x)}y$
$\frac{dy}{dx} + p(x)y = q(x)$
$\Leftrightarrow e^{\mu(x)}\left(\frac{dy}{dx} + p(x)y\right)=e^{\mu(x)}q(x)$
$\Leftrightarrow \frac{dy}{dx}\left(e^{\mu(x)}y\right)=e^{\mu(x)}q(x)$
$\Leftrightarrow e^{\mu(x)}y=\int e^{\mu(x)}q(x)dx$
To solve the integral we use a substitution $v=-rx$ and $x=\frac{-v}{r}$
$\int e^{\mu(x)}q(x)dx=\int e^{-rx}U_{flow}dx=\int e^v \frac{-U_{flow}}{r}dv=\frac{-U_{flow}}{r}\int e^vdv$
and this innermost integral is easy to solve. We get that
$\int {e^v}dv=e^v+C = e^{-rx}+C$
where $C$ is a constant that soon can be solved for using our starting money
$b_{start}=y(0)=25000$.
We now have our function
$e^{-rx}y=\frac{-U_{flow}}{r}(e^{-rx}+C)$
$\Leftrightarrow y=\frac{-U_{flow}}{e^{-rx}r}(e^{-rx}+C)$
and with $x=0$ we get that
$b_{start}=\frac{-U_{flow}}{r}(1+C)$
$\Leftrightarrow C = \dfrac{b_{start}\cdot r}{-U_{flow}}-1$
Inserting $C$ into the equation and simplifying, we get our final equation
$y = b_{start}e^{rx}+\frac{U_{flow}}{r}\left(e^{rx}-1\right)$.
You should be able to simply insert whatever values you want here and compute it. If you plot this function, you will see that time is a very big factor in getting rich fast. So, I apologize for answering 3 years later during which you could have made \$1780 and had in your hand \$26780 by now.
(please let me know if I've made any mistake)


Função Javascript não roda Online

Question: O código abaixo só funciona em localhost , online não funciona, isto é, funciona perfeitamente na minha máquina, quando transfiro para o servidor , nada disso funciona, ja quebrei a cabeça e não consegui solucionar.
DETALHE! - O arquivo.js esta dentro do diretório raiz do http://loacalhost sem caminhos intermediarios, observe:

Realizei testes local, com os três tipos citados acima e todos se saíram bem. Já no servidor http://xpg.uol.com.br tenho feito da mesma maneira deixando-o na raiz, porém sem sucesso.
Numa nova tentativa, fiz a inclusão do conteúdo do arquivo.js dentro do documento HTML(página index.html), mesmo assim, sem chance.
Em outra tentativa com caminho absoluto, relativos a configuração do servidor, sendo:

.. funfa legal quando posto em localhost caso contrário ... nem pensar.
Enfim, me parece estar no escopo da função ou até mesmo na colocação da mesma na página.
Gostaria de entender onde estou errando. Agradeço desde ja, ajuda de todos.
Comment: Tem a ver com os caminhos relativos e configuração do servidor, para resolver isso use caminho absoluto, isto é: www.meusite.pt/public/js/bootstrap.js
Comment: Como fica a url em produção do import?
Comment: Ola, Em colocar na mesma pasta da pagina e usar  não funciona? qual é o erro no console?
Comment: Se estiver usando o Chrome, aperte F12 e veja se tem uma bolinha com um 'x' branco mostrando que tem erros, clique nele e diga o que aparece.
Answer: A todos que comentaram em suma resposta à pergunta, cheguei a conclusão. Foi preciso alterar as seguintes linhas:
errado onclick="nome(txt)"
retirei o txt não era necessário fazer referência ao <input type="text" id="txt"/>, e ficou assim:
onclick="nome()"
também:
errado document.all.id.value;
que agora, esta escrito assim:
document.getElementById('id').value;

Pronto!
Por motivos que desconheço, depois de modificar, a Função Javascript passou a funcionar tanto no lado Cliente quanto no lado Sevidor.

Função Javascript não roda Online